Unbreakable Unbreakable - 5 months ago 8
jQuery Question

How to pass all the checked checkboxID to REST

I am learning web development and I have created some checboxes. At present I have four checkbox. I want to send my "REST Service" all the checkboxesID which are checked by the user. Below is what I have attempted.

<!DOCTYPE html>
<html>
<body>
<form>
<input type="checkbox" id = "1" name="graphId" value="1">Graph1<br>
<input type="checkbox" id = "2" name="graphId" value="2">Graph2<br>
<input type="checkbox" id = "3" name="graphId" value="3">Graph3<br>
<input type="checkbox" id = "4" name="graphId" value="4">Graph4<br>
<input id="btnGetResponse" type="button" value="ClickMe!"/>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
<input id="btnGetResponse" type="button" value="Redirect" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function ()
{
$("#btnGetResponse").click(function ()
{
$.ajax(
{
type: "GET",
// HARD CODED graphId=1 in the URL, I need it to be the checkboxId which are checked
url: "http://localhost:51349/SMS_Rest.svc/v1/CheckBox?graphId=1",
data: '{}', // Need to get the checked checkboxes ID here
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
if (response == true)
{
sessionStorage.setItem('uiResponse', true);
window.location.href = "../backbonetest/dashboardUI.html";
}
},
failure: function (response)
{
alert(response);
}
});
});
});

</script>
</body>
</html>


Kindly help me.

Answer

Use jQuery.map() over :checked selector.

Pass mapped ids in data object.

$("#btnGetResponse").click(function() {
  var ids = $('[name="graphId"]:checked').map(function() {
    return this.id;
  }).get();
  console.log(ids);
  $.ajax({
    type: "GET",
    url: "http://localhost:51349/SMS_Rest.svc/v1/CheckBox",
    data: {
      checked: ids
    },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(response) {
      if (response == true) {
        sessionStorage.setItem('uiResponse', true);
        window.location.href = "../backbonetest/dashboardUI.html";
      }
    },
    failure: function(response) {
      alert(response);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
  <input type="checkbox" id="1" name="graphId" value="1">Graph1
  <br>
  <input type="checkbox" id="2" name="graphId" value="2">Graph2
  <br>
  <input type="checkbox" id="3" name="graphId" value="3">Graph3
  <br>
  <input type="checkbox" id="4" name="graphId" value="4">Graph4
  <br>
  <input id="btnGetResponse" type="button" value="ClickMe!" />
</form>

Comments