tags:

views:

236

answers:

3

I have a simple from with 2 radio buttons and I need to get their values if they are checked.

       <form class="descriptions" id="collection"  method="post" action="">
                          <table width="200">
                              <tr>
                                <td>
                                  <label>Collection</label>
                                  <input type="radio" value="collection" name="collection" />
                       </td>
                                <td>
                                  <label>Delivery</label>
                                  <input type="radio" value="delivery" name="collection"    />
                                </td>  
                            </tr>
                         </table>

                </form>

     var delivery = "";
     delivery = $('input:radio:checked').val();
if(delivery == 'delivery') {
 meal_deal7 = 11.49;
}else {
 meal_deal7 = 9.99
}

the value of meal_deal7 is always 9.99, am I doing sth wrong.

thanks

+1  A: 

Look at the following example courtesy this link
and make the necessary changes to your form;

<form name="orderform">
Which one is your favorite?<br>
<input type="radio" name="music" value="Rock" 
checked="checked"> Rock<br>
<input type="radio" name="music" value="Reggae"> Reggae<br>
<input type="radio" name="music" value="Pop"> Pop<br>
<input type="radio" name="music" value="Rap"> Rap<br>
<input type="radio" name="music" value="Metal"> Metal<br>
<input type="submit" onclick="get_radio_value()">
</form>
Kevin Boyd
Thanks, but that's javascript, I wanted to do it with jquery.
amir
A: 

Use javascript to get the value

var elemArray=document.getElementsByName('collection');
var value="";
if(elemArray.length>0){
for(var i=0;i<elemArray.length;i++){
if(elemArray.checked==true){
value=elemArray.value;
}
}
}else{
if(elemArray.checked==true){
value=elemArray.value;
}
}
Saeros
+5  A: 

you need to have your code in an event handler attached to each of the radio buttons so that the value of delivery variable is updated each time a radio button is clicked/checked

Working Demo - add /edit to see the code and play with the example.

The code

 $("input:radio[name='collection']").click(function() {
     var delivery = $("input:radio[name='collection']:checked").val();

     if(delivery == 'delivery') {
         meal_deal7 = 11.49;
     }
     else {
         meal_deal7 = 9.99
     }
 });

I'd be tempted to use a CSS class to identify the radiobuttons too

Russ Cam
Thanks, works just fine.
amir