JQuery: Collect values of multiple select or checklist element

JQuery: Collect values of multiple select or checklist element

·

1 min read

serializeArray()

Here we have 3 checkboxes, each had a value of user id. To collect data from them we must use an identifier that can be applied to more than one element, we can use 'name' attribute or 'class' attribute.

but for personal preference I use class for CSS identifier and name for other purposes (like collecting data).

<input type="checkbox" name="user_id[]" value="1" onchange=getValue()>Liam</input>
<input type="checkbox" name="user_id[]" value="2" onchange=getValue()>Olivia</input>
<input type="checkbox" name="user_id[]" value="3" onchange=getValue()>Noah</input>

after that, we can just access it in js file.

let arrId=[] //array to contain selected value

function getValue(){
  arrId=[] //clear the array on every trigger, so there is no duplicate
  let user_ids=$('[name="user_id"]').serializeArray()
  //let user_ids=$('.ids').serializeArray() //use this if using 'class'
  //console.log(user_ids) //show object array of elm selected
  //like this [{"name": "user_id[]","value":"3"}]
  //loop the array obj so we get the value only

  for(x in user_ids){
    arrId.push(user_ids[x].value)
  }
  console.log(arrId) // this will show an array ex: ["2","3"]
}

Hope this helps! This is extremely helpful when you deal with forms that nested data, in my early days this is one problem that confuse me so much. Hope this post helps you!

More like this? visit my hashnode