I just started learning JS and jQuery and have a question. I want to make a dynamic form which can be complex with more then one Selector. The problem is when I open Option1 and then press the other selector with option6 and 7 it disappears but I want it to be visible. I know the problem is the $(‘label’).hide(); but I’m so bad at jQuery and Jscript that I don’t know how to make this work. I would appreciate any help with this.
Here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('label').hide();
$('#sel').change(function() {
var val = $(this).val();
$('label').hide();
switch (val){
case 'option1':
$('#label1').show();
break;
case 'option2':
$('#label2').show();
break;
case 'option3':
$('#label3').show();
break;
case 'option4':
$('#label4').show();
break;
case 'option5':
$('#label5').show();
break;
}
});
$('#sel2').change(function() {
var val = $(this).val();
$('label').hide();
switch (val){
case 'option6':
$('#label6').show();
break;
case 'option7':
$('#label7').show();
break;
}
});
$("input")
.focus(function () {
$(this).next("span").fadeIn(1000);
})
.blur(function () {
$(this).next("span").fadeOut(1000);
});
});
</script>
<style>
label {
display:block;
}
</style>
</head>
<body>
<form>
<select id="sel">
<option value="">- select -</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
<option value="option4">Option 4</option>
<option value="option5">Other</option>
</select>
<label id="label1">
<select id="sel2">
<option value="">- select -</option>
<option value="option6">Option 6</option>
<option value="option7">Option 7</option>
</select>
</label>
<label id="label2" for="option2">Text box label 2
<input type="text" id="option2" />
</label>
<label id="label3" for="option3">Text box label 3
<input type="text" id="option3" />
</label>
<label id="label4" for="option4">Text box label 4
<input type="text" id="option4" />
</label>
<label id="label5" for="option5">Other
<input type="text" id="option5" />
</label>
<label id="label6" for="option6">Text box label 6
<input type="text" id="option6" />
</label>
<label id="label7" for="option8">Text box label 7
<input type="text" id="option7" />
</label>
</form>
</body>
</html>
When you call #sel2, you keep hiding ‘label’ every time (which includes itself). I would change it to: