Reputation: 33
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?
Upvotes: 3
Views: 3891
Reputation: 357
You could get the name attribute from an onchange event (using jQuery)
// Onload handler
$(function() {
// Get all radio buttons and add an onchange event
$("input[type=radio]").on("change", function(){
// Output a message in the console which shows the name and state
console.log($(this).attr("name"), $(this).is(":checked"));
// Trigger the onchange event for any checked radio buttons after the onload event has fired
}).filter(":checked").trigger("change");
});
Upvotes: 1
Reputation: 79049
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());
Upvotes: 1
Reputation: 5490
you can use a parent div with id="anything"
now using jquery selector $('#anything input[type="radio"]:checked').val()
you can achieve that
Upvotes: 0
Reputation: 15376
Try this:
$('input[type="radio"]:checked')
as in:
alert( $('input[type="radio"]:checked').val() );
Upvotes: 3