Cheerio
Cheerio

Reputation: 1240

Display new field when choose specific value (JS/HTML)

I have this form:

http://dl.dropbox.com/u/14698783/project/register/form.htm

The city input is hidden by default.
I want to display it when the visitor choose USA or Canada only.

Upvotes: 0

Views: 181

Answers (2)

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

For this, I'm using jQuery. First, I set up and event handler for the country dropdown using the change method - this will be raised when the value is changed (not surprisingly). Then test if the value selected is in a set of accepted values (for this, I'm using the 'in' operator). Since this is an input element, I can just reference element.value without wrapping it in jQuery. Finally, use the toggle, passing in the boolean value to indicate if the select should be shown or hidden.

var valuesToShowFor = [0, 1]; // USA + Canada

$("#title").change(function() {
    var shouldShowCity = (this.value in valuesToShowFor);
    $("#city").toggle(shouldShowCity);
});

Example: http://jsfiddle.net/jonathon/xULyc/

For this, I recommend having IDs on your elements. It makes it much easier and neater to do the jQuery selects - otherwise you'd need something like $("input[name='title']") to reference the element.

Upvotes: 2

kapa
kapa

Reputation: 78681

Here are some clues for you:

  1. Catch onchange with jQuery .change()
  2. Get the selected option value with jQuery .val()
  3. If the selection option value is one of those you need, use jQuery .show() to show the other input box (and .hide() to hide it)

Upvotes: 2

Related Questions