简体   繁体   中英

why my webpage is refreshing when i am calling a JavaScript function in my aspx page on a html image click event?

i am using a html image control in mt aspx page and i am calling a javascript function on the click event of that control but here my page is getting refreshed every time i am clicking it

here's my code:

<input id="wbsnew1" type="image" value="New" onclick="showHideDiv()" src="images/New.png" />

and here's my javascript code :

function showHideDiv() {
        document.getElementById("newdata2").style.display = "block";
    } 

"newdata2" is a div

<input id="wbsnew1" type="image" value="New" onclick="return showHideDiv();" src="images/New.png" />

function showHideDiv() {
    document.getElementById("newdata2").style.display = "block";
    return false;
 } 

Try to return after applying the function like the following code :

`<input id="wbsnew1" type="image" value="New" onclick="showHideDiv(); return false;" src="images/New.png" />`  

also let your function return false

function showHideDiv() {  
     document.getElementById("newdata2").style.display = "block";

return false;
}

I suppose that the input tag is located inside some other html element that triggers reloading. Try stopping bubbling:

<input id="wbsnew1" type="image" value="New" onclick="showHideDiv(event)" src="images/New.png" />

function showHideDiv(event) {
        event.stopPropagation();
        document.getElementById("newdata2").style.display = "block";
    } 

<input type="image" /> elements are used to submit the form (in ASP.NET that equals the postback).

You have few alternatives:

  1. (best) Replace the <input> tag to <img /> . The other attributes are the same (except the type attribute is not needed).
  2. Add return false to the onclick handler: <input onclick="showHideDiv(); return false;" .
  3. Return the false value from the method itself and add return keywork to the method

    <input onclick="return showHideDiv();" /> function showHideDiv() { .... return false; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM