开发者

How to use method get value in "input[type=radio]"

开发者 https://www.devze.com 2023-03-19 09:40 出处:网络
I think I have an error in my code here - $(\'#form input[type=radio]\').val();. JS: <script> $(document).ready(function(){

I think I have an error in my code here - $('#form input[type=radio]').val();.

JS:

<script>
$(document).ready(function(){
   $('#btnSubmit').bind('click', function(){
      var option = $('#form input[type=radio]').val();
        if(!option){
            alert('Answer empty');
            ret开发者_如何学运维urn false;
        }
        $('#form').submit();
   });
});
</script>

HTML:

<form id="form" method="post">
    <input type="radio" id="option1" name="option1" />
    <input type="submit" name="btnSubmit" id="btnSubmit" value="submit" />
</form>


According to documentation you can use

$('input:radio').val();

for

<input type="radio"  name="r" value="radio1"/> 

Info:
http://api.jquery.com/val/
http://snipplr.com/view/9166/get-radio-button-value-using-jquery/
http://api.jquery.com/radio-selector/


$('#form :radio') is shorter.

But what if there are multiple radio inputs? Try using this instead : $('#form :radio:first')

And by the way, not really a PHP problem.


it seems fine to me accept your html...you are missing value attribute in your html

<input type="radio" id="option1" name="option1" value="15"/>

you can see it here


What you really want and need is such code instead:

$('#btnSubmit').bind('click', function(){
    var checked = ($("input[name='option1']:checked").length > 0);
    if (!checked) {
        alert('Answer empty');
        return false;
    }
    return true;
});

You don't need the value, just to verify user has checked any of the radio buttons.


try this

 <script>
$(document).ready(function(){
   $('#btnSubmit').bind('click', function(){
    var option = $('#option1:Checked').val();
    if(!option){
        alert('Answer empty');
        return false;
    }
    $('#form').submit();
});
});
</script>
<form id="form" method="post">
<input type="radio" id="option1" name="option1" />
<input type="submit" name="btnSubmit" id="btnSubmit" value="submit" />
</form>
0

精彩评论

暂无评论...
验证码 换一张
取 消