【问题标题】:Change placeholder text based on the dropdown selection?根据下拉选择更改占位符文本?
【发布时间】:2014-09-24 10:31:30
【问题描述】:

我有一个选择框,其中有几个选项可供用户选择,当用户选择“名字”时,我希望占位符文本“输入您的名字”出现在文本框旁边。 请在下面找到我的一段代码:

HTML:

<select id="selectionType">
<option value="-1">Select One</option>
<option value="0">First Name</option>
<option value="1">Last Name</option>

JS:

    var placeholderText = {"First Name":"Enter your First Name","Last Name":"Enter your Last Name"};

$("#selectionType").on("change",function() {
    var selection = document.getElementById("selectionType");
    var inputBox = document.getElementById("inputBox");

    var selectedVal = $('#selectionType').find(':selected').text();
    if (placeholderText[selectedVal] !== undefined) {
        inputBox.placeholder = placeholderText[selectedVal];
    }
});

它在 Chrome 和 FF 中运行良好,但在 IE 8 和 9 中失败... 对此有任何帮助。

查看演示:http://jsfiddle.net/sW6QP/6/

【问题讨论】:

标签: javascript jquery html placeholder


【解决方案1】:

在 IE 8 和 9 中使用 jQuery Placeholder 支持。

因为 IE 8 和 9 不支持 html5 占位符,仅在 IE 10 中支持。

参考:http://www.w3schools.com/Tags/att_input_placeholder.asp

【讨论】:

  • 我将使用 jquery 库作为占位符来让它工作......谢谢
【解决方案2】:

试试

 var placeholderText = {
    "First Name": "Enter your First Name",
    "Last Name": "Enter your Last Name"
};

$("#selectionType").on("change", function () {

    if (this.value != -1) {
        $("#inputBox").val(placeholderText[$("#selectionType option:selected").text()]);
    } else {
        $("#inputBox").val("");
    }

});

UPDATED DEMO

【讨论】:

    【解决方案3】:

    您的全新代码:

    var placeholderText = {"First Name":"Enter your First Name","Last Name":"Enter your Last Name"};
    $("#selectionType").on("change",function() {
        var selection = $("#selectionType");
        var inputBox = $("#inputBox");
    
        var selectedVal = $(':selected', selection).text();
        if (placeholderText[selectedVal] !== undefined) {
            inputBox..attr('placeholder', placeholderText[selectedVal]);
        }
    });
    

    应该能解决你的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 2019-06-14
      • 2014-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-14
      相关资源
      最近更新 更多