[英]Accessing HTML form elements with same name from javascript
I am using the following solution ( How to best implement Save | Save and Close | Cancel form actions in ASP.NET MVC 3 RC ) of multiple submit buttons to allow cancel and save from my MVC form: 我正在使用以下多个提交按钮的解决方案( 如何在ASP.NET MVC 3 RC中最佳实现保存|保存并关闭|取消表单操作 ),以允许从我的MVC表单中取消和保存:
<form action="Xxxx" method="post" onsubmit="return validatePost()">
...
<input type="submit" name="actionType" value="Save" />
<input type="submit" name="actionType" value="Cancel" />
</form>
With javascript called onsubmit: 使用名为onsubmit的javascript:
function validatePost() {
if(Blah blah){
return true;
}
}
I only want to do this javascript validation if 'Save' is clicked, but cannot tell which button was clicked from the javascript. 我只想在单击“保存”时执行此javascript验证,但是无法确定从javascript中单击了哪个按钮。
I tried getting the actionType value using document.forms[0].elements["actionType"].value
but could not, as there is more than one item named actionType on the form. 我尝试使用
document.forms[0].elements["actionType"].value
但无法执行,因为表单上有多个名为actionType的项。
Can anyone help? 有人可以帮忙吗?
Thanks 谢谢
You can use id
( http://jsfiddle.net/7p5N5/ ) 您可以使用
id
( http://jsfiddle.net/7p5N5/ )
<form method="post">
<input id="save" type="submit" name="actionType" value="Save" />
<input type="submit" name="actionType" value="Cancel" />
</form>
function validate() {
alert('Validate');
return false; // cancel click, true will submit
}
$("#save").click(function () {
return validate();
});
If you don't want to use id
, you can use $('input[name="actionType"][value="Save"]')
to select the Save button 如果您不想使用
id
,则可以使用$('input[name="actionType"][value="Save"]')
选择“保存”按钮
Are you able to listen to the onclick event of only the 'Save' input and have it use your validatePost function. 您是否能够仅侦听“保存”输入的onclick事件,并使其使用validatePost函数。
Then you could have a different function for the onclick of 'Cancel' to do appropriate action. 然后,您可以为“取消”的onclick设置不同的功能,以执行适当的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.