Search code examples
javascriptselectinputinnerhtmlconcatenation

How do i concat the values of select and input field and also display altogether with JavaScript


I'm making a phone picker input menu which has a <select> and <input> field just like below:

<select id="country">
    <option data-countryCode="IN" value="91">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">

JS code:

 const select = document.querySelector('#country');
    const tel = document.getElementById('tel')
        tel.value = `${select.options[select.selectedIndex].value}` +`${tel.value}`


How do I concat/join the select value with the input field and also display whole together in that input field.


Solution

  • 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;
    });
    <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">