NooBskie NooBskie - 4 months ago 46
jQuery Question

`Select2` Alternate other input placeholder on val change

I have a seclet2 dropdown with two options

<select id="ddlsearch">
<option value="0">Translated Search</option>
<option value="1" selected="">Exact Search</option>
</select>


It seems to change the placeholder correctly for the first
if
statement but I cant seem to get my else statement working. What exactly am I doing wrong here?

function selectPlaceholder() {
var reportLevel = "0",
$select = $("#ddlsearch")

if (reportLevel == "0") {
$select.on("change", function(e) {
$('#txtkey').attr('placeholder', 'asd')
});
} else {
$select.on("change", function(e) {
$('#txtkey').attr('placeholder', '123')
});
}
};
selectPlaceholder()

Answer

You need to do something like this...

$("#ddlsearch").on("change", function(e) {
  if ("0" == this.value) {
    $('#txtkey').attr('placeholder', 'asd')
  } else {
    $('#txtkey').attr('placeholder', 'fgh')
  }
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h4> Your select </h4>

<select id="ddlsearch">
  <option value="0">Translated Search</option>
  <option value="1" selected="">Exact Search</option>
</select>

<h4> Your text input somewhere </h4>
<input id='txtkey'>

The if statement should reside inside the change event handler, and placeholder should be changed based on value of the select.

Comments