SoulieBaby
SoulieBaby

Reputation: 5471

on select display textbox with jquery?

I'm sure this is super easy, but I can't seem to think what I'm doing wrong, anyway I have a "title" select list for my form, and I want to display a textbox if "Other" is selected.

<select name="title" id="title" class="required">
    <option value="" selected="selected">- Select Title -</option>
    <option value="Ms.">Ms.</option>
    <option value="Mrs.">Mrs.</option>
    <option value="Mr.">Mr.</option>
    <option value="Dr.">Dr.</option>
    <option value="Prof.">Prof.</option>
    <option value="Rev.">Rev.</option>
    <option value="Other" onclick="showOther();">Other</option>
</select>

function showOther() {
  jQuery("#otherTitle").show();
}

But that's not working.. the #otherTitle textbox is hidden using jquery when the page loads.

Upvotes: 1

Views: 2572

Answers (4)

karim79
karim79

Reputation: 342635

I would suggest a different approach:

$("#title").change(function() {
    if($(this).find("option:last").is(':selected')) {
        $("#otherTitle").show();
    } else {
        $("#otherTitle").hide();
    }
});

That is, if the last option is selected, show the textbox that goes by the ID otherTitle. I actually use this method. Hope that helps. Of course, your 'Other' field must always be last for this to work - plus it's rather handy for multilingual sites.

Upvotes: 2

Pointy
Pointy

Reputation: 413727

  1. Use jQuery to bind your event handlers instead of the "onfoo" element attributes
  2. You're better off binding the handler to the "select" element, because there are ways in which the option can be selected that won't involve a "click" event:

(some text to make stackoverflow show the code block below)

$(function() {
  $('#title').change(function() {
    if ($(this).val() == 'Other')
      $('#otherTitle').show();
    else
      $('#otherTitle').hide();
  });
});

I'd prefer to give the "Other" option an "id" value rather than relying on the "value", but whatever.

Upvotes: 1

Russ Cam
Russ Cam

Reputation: 125488

$(function() {    
    $('#title').change(function() {
      if (this.value === "Other") {
        $("#otherTitle").show();
      }
      else {
        $("#otherTitle").hide();
      }     
    });    
});

and a Working Demo. add /edit to the url to see the code

Upvotes: 1

Juraj Blahunka
Juraj Blahunka

Reputation: 18523

Bind an event to your select list, when its changed, look at the value and do your hiding / showing

$(function(){

    $("#title").change(function () {
        if ($(this).val() == 'Other') {
            $("#otherTitle").show();
        }
    });

});

Upvotes: 1

Related Questions