简体   繁体   中英

Getting values of multiple checkboxes(Javascript), then assigning different values based on selection

So I have a bit of a tricky situation here.

I have a series of forms that have selections that are being stored as arrays. I am checking selections against the correct answer at the index, so index and amount of elements are very important.

My issue arises why trying to concatenate these 2 arrays that hold checked and unchecked values for html checkboxes.

ie: let comb = checked.concat(unchecked)

let checked = $('input:checkbox:checked').map(function() {
return this.value;}).get();

let unchecked = $('input:checkbox:not(:checked)').map(function() {
return "100"; }).get();

The problem with that code is it messes up the order of selections, which breaks the code that is checking at specific indexes against the correct answer.

What I need is to get all the checkbox values, and assign the html value only if it is checked, otherwise insert some arbitrary value(as you can see return "100")

Something like this(not syntatically correct or runnable):

let checked = $('input:checkbox').map(function() {
if ('input:checkbox:checked'){ .  //if checked
return this.value;}).get();}else if ('input:checkbox:not(:checked)'){ //if unchecked
return "100"; }).get();
}

You need the whole conditional inside the map() callback

let checked = $('input:checkbox').map(function() {
  // if checked return the value , if not return "100"
  return this.checked ? this.value : '100';
}).get();

Or in long-hand using is() as you were trying to do

let checked = $('input:checkbox').map(function() {      
  if($(this).is(':checked')){
     return this.value;
  }else{
     return '100';
  } 
}).get();

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