May 29, 2013
How to get value of radio button with dynamically generated name
Daniel Young’s Question:
I have a whole bunch of radio buttons with dynamically generated names like below:
<input type="radio" id="Red<?php echo $wineID; ?>" name="category<?php echo $wineID; ?>" value="Red" <?php if ($category == "Red") { ?>checked="true"<?php } ?>>
<label for="Red<?php echo $wineID; ?>">Red</label>
<input type="radio" id="White<?php echo $wineID; ?>" name="category<?php echo $wineID; ?>" value="White" <?php if ($category == "White") { ?>checked="true"<?php } ?>>
<label for="White<?php echo $wineID; ?>">White</label>
<input type="radio" id="Sparkling<?php echo $wineID; ?>" name="category<?php echo $wineID; ?>" value="Sparkling" <?php if ($category == "Sparkling") { ?>checked="true"<?php } ?>>
<label for="Sparkling<?php echo $wineID; ?>">Sparkling</label>
I need to get the selected value and add it into my dataString for an ajax call to update my database. How can this be done using jQuery?
You can use attribute selector to get the element
$('input[name="category<?php echo $wineID; ?>:selected"')
However this uses a PHP inline script, so it will only work if rendered at the page load.
Or easiest would be:
console.log($(":radio:selected").val());