0

If a user selects a certain option value in one select field, how do you then make a text field hidden, s it will not be needed. This must be done before the form is submitted?

For example in the following select field, a user select chooses value='a' then how would this text field become hidden:

 <select name="form" id="aForm"> <option value="a">choice1</option> <option value="b">choice2</option> <option value="c">choice3</option> </select> <input type="text" style="width:285px" name="textField" id="textField"/> 

2 Answers 2

4
$("#aForm").on("change", function() { if ($(this).val() == "a") $("#textField").hide(); else $("#textField").show(); }); 

Here is also a jsfiddle

I assumed that you will show the textfield for any other value than a.

If you're using plain JavaScript and not jQuery

function hideTF() { var s = document.getElementById("aForm"); document.getElementById("textField").style.display = (s.selectedIndex > 0 && s.options[s.selectedIndex] == 'a' ? "none" : "block"); } var s = document.getElementById("aForm"); if (s.attachEvent) s.attachEvent("onchange", hideTF); else s.addEventListener("change", hideTF, false); 
Sign up to request clarification or add additional context in comments.

11 Comments

Nice solution Adrian, but he is not using jQuery.
I modified my solution for plain JavaScript too.
if(this.val()) should be if($(this).val()) or if(this.value).
Did you put it inside $(document).ready(function(){ // code goes here });
@SheikhHeera: Thanks that was the problem. Works perfectly now. Thanks for both of yours help.
|
2

You can use a variation of this:

var selection = aForm.selectedIndex, field = document.getElementById('textField'); if ( selection === x ) { field.style.display = "block"; // or visibility = "hidden" } 

This should be enclosed in an .onchange event. aForm.selectedIndex is the index of the corresponding <option> element that is selected.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.