1

I am trying to add an ID to an existing array using Javascript like this...

var myinput = $("input[name=myinput]").val();
console.log(myinput);

var split = myinput.split(',');

SavedId = 1;

split.push(SavedId);

alert(split);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="myinput" value="34">

This works great, but if myinput does not already have a value then it adds a comma before the inject value like this...

var myinput = $("input[name=myinput]").val();
console.log(myinput);

var split = myinput.split(',');

SavedId = 1;

split.push(SavedId);

alert(split);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="myinput" value="">

Anyone any ideas how I can fix this?

3 Answers 3

6

If myinput is empty ("") it gets split to ([""]) and joining that with another value results in the extra comma. You could just replace that by an empty array:

 var split = myinput.length ? myinput.split(',') : [];
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, simple explanation. Fix makes sense
4

You could filter the array with empty strings,

because if you split an empty string,

''

you get an array with this empty string,

['']

which is unwanted.

By filtering with Boolean as callback, you get an array only with truthy, like not empty strings, values.

[]

var myinput = $("input[name=myinput]").val();

console.log(myinput);

var split = myinput.split(',').filter(Boolean),
    SavedId = 1;

split.push(SavedId);
alert(split);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="myinput" value="">

Comments

0

You have to filter the empty strings.

Splitting '' on every comma will give you [''] since the starting string is empty. Because of that, you have to remove those empty strings in the resulting array. You can do it by filtering out values based on their truthiness using the Boolean function.

Also, take care to convert the split strings to numbers before adding a number to your array. You can do this by mapping the Number function on your array.

function onChange() {
  const myinput = $("input[name=myinput]").val();

  const split = myinput.split(',')
    .filter(Boolean)
    .map(Number);

  split.push(1);

  console.log(split);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Type in the field:
<input name="myinput" value="" oninput="onChange()">

1 Comment

.filter(Boolean).map(Number) if you want to re-use existing functions that do the same.

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.