开发者

jQuery :input[value] with Radio buttons

开发者 https://www.devze.com 2023-01-07 04:47 出处:网络
I\'m using: var data = $(\"form :input[value]\"); To get all the values in a form and passing the data to an ajax script.

I'm using:

var data = $("form :input[value]");

To get all the values in a form and passing the data to an ajax script.

My problem is it doesn't work with RADIO buttons - it always sends the last value for the 开发者_JAVA技巧radio group.

Any ideas on how to get the checked radio button along with all the other form values?


There's a function built-in for this, just call .serialize(), like this:

var data = $("form").serialize();

You can see how it's appropriately filtering out these elements here.


You are maybe looking for .serialize() method.

var data = $('form').serialize();

Note: .serialize() only serializes input controls which have a name attribute.

Reference: .serialize()


for radio buttons you need to inspect the checked attribute.


<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
// serialize() will get all data from form with id "myform" and store it in data variable, that will be sent to test.php page.

    $(document).ready(function() {
        $('#submit').click(function () {

         var data = $("#myForm").serialize();   

         if($('input[type="radio"]:checked').length == "0") {    
              alert("Select any value");     
         } else {                       
                $.post ( 
                    "test.php", 
                     data,
                     function (response) {
                     $('#message').html(response);
                     }
                );
        }
        return false;           
        });

    });
</script>

</head>
<body> 
    <form id ="myForm">
        <label>Name</label>
        <input type="text" name="name" id="name"/> <br/><br/>   
        <br/>
        <label>Select your favourite Activities:</label><br/>
        <input type="radio" name="reading" value="reading"> Reading<br />
        <input type="radio" name="programming" value="programming"> Programming<br />

        <input type="submit" id="submit"/>  
    </form>
<div id="message"></div>

</body>
</html>

test.php 
<?php 

    var_dump($_POST); 

    $name = $_POST['name'];
    echo "Welcome ". $name.'!<br/>';

?>
0

精彩评论

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