JavaScript/jQuery:选择列表/下拉值为“其他”时添加文本框

我正在编写一个包含多个选择列表的表单,其中包括值“其他”。


我需要编写一个 Javascript/JQuery 函数,如果 value === "Other" 则插入一个文本框,然后在提交表单时将字段的值保存为文本框中的值。我被困在如何实现这一点上。它当然不能使用和 ID,因为页面上至少有两个输入需要使用此功能。


我目前正在尝试使用类使其工作,这是我得到的代码:


function doSomething(){

  if($(".selectlist :selected").text() === "Other"){

    $(".selectlist :selected").add("<input type=text></input>").appendTo(document.body);

  }

}

这种方法有效,但正如您所见,它在创建输入时将“其他”值从选择列表中拉出。我听说过event.target并使用thisor $(this),但我在 JQuery 方面没有太多经验,滚动浏览 JQuery 文档对我没有多大帮助,我一直在使用.append(),等.appendTo(),.add()但我要去有点盲目


(在这种情况下,不允许对输出进行硬编码并根据选择值显示/隐藏它)


欢迎任何想法!


人到中年有点甜
浏览 170回答 2
2回答

犯罪嫌疑人X

这有效:function DoSomethingOnChange(selectBox) {&nbsp; &nbsp; if ($(selectBox).find(":selected").text().trim().toUpperCase() == "OTHER") {&nbsp; &nbsp; &nbsp; &nbsp; $('.other-input').show();&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; $('.other-input').hide();&nbsp; &nbsp; &nbsp; &nbsp; $('.other-input').val(""); //clear out the value if required&nbsp; &nbsp; }}当通过内联事件处理程序触发时,例如:<select&nbsp; onchange="DoSomethingOnChange(this)"><option></option><option>One</option><option>Two</option><option>Other</option></select>前提是您的选项之一有其他文字。function DoSomethingOnChange(selectBox) {&nbsp; if ($(selectBox).find(":selected").text().trim().toUpperCase() == "OTHER") {&nbsp; &nbsp; $('.other-input').show();&nbsp; } else {&nbsp; &nbsp; $('.other-input').hide();&nbsp; &nbsp; $('.other-input').val("");&nbsp; }}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><select onchange="DoSomethingOnChange(this)">&nbsp; <option></option>&nbsp; <option>One</option>&nbsp; <option>Two</option>&nbsp; <option>Other</option></select><input class="other-input" hidden type=text placeholder="Other input" />

幕布斯6054654

这样的事情可能会奏效$("select").each(function(i,obj) {&nbsp;&nbsp; &nbsp; if ($(obj).val() === "Other") {&nbsp; &nbsp; &nbsp; &nbsp; $(obj).parent().append("<input type=\"text\" name=\"" + $(obj).prop("name") + "\" />");&nbsp; &nbsp; &nbsp; &nbsp; $(obj).remove();&nbsp; &nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript