Fetch selected value of dynamically-generated radio buttons with JS

Hello everybody,

I have a working function in JavaScript that iterates through a bunch of dynamically-generated form rows to see if a particular item is checked. I've use this solution to achieve that.

Now I have a more complex scenario. In this new table, also dynamically-generated, I have one checkbox to mark each item active or inactive (for that I'll use the above solution) and five radio buttons. I'm trying to come up with another foreach function that will give me the checked value for each item.

I'm trying to modify the original function but it will only give me 1 if the last radio button is checked for each item/line. How can I do this?

For the checkboxes, it's giving me something like this:

{"1":1,"2":1,"4":1,"5":1}

Open in new window


Which means that every item ID is active, but trying to use the same for the checkboxes gives me all IDs with values in 0. Here's the function:
var sistemaCriticidadEventosNivel={};
$('[id^="criticidadeventoradio-"]').each(function(){
	let id = $(this).attr("id").replace(/\D/g,'')
	sistemaCriticidadEventosNivel[id] = this.checked ? 1 : 0;
});
sistemaCriticidadEventosNivel = JSON.stringify(sistemaCriticidadEventosNivel);
console.log(sistemaCriticidadEventosNivel);

Open in new window


I know I should get the value of the radio button and not 1 or 0 but my brain can't process it right now.

Any thoughts? Thanks in advance!
LVL 6
Cesar AracenaPHP EnthusiastAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Cesar AracenaPHP EnthusiastAuthor Commented:
Ok, after a break I found it using the following:

var sistemaCriticidadEventosNivel={};
$('[id^="criticidadeventoradio-"]').each(function(){
	let id = $(this).attr("id").replace(/\D/g,'');
	if ($(this).prop('checked')) {
		sistemaCriticidadEventosNivel[id] = parseInt(this.value);
	}
});

Open in new window

Cheers!

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.