简体   繁体   English

无法删除的输入 function (HTML) 中的默认值

[英]Default value in input function (HTML) that can't be removed

So I'm trying to create a form where user will enter their phone number.所以我正在尝试创建一个表单,用户将在其中输入他们的电话号码。 Since it's supposed to be used in single country, I want country code as a default value that can't be erased, only added to.由于它应该在单个国家/地区使用,因此我希望国家/地区代码作为无法删除的默认值,只能添加到。 How that could be done, or maybe there are alternative best practices for such case?如何做到这一点,或者这种情况下可能有替代的最佳实践?

 <form class="form__wrapper"> <h2 class="form__wrapper_text">Just form</h2> <div class="form__wrapper_number"> <p>Your number:</p> <!--<span>+380</span>--> <input type="tel" value="+380" o> </div> </form>

You can make sure it does not get deleted by key-up event.您可以确保它不会被按键事件删除。 Code also checks for cut and selected then delete...代码还检查剪切和选择然后删除...

 document.querySelector('input').addEventListener('keyup', val, false); function val() { if (this.value.includes("+380 ") === false) { this.value = "+380 " + this.value.substr(this.value.indexOf(' ') + 1); this.value = this.value.replace("+380 +380", "+380 "); } }
 <form class="form__wrapper"> <h2 class="form__wrapper_text">Just form</h2> <div class="form__wrapper_number"> <p>Your number:</p> <!--<span>+380</span>--> <input type="tel" value="+380" o> </div> </form>

But I have to say, this kind of things a better done simply like: type +380 <input here> then on submit just join value of +380 to input submitted value...但我不得不说,这种事情做得更好,就像:输入+380 <input here>然后在提交时只需加入 +380 的值来输入提交的值......

And CSS only solution:而 CSS 唯一解决方案:

 input { padding-left: 40px; }.input-container { position: relative; }.input-container:after { content: '+380 '; position: absolute; top: 50%; left: 5px; transform: translateY(-50%); }
 <form class="form__wrapper"> <h2 class="form__wrapper_text">Just form</h2> <div class="form__wrapper_number"> <p>Your number:</p> <div class="input-container"> <input type="tel"> </div> </div> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM