0

I'm try to pass the from value (radio button) via ajax. The value sent but wrong. I have 4 radios but the form keeps sending the first value (==1). Could you guys please give me some suggestions. Why it happening?

Here's my code:

<ul class="nav nav-list">   
<li><label for="1"><input type="radio" name="vote" id="1" class="choice" value="1">&nbsp;Choice 1</label></li>  
<li><label for="2"><input type="radio" name="vote" id="2" class="choice" value="2">&nbsp;Choice 2</label></li>
<li><label for="3"><input type="radio" name="vote" id="3" class="choice" value="3">&nbsp;Choice 3</label></li>
<li><label for="4"><input type="radio" name="vote" id="4" class="choice" value="4">&nbsp;Choice 4</label></li>
    <li class="divider"></li>
    <li>        
        <div id="vote_loading" style="display:none">loading...</div>
        <div id="vote_result"></div><button class="btn btn-small btn-success" type="button" onClick = "voting()"><i class="icon icon-thumbs-up icon-white"></i>&nbsp;Vote</button>
    </li>
</ul>
<script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
    //voting
    function voting(){
         var choice = $('.choice').val();
         $.ajax({
             type: "POST",
             url: "inc/vote_chk.php",
             data: {choice:choice}
             }).done(function(result){
             $("#vote_loading").slideUp("slow");
             $("#vote_result").html(result).slideDown("slow");
         });
    }
    </script>

By the way I'm using bootstrap. But it's no matter with the code.

Regards,

Wilf
  • 2,297
  • 5
  • 38
  • 82

4 Answers4

2

since you using a class that returns multiple values, its only returning one of them. To get the selected:

change

var choice = $('.choice').val();

to

var choice = $('.choice:checked').val();

I initially thought it was :selected to get the selected radio, but thats for select options. Combined other answers to not confuse people. :checked is used for radio buttons.

It should be noted, that it is technically faster to reference by the class rather than by a property of an element though if that matters to you.

Rooster
  • 9,954
  • 8
  • 44
  • 71
2

Try this:

var choice = $('input[name=vote]:checked').val();
brettkelly
  • 27,655
  • 8
  • 56
  • 72
  • ahhh. Nice call. I haven't used a radio button in a while. :checked is the proper pseudo selector thingy, not :selected. For radio buttons. – Rooster Aug 01 '13 at 20:23
1

You are trying to get the value of the class when you should be retrieving the value of the input. That's because many elements can share a class (even non-radio buttons could have class choice) but only one element can have the same name.

var choice = $('input[name="vote"]').val();
federico-t
  • 12,014
  • 19
  • 67
  • 111
0

have you tried?

$('input[name=vote]').val()
Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378