[英]Change input box placeholder upon select box option change using jQuery
I have created an input box where the placeholder changes if the selected option of the select box is changed. 我创建了一个输入框,如果更改了选择框的选定选项,占位符将更改。 Please have a look at the fiddle: https://jsfiddle.net/dL2aqckj/2/
请看一下小提琴: https : //jsfiddle.net/dL2aqckj/2/
This is the html: 这是html:
<select id="selector">
<option value="book">Book</option>
<option value="journal">Journal</option>
<option value="newspaper">Newspaper</option>
</select>
<input type="text" id="searchbox" placeholder="Find Book" size="20">
and this the JavaScript: 而这个JavaScript:
var selector = $("#selector");
var searchbox = $("#searchbox");
selector.on("change", function () {
searchbox.attr('placeholder', "Find " + selector.find(':selected').text()
)});
This all works nicely. 一切都很好。 Now I want the placeholder to contain a custom text and not just the name of the select box option.
现在我希望占位符包含自定义文本,而不仅仅是选择框选项的名称。 Therefore I am trying to match the select box selected option with some placeholder text.
因此,我尝试将选择框选择选项与一些占位符文本进行匹配。 This is the fiddle: https://jsfiddle.net/2x5m746e/1/
这是小提琴: https : //jsfiddle.net/2x5m746e/1/
The JavaScript code: JavaScript代码:
var placeholderText = {
"book": "Enter book ID",
"journal": "Enter journal ID",
"newspaper": "Enter newspaper ID",
};
var selector = $("#selector");
var searchbox = $("#searchbox");
selector.on("change", function () {
searchbox.attr('placeholder', searchbox.val(placeholderText[selector.find(':selected').text()])
)});
It does not change the placeholder correctly. 它不会正确更改占位符。 What am I doing wrong?
我究竟做错了什么? Any suggestions are highly appreciated!
任何建议都非常感谢!
Since your keys in your placeholderText
object are book
, journal
& newspaper
you want to get placeholderText['book']
or placeholderText['journal']
for instance. 由于你的
placeholderText
对象中的键是book
, journal
和newspaper
你想获得placeholderText['book']
或placeholderText['journal']
。
So you should get the value not the text of the selected item since in your HTML code your values in options are book
, journal
& newspaper
. 因此,您应该获得的值不是所选项目的文本,因为在您的HTML代码中,您选择的值是
book
, journal
和newspaper
。
var placeholderText = { "book": "Enter book ID", "journal": "Enter journal ID", "newspaper": "Enter newspaper ID", }; $("#selector").on("change", function () { $("#searchbox").attr('placeholder', placeholderText[$(this).find(':selected').val()]); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="selector"> <option value="book">Book</option> <option value="journal">Journal</option> <option value="newspaper">Newspaper</option> </select> <input type="text" class="form-control" id="searchbox" placeholder="Enter book ID" size="20">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.