我如何合并选择和输入字段的值,并且还与JavaScript一起显示

问题描述 投票:0回答:3

我正在制作一个电话选择器输入菜单,其中具有<select><input>字段,如下所示:

<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代码:

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

如何将select值与input字段合并/合并,并同时在该输入字段中一起显示全部。

javascript select input innerhtml concat
3个回答
0
投票

首先,您提供的代码中有一些奇怪的细节。

<select id-"country"> 

应该是


0
投票

问题是,您在第一行上放置了'-'而不是'='符号。应该是:

<select id="country">

而且,为什么要使用jQuery? Javascript可以轻松覆盖它:


0
投票

您可以做这样的事情

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">
© www.soinside.com 2019 - 2024. All rights reserved.