0

I have got a form with two inputs (there is a PHP script behind it):

<select id="select1">
  <option>One</option>
  <option>Two</option>
</select>
<input type="text" id="text1" disabled="disabled" />

The PHP script look into a database and mark "One" or "Two" with the selected="selected" attribute.

If "One" is selected, I want to activate the disabled text field. If any other entry is selected (in this example "Two"), the text field should be disabled. I wrote this jQuery code:

<script type = "text/javascript">
  $("#select1").bind('change paste keyup', function() {
    if (this.value == 'One') {
      $("#text1").prop('disabled', false);
    } else {
      $("#text1").prop('disabled', true);
    }
  });
</script>

My Problem: When I visit the page and "One" is preselected, the text field is disabled. I must select "Two" and "One" again. After this, the text field is enabled. I want to check on page load which item is selected. I tried a lot with triggering a change like this, but it did not run:

$(window).bind("load", function() {
  $("#select1").trigger('change paste keyup');
});

I know I could use thinks like .on or .change, but I want to do it with .bind.

How can I call .bind on page load?

mhellmeier
  • 1,982
  • 1
  • 22
  • 35
  • Are you looking for `default selected item`? If right, here you go: http://stackoverflow.com/questions/3518002/how-can-i-set-the-default-value-for-an-html-select-element – Tân Oct 06 '16 at 17:18
  • ps: `if (this.value == 'One') { $("#text1").prop('disabled', false); } else { $("#text1").prop('disabled', true); }` => `$("#text1").prop('disabled', (this.value != 'One'));` – Julian Oct 06 '16 at 17:29

1 Answers1

4

Just trigger the event on pageload

$("#select1").on('change', function() {
    $("#text1").prop('disabled', this.value !== 'One');
}).trigger('change');
  • bind has been superseded by on, and shouldn't be used
  • a select shouldn't have any key events, and can't be pasted to?
  • you can use the condition direcly to set the property

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Thanks a lot for the answer. But can you tell me, why I shouldn't use bind? – mhellmeier Oct 06 '16 at 20:42
  • 1
    Because it's superseded by `on`. There's no other reason than that for now, jQuery hasn't removed `bind`, they just recommend using `on`. Internally they do the same thing, for now! – adeneo Oct 06 '16 at 20:54
  • After I add `$(function () { YOUR CODE });`, it worked like a charm, thanks! – mhellmeier Oct 07 '16 at 13:54