Cam
Cam

Reputation: 2188

How do I create a textfield when a certain selection is made inside a <select> element?

I'm trying to create a basic web form that contains a couple of drop-down select elements. Both of these elements have an 'other - please specify' option, and I wish for a textfield to automatically appear under the drop-down box whenever the 'other' option is selected, and to have the textfield disappear if the option is changed from 'other' to a different option.

I am at a loss as to how to do this, can anyone help?

Upvotes: 0

Views: 75

Answers (4)

MikeM
MikeM

Reputation: 27405

example jsfiddle

HTML

<select id="aDropDown">
    <option value=1>1</option>
    <option value=2>2</option>
    <option value=3>3</option>
    <option value=other>Other</option>
</select>
<p id="aDropDownOther" class="other-label">Other Label</p>​

JS

var ele_aDropDownOther = document.getElementById('aDropDownOther');

document.getElementById('aDropDown').onchange = function() {
    if (this[this.selectedIndex].value === "other") {
        ele_aDropDownOther.style.display = "block";
    } else {
        ele_aDropDownOther.style.display = "";
    }
}​

CSS

.other-label {display:none;}​

OR similarly using jQuery

example jsfiddle

JavaScript/jQuery

var $aDropDown = $('#aDropDown'),
    $aDropDownOther = $('#aDropDownOther');

$aDropDown.change(function() {
    if ($aDropDown.val() === "other") {
        $aDropDownOther.show();
    } else {
        $aDropDownOther.hide();
    }
});​

Upvotes: 0

Anoop
Anoop

Reputation: 23208

Working code on jsfiddle

JS:

document.getElementById("sid").onchange= function(){

    if(this.value == 'Other'){
       document.getElementById("other").style.display = '';
    }
    else{
          document.getElementById("other").style.display = 'none';
    }
}​

HTML:

<select id='sid'>
<option>1</option>
<option>2</option>
<option>Other</option>
</select>
<input id='other' style='display:none' /> ​

Upvotes: 1

Mitch Dart
Mitch Dart

Reputation: 1369

on your select tag you can add an onchange="changed()" attribute. Then create a javascript function called changed.

Use Jquery for the rest.

For example

function changed() {
    if($('#idOfSelect').val() == "Other") {
        $('#idOfSelect').after("<textbox>bla bla</textbox>");
    }
}

Something like that.

Upvotes: 0

Nick B.
Nick B.

Reputation: 23

You could use CSS to accomplish this. Try this page http://www.coderanch.com/t/112986/HTML-CSS-JavaScript/Show-hidden-text-field.

Upvotes: 0

Related Questions