admin管理员组文章数量:1435859
Is it possible to call onclick event on button only when certain condition is met ?
F.e.: I would like to call my onclick event if function call returns number > 0, something like: if(checkNoOfRows() > 0) //call onclickevent
Is it possible to do this inline ?
Here's my button onclick event, which I would like to call only when certain condition is fulfilled:
<button id="btnExportXLSPropsChild" onclick="location.href='@Url.Action("exportUserProp", "UserManagement", new { typeToExport = "CHILD" })'">Export</button>
Is it possible to call onclick event on button only when certain condition is met ?
F.e.: I would like to call my onclick event if function call returns number > 0, something like: if(checkNoOfRows() > 0) //call onclickevent
Is it possible to do this inline ?
Here's my button onclick event, which I would like to call only when certain condition is fulfilled:
<button id="btnExportXLSPropsChild" onclick="location.href='@Url.Action("exportUserProp", "UserManagement", new { typeToExport = "CHILD" })'">Export</button>
Share
Improve this question
asked Oct 6, 2015 at 16:06
FrenkyBFrenkyB
7,22717 gold badges74 silver badges125 bronze badges
2
- Do you want to do the check on the server or the client? – James Brierley Commented Oct 6, 2015 at 16:11
- I want to do the check on the client. – FrenkyB Commented Oct 6, 2015 at 16:18
3 Answers
Reset to default 3You can do this check in razor
, but the syntax is a bit messy. You need the <text>
elements so that it doesn't try to parse your onclick
as code on the server:
<div @if (true) { <text>onclick="test"</text> }></div>
However, a better approach would probably be to add the url as an attribute and then bind an event in javascript with the check. Your template will then be something like:
<button id="btnExportXLSPropsChild" data-url="@Url.Action("exportUserProp", "UserManagement", new { typeToExport = "CHILD" })">Export</button>
And then in the javascript with jQuery:
$("#btnExportXLSPropsChild").on('click', function(){
if(checkNumberOfRows() > 0){
var url = $(this).data('url');
window.location.href = url;
}
}
You should remove the inline event and use an event handler instead. From the JavaScript event handler, you can check how many rows exist and conditionally run your function.
$("#btnExportXLSPropsChild").on('click', function(){
if(checkNumberOfRows() > 0){
//code goes here
}
}
Jquery can do the magic for you :
$('button').click(function(){
if(condition > 0)
{
windown.location.href = '@Url.Action("Action","Controller")';
}
});
本文标签: javascriptRazor button onclick call only when condition is trueStack Overflow
版权声明:本文标题:javascript - Razor button onclick call only when condition is true - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745669458a2669483.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论