Reputation: 411
There are 5 no. of buttons(images). Initially all are off image. Only 1 may be on at a time. So when i press any button that img's src changes to on.png. Then when I press any of those on or off buttons, the pressed button source img changes to on.png and all other on img also change to off.png.
The html code is,
<table cellspacing="0" style="padding:0%; margin:0% auto;">
<tr><td><img id="img1" src="off.png" height="30" width="30" onclick="off(this.id);" /></td><td>45:78</td></tr>
<tr><td><img id="img2" src="off.png" height="30" width="30" onclick="off(this.id);" /></td><td>45:78</td></tr>
<tr><td><img id="img3" src="off.png" height="30" width="30" onclick="off(this.id);" /></td><td>45:78</td></tr>
<tr><td><img id="img4" src="off.png" height="30" width="30" onclick="off(this.id);" /></td><td>45:78</td></tr>
<tr><td><img id="img5" src="off.png" height="30" width="30" onclick="off(this.id);" /></td><td>45:78</td></tr>
</table>
The javascript code is,
function off(a)
{
var images = document.getElementsByTagName('img');
for(var i = 0; i < images.length; i++)
{
var img = images[i];
alert(img.src);
if(img.src == 'on.png')
{
img.src = 'off.png';
}
}
document.getElementById(a).src='on.png';
}
The if() condition is not working, Please provide solution and explain why its not
working. Thank you!
Upvotes: 0
Views: 17128
Reputation: 377
You have described a behavior of radiogroup. You do not need to implement it, it is not a good practice to implement standard elements. Why you do not use something like this:
<radiogroup class="custom-radio">
<input type="radio" name="myRadio" value="1">
<input type="radio" name="myRadio" value="2">
<input type="radio" name="myRadio" value="3">
<input type="radio" name="myRadio" value="4">
<input type="radio" name="myRadio" value="5">
</radiogroup>
You can customize radiobuttons how you want, and it will work without javascript.
Upvotes: 0
Reputation: 18472
You can use match
:
img.src.match('on.png')
Or with a regex (that makes sure it's at the end of the string):
img.src.match(/on\.png$/)
Upvotes: 0
Reputation: 600
img.src will return the full path of the image (/full/path/to/on.png) rather than what the src attribute is set to in the markup (on.png). Instead use:
if (img.getAttribute('src') === 'on.png')
Upvotes: 10
Reputation: 1789
What is the alert(img.src);
showing? If I try on stackoverflow something like:
images[0].src = 'on.png';
images[0].src == "http://stackoverflow.com/questions/18149043/on.png"
, not "on.png" (it's relative to the current page).
Upvotes: 2