Search code examples
javascriptsyntaxonclickdom-eventsonclicklistener

Function to refresh captcha, works on iPhone, not on desktop browsers


Here's my page where I have a function to refresh the captcha (if you click on "clicca qui" it should change the image). I'm 100% sure it worked some months ago and now it doesn't without me changing anything. The call to the function was <a href="javascript: refreshCaptcha();">. I noticed though that on iPhone it worked. So I thought it was a problem of some browsers that didn't accept the "javascript:" syntax. Then I changed it to <a href="#" onclick="refreshCaptcha();return false;"> (as it is now, "live"). This changed nothing, still works (image changes) on iPhone, doesn't change on desktop browsers (tried with IE and Firefox).

Firebug console doesn't say anything.

What's happening?


Solution

  • I can not seem to find the reason but an empty string is returned when attempting to get the src like document.images[4].src. It only happens in FF so I am stumped more there. You can however access the image source using .getAttribute("src") and set it using .setAttribute("src", "value").

    Try the following code:

    function refreshCaptcha(){ 
      var img = document.images['captchaimg'];
      imgSrc = img.getAttribute("src");
      newImgSrc = imgSrc.substring(0,imgSrc.lastIndexOf("?"))+"?rand="+Math.random()*1000;
      img.setAttribute("src", newImgSrc);
    }
    

    Also, please don't link to your site. It is okay to link to a fiddle but as soon as you make these changes on the site your question will no longer be of any help to the community.