Reputation: 542
i have a small problem in my code when i try to update the value in the variable "a" to class attribute of label tag. Can anyone help me out. here is my code
<html>
<head>
<style>
label.visible {visibility:visible}
label.hidden {visibility:hidden}
</style>
<script type="text/javascript">
var a;
function doset()
{
a="hidden";
alert(a);
return a;
}
</script>
</head>
<body>
<form>
<label class=visible>Hello</label>
<button onclick="doset()">v</button><br>
<label class=a>Hello1</label><br>
<label class=a>Hello2</label><br>
<label class=a>Hello3</label><br>
<label class=a>Hello4</label><br>
<label class=a>Hello5</label><br>
</form>
</body>
</html>
Here is the fiddle : http://jsfiddle.net/M8CXN/
Upvotes: 0
Views: 326
Reputation: 4524
<html>
<head>
<style>
label.visible {visibility:visible}
label.hidden {visibility:hidden}
</style>
<script type="text/javascript">
function setLabelsClass(){
var form = document.getElementsByTagName('form');
var labels = form[0].getElementsByTagName('label');
for(var i=0,len=labels.length;i<len;i++){
var lbl_class = labels[i].getAttribute('class');
if(lbl_class==="") labels[i].setAttribute('class','hidden');
}
}
</script>
</head>
<body>
<form>
<label class=visible>Hello</label>
<button onclick="setLabelsClass(); return false;">v</button><br>
<label>Hello1</label><br>
<label class="">Hello2</label><br>
<label class="">Hello3</label><br>
<label class="">Hello4</label><br>
<label class="">Hello5</label><br>
</form>
</body>
</html>
Not a good approach after all if you don't provide AJAX since your form doesn't submit anymore. On second thought I have the feeling you might not understand what I'm talking about here but you'll get to it.
Upvotes: 0
Reputation: 175776
class=a
This does not bind the class name to the javascript global variable a
; they are different things in different contexts.
If you want to manipulate classes you must do so via the DOM. The simplest way is to use a container;
<div id="myItems">
<label>Hello1</label><br>
<label>Hello2</label><br>
...
and
function doset() {
a="hidden";
document.getElementById("myItems").style.visibility = a;
alert(a);
}
called with
<button onclick="doset(); return false;">v</button><br>
Upvotes: 1
Reputation: 16703
If you give all the relevant labels the same class:
<label class="myclass">Hello1</label><br>
<label class="myclass">Hello2</label><br>
<label class="myclass">Hello3</label><br>
You can then target these and add or remove the class you want:
$('.myclass').addClass('hidden');
$('.myclass').removeClass('hidden');
or just:
$('.myclass').hide();
$('.myclass').show();
(using jQuery)
Upvotes: 0