Fetch selected value of dynamically-generated radio buttons with JS

Cesar Aracena
Cesar Aracena used Ask the Experts™
on
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!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
PHP Enthusiast
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!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial