Deathlex
Deathlex

Reputation: 184

jQuery hide/show element depend on html select value

I am sure its something trivial, even so i have a problem with hiding/showing element via jQuery depand on selected value on html form. I have this html:

HTML

<select name="town" id="town" onchange="otherTown()">
    <option value="1">New York</option>
    <option value="2">Washington</option>
    <option value="3">London</option>
    <option value="4">Other</option>
</select>

<div id="alt_town" style="display:none;">
    <label for="right-label" class="right inline">Other Town</label>
    <input type="text" id="right-label" name="alt_town">
</div>

JS

function otherTown() {
    $('#town').on('change', function () {
        if ($(this).val() === "4") {
            $("#alt_town").show()
        } else {
            $("#alt_town").hide()
        }
    });
}

When user choose "Other" option in select, "Other Town" form show up. It works but only after i choose something else before "Other" option (for example "London" option). I need to element shows even if "Other" is first choice.

Thank you guys for help.

Upvotes: 1

Views: 2965

Answers (3)

Ajay Thakur
Ajay Thakur

Reputation: 1072

You can use this :

$('#town').change(function () {
    if($(this).val()==parseInt("4"))
       {
       $('#alt_town').show();
       }else{
            $('#alt_town').hide();
       }
    });

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

The problem is your inline event handler, you are registering the jQuery change handler(which is toggling the display) only in the inline event handler, so when the first change is happening there is no jQuery handler to execute so nothing happens.

When the second change is triggered, you have the handler registered in the previous event that gets invoked and the display is changed, but it will cause multiple change event handlers to be invoked since each change will add a new jQuery event handler

There is no need for the inline handler

//dom ready handler
jQuery(function($) {
  $('#town').on('change', function() {
    //use toggle for ease of use
    $("#alt_town").toggle(this.value == 4)
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="town" id="town">
  <option value="1">New York</option>
  <option value="2">Washington</option>
  <option value="3">London</option>
  <option value="4">Other</option>
</select>

<div id="alt_town" style="display:none;">
  <label for="right-label" class="right inline">Other Town</label>
  <input type="text" id="right-label" name="alt_town">
</div>

Upvotes: 3

A. Wolff
A. Wolff

Reputation: 74410

Bind handler using jQuery (so remove onchange="otherTown()"). Then using jQuery toggle() method:

$(function() { // shothand for document ready pseudo event, if needed
    $('#town').on('change', function () {
        $("#alt_town").toggle(this.value === "4");
    });
});

Upvotes: 1

Related Questions