Reputation: 5
I'm not a programmer so I hope you will pardon me if I will write not correct things.
I have two fieldset with two different "id"
I tried to write a code in javascript that when I show the 1st the 2nd will be hided and viceversa.
I can't understand where I'm doing wrong. Can you help me? Here html
<label onclick="add()"></label>
<label onclick="modify()"></label>
<fieldset id="add">some text</fieldset>
<fieldset id="modify">some other text</fieldset>
and here my javascript text
function add() {
var x = document.getElementById('add');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
function modify() {
var y = document.getElementById('modify');
if (y.style.display === 'none') {
y.style.display = 'block';
x.style.display = 'none';
} else {
y.style.display = 'none';
}
}
the problem is that not only I would like that when I do click on the first it open and with another click it will close but also that when 1 fieldset is shown, the other will be hided and viceversa.
Thank you
Upvotes: 0
Views: 67
Reputation: 1477
You can use below function
function hideShow(targetId) {
var targetNode = document.getElementById(targetId);
if(targetNode.style.display === 'block') {
return; // If click is on the node which is already shown, just return
}
var x = document.getElementById('add');
var y = document.getElementById('modify');
if (x.style.display === 'none') {
x.style.display = 'block';
y.style.display = 'none';
} else {
y.style.display = 'block';
x.style.display = 'none';
}
}
And use same function for both,
<label onclick="hideShow('add')"></label>
<label onclick="hideShow('modify')"></label>
<fieldset id="add">some text</fieldset>
<fieldset id="modify">some other text</fieldset>
Upvotes: 1
Reputation: 2138
Simple fix, if you want to get working.
function add() {
var x = document.getElementById('add');
var y = document.getElementById('modify');
if (x.style.display === 'none') {
x.style.display = 'block';
y.style.display = 'none';
} else {
x.style.display = 'none';
}
}
function modify() {
var x = document.getElementById('add');
var y = document.getElementById('modify');
if (y.style.display === 'none') {
y.style.display = 'block';
x.style.display = 'none';
} else {
y.style.display = 'none';
}
}
As you can see both has x and y var so that none of them is undefined. To move to clean code, you may wish to bring the var outside of the methods(reduce redundancy of the code)
Upvotes: 0
Reputation: 907
You need to define x in your modify function. Or like @ibrahim said, just defined both variables outside the sope
function modify() {
var y = document.getElementById('modify');
var x = document.getElementById('add')
if (y.style.display === 'none') {
y.style.display = 'block';
x.style.display = 'none';
} else {
y.style.display = 'none';
}
}
Upvotes: 0