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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26250291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:42:52  来源:igfitidea点击:

Passing checkbox values of a form as JSON?

javascriptjqueryajaxjsoncheckbox

提问by User2413

Html code :

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:

JSON代码:

    <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>

In the above code am able to take the values of each textbox but when it comes to checkbox,i want to retrive multiple checkbox values inside json and want to pass it to Ajax.Can anyone tell me how can i take the multiple checkbox values in to Json??Any Help would be Appreciated..

在上面的代码中,我能够获取每个文本框的值,但是当涉及到复选框时,我想在 json 中检索多个复选框值并将其传递给 Ajax。谁能告诉我如何获取多个复选框值到 Json??任何帮助将不胜感激..

回答by HarryFink

Try something like this to get checked values:

尝试这样的事情来获取检查值:

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

In your case this will be something like this:

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

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

回答by Sameer Shemna

Why not just take the whole form with jQuery serializeArray():

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

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

Will get what you want and greatly shorten your code.

将得到您想要的并大大缩短您的代码。

Its Javascript code by the way not JSON code. ;)

顺便说一下,它的 Javascript 代码不是 JSON 代码。;)

Try:

尝试:

function addperson(){

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

       });

回答by Akash Sarawagi

Mark it as answer if it helps you. change your function addperson()

如果对您有帮助,请将其标记为答案。更改您的功能 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);
       }
     });

}

}