How Do I Concat The Values Of Select And Input Field And Also Display Altogether With JavaScript October 02, 2022 Post a Comment I'm making a phone picker input menu which has a and field just like below: Solution 1: You can do something like this const select = document.querySelector('#country'); const tel = document.getElementById('tel'); let prevVal = select.value; // storing previous value of select // this block will be exected on init of code if(tel.value) tel.value = `${select.value}${tel.value}`; else tel.placeholder = `${select.value}${tel.placeholder}`; // adding event on changing input tel.addEventListener('change', ({ target }) => { const reg = new RegExp(`(^${prevVal} )`); // checking do we already have country code if (reg.test(target.value)) tel.value = tel.value.replace(reg, target.value); else tel.value = `${select.value}${target.value}`; }); // adding event on changing select select.addEventListener('change', ({ target }) => { const reg = new RegExp(`(^${prevVal})`); if(tel.value) tel.value = `${target.value}${tel.value.replace(reg, '')}`; else tel.placeholder = tel.placeholder.replace(reg, target.value); prevVal = target.value; });Copy <select id="country"> <option data-countryCode="IN" value="91" selected>India</option> <option data-countryCode="US" value="1">US</option> <option data-countryCode="GB" value="44">UK</option> </select> <input type="tel" placeholder ="956 826 4457" id="tel">Copy Solution 2: First of all there are some wierd details in the code you provided. <select id-"country"> Copy supposes to be <select id="country"> Copy ? why do you concat templates with plus using templates at the same time? isn't it enough just to use tel.value = ${select.options[select.selectedIndex].value}${tel.value} ? In addition, what event are you going to use? If we select country for the first time it works well, adding '91' for example. But next time (if we picked up the wrong country accidentally) it will add the code again. As for the problem , could you give more detailed explanation of what happens now exactly Solution 3: The problem is that you have put a '-' instead of an '=' sign on the first line. It should be: <select id="country"> Copy Also, why have you used jQuery? Javascript covers it just as easily: const select = document.getElementById('country'); const tel = document.getElementById('tel'); tel.value = select.options[select.selectedIndex].value + tel.value; Copy Share Post a Comment for "How Do I Concat The Values Of Select And Input Field And Also Display Altogether With JavaScript"
Post a Comment for "How Do I Concat The Values Of Select And Input Field And Also Display Altogether With JavaScript"