3

I have some inputs by type checkbox:

<input type="checkbox" value="5da1dc651d011c56ef1cb3db_693715"  onchange="handlechange(this)">
<input type="checkbox" value="6da1dc651d011c56ef1cb3db_123689"  onchange="handlechange(this)">

handlechange() function is going to add the values of input checkedin

<input type="hidden" value="" class="GetVals" />

The main problem is that when checked is false the value of that input should be removed of <input type="hidden" value="" class="GetVals" />, but it would not remove.

function handlechange(a) {
  var check = $(a).prop("checked");
  if (check == true) {
    var value = $(a).val();
    ids += value + ','

  } 
  else if (check == false) {
    var elements = ids.substring(0, ids.lastIndexOf(","))
    var element = elements.split(",");
  }
  $(".GetVals").val(ids)
}

2 Answers 2

2

You can achieve the result by using some built-in methods.

You can use .map() only on the checked check boxes with .get() and join() like the following way:

function handlechange() {
  var ids = $('input:checked').map((i, chk) => chk.value).get().join();
  $(".GetVals").val(ids)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="5da1dc651d011c56ef1cb3db_693715"  onchange="handlechange(this)">
<input type="checkbox" value="6da1dc651d011c56ef1cb3db_123689"  onchange="handlechange(this)">

<input class="GetVals" style="width:500px;"/>

Sign up to request clarification or add additional context in comments.

1 Comment

Beat me to it :-) . BTW, you don't need the parameter a anymore & in onchange="handlechange(this)"
0

function handlechange() {
  var ids = [];
  $(".checkbox").each(function() {
    if ($(this).prop("checked")) {
      ids.push($(this).val());
    }
  });
  $(".GetVals").val(ids.join(","));
  $("#vals").text(ids.join(","));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input class="checkbox" type="checkbox" value="5da1dc651d011c56ef1cb3db_693715" onchange="handlechange()">
<input class="checkbox" type="checkbox" value="6da1dc651d011c56ef1cb3db_123689" onchange="handlechange()">
<input type="hidden" value="" class="GetVals" />
<div id="vals"></div>

You can use each to loop the checkbox and then join all values which are checked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.