简体   繁体   中英

Remove numbers from a comma separated string in javascript when checked is false

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

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;"/>

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM