Reputation: 267
I have three text fields, I want to show the first and hide the second and third when option 1 is selected, and the opposite when option two is selected.
I did the following:
<script language="javascript">
function hola(x) {
if(x == 1) {
document.getElementById("div1").style.visibility="visible";
document.getElementById("div2").style.visibility="hidden";
}
if(x == 2) {
document.getElementById("div1").style.visibility="hidden";
document.getElementById("div2").style.visibility="visible";
}
}
</script>
<body onload='hola(1)'>
<label class="field6" for="shower_times">how many showers each takes per day: </label>
<SELECT name="shower_times" onChange="hola(this.value)">
<OPTION value="1">1</OPTION>
<OPTION value="2">2</OPTION>
</SELECT>
<div id="div1">
<BR>
<label class="field6" for="hour"> hour of the shower: </label><input type="text" name="hour" class="input">
</div>
<div id="div2">
<label class="field6" for="hour1">hour of first shower: </label><input type="text" name="hour1" class="input">
<BR>
<label class="field6" for="hour2">hour of second shower: </label><input type="text" name="hour2" class="input">
</div>
It's working find when I change the option, but the problem is that at the beginning I want it to show only the first field, that's why I used
<body onload='hola(1)'>
but it's not working, it's showing all three at the beginning.
the code seems to work alone, but all when I add it to other codes as this one http://jsfiddle.net/3YZBm/1/ , this part is not working the way I mentioned
Upvotes: 1
Views: 10429
Reputation: 8350
If you choose to go with pure JS, you could do something like this...
The HTML (slightly modified)...
<label class="field6" for="shower_times">how many showers each takes per day: </label>
<SELECT name="shower_times" id="mselect" onChange="hola();">
<OPTION value="1">1</OPTION>
<OPTION value="2">2</OPTION>
</SELECT>
<div id="div1">
<BR>
<label class="field6" for="hour"> hour of the shower: </label><input type="text" name="hour" class="input">
</div>
<div id="div2">
<label class="field6" for="hour1">hour of first shower: </label><input type="text" name="hour1" class="input">
<BR>
<label class="field6" for="hour2">hour of second shower: </label><input type="text" name="hour2" class="input">
</div>
</div>
The CSS (optional to hide the 2 fields by default since 1 is selected by default)...
#div2 {
display:none;
}
And the JS modified by Maggie...
function hola() {
var mselect = document.getElementById("mselect");
var mselectvalue = mselect.options[mselect.selectedIndex].value;
var mdivone = document.getElementById("div1");
var mdivtwo = document.getElementById("div2");
if (mselectvalue == 2) {
mdivtwo.style.display = "block";
mdivone.style.display = "none";
}
else {
mdivtwo.style.display = "none";
mdivone.style.display = "block";
}
}
and Maggie's modified solution to back it up!
Upvotes: 1