根据下拉选择更改占位符文本?

时间:2014-08-01 09:00:07

标签: javascript jquery html5 placeholder

我有一个选择框,其中有几个选项供用户选择,当用户选择"名字",我想要占位符文字'输入你的名字'出现在文本框旁边。 请在下面找到我的代码:

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&amp; 9 ... 对此有任何帮助。

请参阅演示:http://jsfiddle.net/sW6QP/6/

3 个答案:

答案 0 :(得分:2)

使用jQuery Placeholder支持IE 8&amp; 9。

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

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

答案 1 :(得分:1)

 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

答案 2 :(得分:0)

您全新的代码:

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]);
    }
});

它应该解决你的问题

相关问题