将表单的复选框值作为JSON传递?

时间:2014-10-08 06:14:21

标签: javascript jquery ajax json checkbox

Html代码:

   <form class="form-horizontal" id="addpersons" style="padding:20px;">
<fieldset class="scheduler-border">

<!-- Form Name -->
<legend class="scheduler-border">Information</legend>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="fname">First Name</label>  
  <div class="col-md-5">
  <input id="fname" name="firstName" type="text" placeholder="First Name" class="form-control input-md">

  </div>
</div>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="lname">Last Name</label>  
  <div class="col-md-5">
  <input id="lname" name="lastName" type="text" placeholder="Last Name" class="form-control input-md">

  </div>
</div>

<!-- Multiple Checkboxes (inline) -->
<div class="form-group">
  <label class="col-md-4 control-label" for="professionalservices">Do you offer any of the services?</label>
  <div class="col-md-4" style="width:70%; margin-left:34%;">
    <label class="checkbox-inline" for="professionalservices-0">
      <input type="checkbox" name="professionalservices" id="professionalservices-0" value="1">
        BI  services
    </label>
    <label class="checkbox-inline" for="professionalservices-1">
      <input type="checkbox" name="professionalservices" id="professionalservices-1" value="2">
      Resell vendor's  services
    </label>
    <label class="checkbox-inline" for="professionalservices-2">
      <input type="checkbox" name="professionalservices" id="professionalservices-2" value="3">
      Consulting Services
    </label>
    <label class="checkbox-inline" for="professionalservices-3">
      <input type="checkbox" name="professionalservices" id="professionalservices-3" value="4">
      Other  servies
    </label>
    <label class="checkbox-inline" for="professionalservices-4">
      <input type="checkbox" name="professionalservices" id="professionalservices-4" value="5">
      No  services
    </label>
  </div>
</div>
</fieldset>

<!-- Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for=""></label>
  <div class="col-md-4">
         <a href="javascript:addperson();" class="btn btn-success">Apply Now</a>
  </div>
</div>

</form>

Json Code:

    <script type="text/javascript"> 

   function addperson(){

        alert("hello");
        var persons = JSON.stringify({
        "firstName": $('#fname').val(), 
        "lastName":$('#lname').val(),
        "Services":$('#services').val()


       });

    alert("test values are"+persons);
    console.log(persons);

       $.ajax({
           type: "POST",
           contentType: 'application/json',
           url: baseurl+"addperson/add",
           data: persons,
           dataType:"text",
           success:successmethod,
           error: function(data,status) {
            alert("Error  "+status);
           }
          });

   }
   function successmethod(data){
    alert("sucessfully stored values");
   }
   </script>

在上面的代码中我能够获取每个文本框的值,但是当涉及到复选框时,我想在json中检索多个复选框值并想要将它传递给Ajax。任何人都告诉我如何才能获取多个复选框值到Json ??任何帮助都会被赞赏..

3 个答案:

答案 0 :(得分:3)

尝试这样的方法来获取选中的值:

$( "#services:checked" ).map(function() {
    return $(this).val();
}).get()

在你的情况下,这将是这样的:

    var persons = JSON.stringify({
    "firstName": $('#fname').val(), 
    "lastName":$('#lname').val(),
    "Services": $( "#services:checked" ).map(function() {
                    return $(this).val();
                }).get()
   });

答案 1 :(得分:0)

为什么不用jQuery serializeArray()来获取整个表单:

data: $('form#addpersons').serializeArray();

将获得您想要的内容并大大缩短您的代码。

它的Javascript代码不是JSON代码。 ;)

尝试:

function addperson(){

        var persons =  $('form#addpersons').serializeArray();
        console.log(persons);

       });

答案 2 :(得分:0)

如果对您有所帮助,请将其标记为答案。 改变你的功能addperson()

function addperson(){
    var objJson={};
    objJson["firstName"]=$('#fname').val();
    objJson["lastName"]=$('#lname').val();
    objJson["Services"]={};
    $.each( $('input[type=checkbox]'), function(i, left) {
        objJson["Services"][$(this).parent().text().trim()]=$(this).prop("checked");
    });
    var persons = JSON.stringify(objJson);
    alert("test values are"+persons);
    console.log(persons);
    $.ajax({
       type: "POST",
       contentType: 'application/json',
       url: baseurl+"addperson/add",
       data: persons,
       dataType:"text",
       success:successmethod,
       error: function(data,status) {
        alert("Error  "+status);
       }
     });

}