student42
student42

Reputation: 171

jquery put comma between every variable except last

I have a script that will insert the checked checboxes and radios in the value() of an input tag.

var burgernavn = meat + " with " + bread + " and " + onion + tomato + cheese + salad;
  $('#burger-navn').val(burgernavn);

Onion, tomato, cheese and salad needs to have1 " ," between them, except the last two who need " and " between them. Thats the first thing. Second thing is that these variables represent checkboxes, so they can be undefined, in which case they should not be put into $('#burger-navn').val(). They can all be undefined, in which case no commas or "and" should be put in. I hope this is accomplishable.

Upvotes: 1

Views: 264

Answers (2)

mp77
mp77

Reputation: 428

  1. Capture all checked values in an array (this makes sure that whatever values in this array, all are defined). Also, it will give you count of values that you need to pass to input box.

var checkedValues = document.getElementsByClassName('checkbox');

  1. Iterate over this array, check for last values. (Check my comments in below code snippet)

var commaValues = "", otherValues= "";
//we are iterating only until (total values -2)
for(var i = 0; i < checkedValues.length - 2 ; i++){
  
  //append comma with each value
  commaValues += checkedValues[i].concat(",");
}

//append 'And' for last two values if total valuesa re more than one
if(checkedValues.length > 1){
  otherValues = checkedValues[checkedValues.length-1].concat("and", checkedValues[checkedValues.length])
}
else if(checkedValues.length == 1){
  otherValues = checkedValues[0];
}

//finally concat both strings and put this concated string in input
 $('#burger-navn').val(otherValues.concat(commaValues));

So, I hope you got the idea. This code snippet might need a bit tweak since I didn't had your html code and sample data, but it is easily doable using this snippet as reference. Cheers

Upvotes: 2

Chris Dixon
Chris Dixon

Reputation: 9167

You can do this pretty easy with jQuery $.map.

var checkboxes = $('input:checkbox');
var commaString = $.map($('input:checkbox'), function( ele, i ) {
    return $(ele).val() + (i + 2 == checkboxes.length ? " and" : (i + 1 != checkboxes.length) ? ",": "");
}).join(" ");

Upvotes: 1

Related Questions