How Do I Concat The Values Of Select And Input Field And Also Display Altogether With Javascript June 27, 2023 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 thisconst 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 codeif(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 = newRegExp(`(^${prevVal} )`); // checking do we already have country codeif (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 = newRegExp(`(^${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<selectid="country"><optiondata-countryCode="IN"value="91"selected>India</option><optiondata-countryCode="US"value="1">US</option><optiondata-countryCode="GB"value="44">UK</option></select><inputtype="tel"placeholder ="956 826 4457"id="tel">CopySolution 2: First of all there are some wierd details in the code you provided.<select id-"country"> Copysupposes 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 usetel.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 exactlySolution 3: The problem is that you have put a '-' instead of an '=' sign on the first line. It should be:<select id="country"> CopyAlso, why have you used jQuery? Javascript covers it just as easily:constselect = 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"