如何合并选择和输入字段的值,以及如何与JavaScript一起显示 [英] How do i concat the values of select and input field and also display altogether with JavaScript

查看:59
本文介绍了如何合并选择和输入字段的值,以及如何与JavaScript一起显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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


如何将select值与input字段合并/合并,并同时在该输入字段中整体显示.


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

推荐答案

您可以执行以下操作

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">

这篇关于如何合并选择和输入字段的值,以及如何与JavaScript一起显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆