Reputation: 761
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/
This is the 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:
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/
The JavaScript code:
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!
Upvotes: 1
Views: 637
Reputation: 402
Since your keys in your placeholderText
object are book
, journal
& newspaper
you want to get placeholderText['book']
or placeholderText['journal']
for instance.
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
.
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">
Upvotes: 3