Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById('').src == ??? (is equal to FAIL)

Tags:

javascript

My javascript is

function changeImage(imgID) {
var baseurl = "media/images/";
if (document.getElementById(imgID).src == baseurl+"selection-off.png") {
    alert('Success');
    document.getElementById(imgID).src = baseurl+"selection-no.png"; }
else {
    alert('Fail'); } }

and my HTML is

<div id="mustard" class="checkbox"><img id="mustard-img" class="no-off" src="media/images/selection-off.png" alt="checkbox" onClick="changeImage('mustard-img')" /></div>

I always get Fail when clicking the image. I must be missing something really elementary.

like image 418
jsejcksn Avatar asked Oct 19 '10 07:10

jsejcksn


3 Answers

Some browsers convert the img src to the full url (including http://www....)

try alerting it to make sure..

You could use the

document.getElementById(imgID).src.indexOf( baseurl+"selection-off.png" ) >= 0

which checks if one string is contained in the other..

like image 131
Gabriele Petrioli Avatar answered Oct 03 '22 14:10

Gabriele Petrioli


Alert string document.getElementById(imgID).src. It might be taking complete path i.e. including host name while the string you are comparing with has relative path.

like image 38
Chinmayee G Avatar answered Oct 03 '22 16:10

Chinmayee G


I tried your code on my own server.

Result:

document.getElementById(mustard-img).src is 'http://localhost/webfiles/media/images/selection-off.png'

baseurl+"selection-off.png" is 'media/images/selection-off.png'

baseurl seems to show the relative url only. So that is the reason why "Fail" gets alerted.

like image 28
Thariama Avatar answered Oct 03 '22 14:10

Thariama