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:


Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!