95XF
95XF

Reputation: 37

Concatenating a string in jQuery

I have following line of code in jQuery:

inputPhoneNumber.val(inputPhoneCountry + inputPhoneMain);

What is the best way of adding two characters (00) in front of those two values inside the inputPhoneNumber variable? Regular JS string concatenation like:

inputPhoneNumber.val('00' + inputPhoneCountry + inputPhoneMain);

...doesn't work for me.

Upvotes: 0

Views: 50

Answers (2)

mplungjan
mplungjan

Reputation: 177684

I do not see why

inputPhoneNumber.val('00' + inputPhoneCountry + inputPhoneMain);

should not work unless inputPhoneNumber is a type=number in which case it MIGHT remove the leading 0s (but it doesn't)

Try template literals and a text field

inputPhoneNumber.val(`00${inputPhoneCountry}${inputPhoneMain}`);

In testing it does not make a difference

const inputPhoneCountry = 31;
const inputPhoneMain = 612345678;
$("#inputPhoneNumber1").val(`00${inputPhoneCountry}${inputPhoneMain}`);
$("#inputPhoneNumber2").val(`00${inputPhoneCountry}${inputPhoneMain}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="inputPhoneNumber1" />
<input type="text" id="inputPhoneNumber2" />

Upvotes: 2

Alexis Garcia
Alexis Garcia

Reputation: 472

This works for me:

inputPhoneNumber.val('00' + inputPhoneCountry + inputPhoneMain);

This works too:

inputPhoneNumber.val(`00${inputPhoneCountry}${inputPhoneMain}`);

Still if it doenst work for you, you can break them and use only one var for it. Example:

var inputPhoneCountry = 10;
var inptPhoneMain = 20;
var finalNumber = '00' + inputPhoneCountry + inptPhoneMain;

alert(finalNumber);

Upvotes: 0

Related Questions