开发者

javascript serialize checkbox value

开发者 https://www.devze.com 2023-03-28 00:49 出处:网络
I have a form in this project that i am serializing so that i can pass it to PHP and make some database calls开发者_如何学C based on input values.everything was working fine until I added a checkbox t

I have a form in this project that i am serializing so that i can pass it to PHP and make some database calls开发者_如何学C based on input values. everything was working fine until I added a checkbox to my form and tried to serialize it.

<input type="checkbox" name="reduceHolOT" id="reduceHolOT" checked="checked" ></input>

how can i get the checked or value attribute of this checkbox into a

$('form').serialize()

along with other data in my form?


You shoud add a value attribute for your checkbox. Good practice you know.

But serialize should be putting the string "reduceHolOT=on" into the result if the checkbox is checked. If it isn't checked, nothing will show up whether you have a value or not.


Maybe you should try this:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>serialize demo</title>
  <style>
  body, select {
    font-size: 12px;
  }
  form {
    margin: 5px;
  }
  p {
    color: red;
    margin: 5px;
    font-size: 14px;
  }
  b {
    color: blue;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<form>
  <select name="single">
    <option>Single</option>
    <option>Single2</option>
  </select>

  <br>
  <select name="multiple" multiple="multiple">
    <option selected="selected">Multiple</option>
    <option>Multiple2</option>
    <option selected="selected">Multiple3</option>
  </select>

  <br>
  <input type="checkbox" name="check" value="check1" id="ch1">
  <label for="ch1">check1</label>
  <input type="checkbox" name="check" value="check2" checked="checked" id="ch2">
  <label for="ch2">check2</label>

  <br>
  <input type="radio" name="radio" value="radio1" checked="checked" id="r1">
  <label for="r1">radio1</label>
  <input type="radio" name="radio" value="radio2" id="r2">
  <label for="r2">radio2</label>
</form>

<p><tt id="results"></tt></p>

<script>
  function showValues() {
    var str = $( "form" ).serialize();
    $( "#results" ).text( str );
  }
  $( "input[type='checkbox'], input[type='radio']" ).on( "click", showValues );
  $( "select" ).on( "change", showValues );
  showValues();
</script>

</body>
</html>

Source Link

0

精彩评论

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

关注公众号