LearnProgramming
LearnProgramming

Reputation: 806

How to make dropdown immediately response base on this js code?

I found this original code from other answer(jsfiddle) . What it does is, when the user selected other from dropdown selection, a textbox will appear. But if i put <option value='0' selected>Other</option>, when the page appear for the first time, it doesn't make the textbox appear. How do I solve this?

Code That I change

<option value='0' selected>Other</option>

Upvotes: 0

Views: 50

Answers (3)

Lain
Lain

Reputation: 3726

You have to call the onchange() when the page is ready. Since the onchange() event is only triggered on actual changes from the user.

Example 1: jsfiddle.net/ghLc9/49

$('select').trigger("change");

Example 2: jsfiddle.net/ghLc9/52

$(document).ready(function(){
    $('select').trigger("change");
})

Upvotes: 2

Helping hand
Helping hand

Reputation: 2920

Sorry I couldn't comment as my reputation is less. In Your code, Write

$("#myTxt").show() outside the onchange function,

to load the input, when page appears first time.

Here is the fiddle, http://jsfiddle.net/sanketdhoble/ghLc9/46/

$("#myTxt").show();
$('select').on('change', function() {

  if( this.value  == '0')
    $("#myTxt").show();
  else
    $("#myTxt").hide();
})

Upvotes: 0

Shai Aharoni
Shai Aharoni

Reputation: 1957

what you can do is to extract the textbox's show/hide logic to a function and call this function when the page loads. This is an example of the updated JS code:

var updateMyText = function(){

  var value = $("select").val();

  if( value  == '0')
      $("#myTxt").show();
    else
        $("#myTxt").hide();
}

$('select').on('change', updateMyText)

//Update the UI when the page loads
$(function(){
    updateMyText();
})

This is a link to the updated fiddle : http://jsfiddle.net/ghLc9/53/

Upvotes: 2

Related Questions