我有一个下拉菜单,它隐藏不同的选项,直到它们在文本输入框中被填充或不被填充,问题是在 safari 中,选项不能被设置样式(我用 display:none 隐藏了它们)直到它们是填写。所以我在填写表格时将它们添加到带有js的文档中。现在,当我填写一个电话号码时,脚本会根据字符数量添加选项数量,而不仅仅是我在上述字段中想要的方式。我是 js 的新手,所以我们将不胜感激。
Javascript
function contactPhone() {
var inputPhone = document.getElementById("inputPhone").value;
if (inputPhone !== "") {
var phone = document.createElement('option');
phone.id = "contact_phone"
phone.value ="phone"
phone.innerHTML = 'Phone';
document.getElementById("contact_option").appendChild(phone);
}
}
电话号码的输入html
<li>
Phone:
<input id="inputPhone" type="tel" name="phone" class="form-control" placeholder="Phone" oninput="contactPhone()">
</li>
应该添加选项的地方他们添加到正确的位置但是太多了 我有一个总是显示页面加载时已经在 html 中的内容
<div>
<label>What is the best way to contact you?</label>
<select id="contact_option" name="best_contact" onchange="jsContact()">
<option value="email" id="contact_email">Email</option>
</select>
</div>
当填写正确的字段时显示选项的 js。我的答案可能不需要,但我想 id 添加它以防万一。
function jsContact(){
var contact = document.getElementById("contact_option").value;
if (contact == "mail" || contact == "email" || contact == "phone") {
document.getElementById("contact_submit").style.display = "block";
}
else {
document.getElementById("contact_submit").style.display = "none";
}
}
这是一个 jsfiddle https://jsfiddle.net/ryqjtwcv/
最佳答案
因此您可以尝试使用 onblur,并且您还需要跟踪选项框的状态。
在这种情况下,我只是在其中插入了一个简单的 if 语句,以帮助您了解可以在哪里检查该选项列表的状态
https://jsfiddle.net/qnj24hbn/10/
Js
function contactPhone() {
var contact_opts = document.getElementById("contact_option");
// if it has more then 1 option in there don't do anything
if (contact_opts.options.length === 1) {
var inputPhone = document.getElementById("inputPhone").value;
if (inputPhone !== "") {
var phone = document.createElement('option');
phone.id = "contact_phone"
phone.value = "phone"
phone.innerHTML = 'Phone';
contact_opts.appendChild(phone);
}
}
}
html
Phone:
<input id="inputPhone" type="tel" name="phone" class="form-control" placeholder="Phone" onchange="contactPhone()">
<div>
<label>What is the best way to contact you?</label>
<select id="contact_option" name="best_contact" onchange="jsContact()">
<option value="email" id="contact_email">Email</option>
</select>
</div>
关于javascript - 为什么我的 js 脚本根据所述字段中的字符数量而不是一次创建多个选项标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42015956/