Home > Software design >  It is possible to get all checkbox value into comma seperated string in jquery
It is possible to get all checkbox value into comma seperated string in jquery

Time:04-02

<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
  <label for="vehicle1"> I have a bike</label><br>
  <input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
  <label for="vehicle2"> I have a car</label><br>
  <input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
  <label for="vehicle3"> I have a boat</label><br><br>

i want all checkbox value like below there is any possible

$(document).ready(function () {
var ckhvalue="'bike','car','boat'";
});

CodePudding user response:

You can use the :checked selector and .map to get your values and combine them:

$("#btn").click(() => {

    var chkValue = $(":checked").map((i,e) => e.value).toArray().join(",");
    console.log(chkValue)

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label><br><br>

<hr/>
<button id=btn>click me</button>

  • Related