1

I am trying to get values from checkboxes in the following format of an array. Maybe this is the simple problem for you guys but I am really stuck here.

This is my input types

<input type="checkbox" id="any" name="chk" value="value1">
<input type="checkbox" id="any1" name="chk" value="value2">
<input type="checkbox" id="any2" name="chk" value="value3">
<input type="checkbox" id="any3" name="chk" value="value4">
<input type="checkbox" id="any4" name="chk" value="value5">

jQuery code

var fuelType =new Array();
  $.each($("input[name='chk']:checked"), function(){
    console.log($(this).val())
    fuelType.push($(this).val());
});
fuelType = fuelType.join(",");
console.log(fuelType);

I am getting following log

["value1,value2,value3",value4",value5"]

Required response

["value1","value2,"value3","value4","value5"]
8
  • 1
    Ok, then I'm still confused. fuelType already fits that pattern without doing anything to it. It's an array of strings Commented Oct 25, 2018 at 17:39
  • I don't understand why I am not getting required format, thats why I've posted here :( Commented Oct 25, 2018 at 17:40
  • 3
    jsfiddle.net/0y4p6w2x The variable is already an array of strings. If you wanting the console log of that to print out in a pre-defined manner, then you are actually asking to take an array, format it to a string, and print the string. Commented Oct 25, 2018 at 17:42
  • Yes it is giving right output in fiddle but I don't know why I am unable to get it into my page :( Commented Oct 25, 2018 at 17:45
  • 1
    jsfiddle.net/0y4p6w2x/1 [] vs new Array() doesn't change the result. You have something else going on with your code that is not reflected in your question as it currently stands. Commented Oct 25, 2018 at 17:47

1 Answer 1

1

This is what you need to change you jQuery to:

var fuelType =new Array();
$.each($("input[name='chk']:checked"), function(){
    console.log($(this).val())
    fuelType.push($(this).val());
});
console.log(fuelType);

What you were doing is joining the array of strings and delimiting them with a ','. That does not create an array of strings. That creates a single string that separate the keys with ','. If you had a different set of data you could use Array.prototype.map() to create a new array, but you already have it as another poster has mentioned.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes you are right I was making mistake with join(); Thanks Alek and Talpar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.