NooBskie NooBskie - 3 months ago 6
Javascript Question

Changing placeholder with `this` on multiple elements via checkbox

Currently I have two search inputs on every page using the same classes. What I am trying to do is change the placeholder text of

this
element when the checkbox isnt checked here is what I have so far. Also Codepen

HTML

<nav class="navbar navbar-secondary-scroll-mobile" role="navigation">
<div class="container">
<div class="row">
<div class="search-scroll">
<div class="pull-left">
<input autocomplete="off" class="form-control SearchInput" name="search" placeholder="Have your search terms translated to Chinese." value="" type="text">
</div>
<div class="pull-right">
<label>
<input class="translateSearch" type="checkbox" checked="checked">
<span>Translate</span>
</label>
</div>
</div>
</div>
</div>
</nav>


JS

$('.translateSearch').on('change', function(e) {
if ($(this).is(':checked') == true) {
$('.translateSearch').not($(this)).attr('checked', true);
} else {
$('.translateSearch').not($(this)).attr('checked', false);
$('.translateSearch').attr('placeholder', 'Search using exact terms.');
}
});


I just cant seem to get it to work with the placeholder. Any ideas?

Answer

The following JS will set the placeholder on your text input with class SearchInput. I assumed you wanted the placeholder there instead of on the translateSearch checkbox as implied by the original code. Also made a change that restored the original placeholder text when the box is checked.

$('.translateSearch').on('change', function(e) {
  if ($(this).prop('checked')) {
    $('.SearchInput').attr('placeholder', 'Have your search terms translated to Chinese.');
  } else {
    $('.SearchInput').attr('placeholder', 'Search using exact terms.');
  }
});

Also as a note - you don't need to manually to the checkbox behaviors as they are done automatically by default.

Here's a link to the CodePen: http://codepen.io/anon/pen/akxxOk

Comments