简体   繁体   中英

Button click not working in javascript

I'm trying to do a click in a html button through javascript , but I can't make it work.

This is the button I'm trying to click with javascript (it works when I click it)

<button id="btnClean" runat="server" type="button" class="btn btn-warning btn-cons m-b-10" onserverclick="btnClean_Click">
    <i class="fa fa-trash-o"></i>
    <span class="bold m-l-3">Limpar</span>
 </button>

This is the button that calls the javascript function:

<button id="btnCreateOS" type="button" class="btn btn-success btn-cons m-b-10" onclick="Clean();">
    <i class="fa fa-save"></i>
    <span class="bold m-l-3">Criar</span>
</button>

And this is my javascript (it is located under <form> tag in my .aspx page):

<script type="text/javascript">        

    function Clean() {

        document.getElementById("btnClean").click();

    }

</script>

And finally, this is the asp method:

public void btnClean_Click(object sender, EventArgs e)
{
   CleanFields();
}

Any ideas what I'm doing wrong?

Bsically what happens, when you are using master and content page then it always changes its id according to it default behavior.

function Clean() {
        //document.getElementById("btnClean").click()

        document.getElementById('<%= btnClean.ClientID %>').click();
    }

Another solution you just add ClientIdMode="Static" .

<button id="btnClean" runat="server" clientidmode="Static" type="button" class="btn btn-warning btn-cons m-b-10" onserverclick="btnClean_Click">
        <i class="fa fa-trash-o"></i>
        <span class="bold m-l-3">Limpar</span>
    </button>

in your button..

Then your current javascript code will also work..

function Clean() {
        document.getElementById("btnClean").click();

        //document.getElementById('<%= btnClean.ClientID %>').click();
    }

You should use

document.getElementById("btnClean").trigger("click");

instead, because it's faster. Maybe you should also try to prevent default behaviour in btnClear_Click? Try to add a console.log("a") (or rather "b" at the second) to your two functions, to see, if and which of the two functions are running.

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