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?
2 Answers 2
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();
}
1 Comment
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.
2 Comments
Uncaught TypeError: Cannot read property 'trigger' of null(...)
.trigger
is a jQuery method, not native javascript. 2) Even if this worked, it would be semantically the same as OP's existing call to click()
. 3) even if this worked, it would only trigger the client-side event of btnClean
, which the button doesn't have - it has a server-side event which the OP is trying to call.
id
? Is the post-back invoked?document.getElementById("btnClean").click();
will call client event ofbutton