如何将表单名称动态传递给 javascript 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3316774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 00:49:59  来源:igfitidea点击:

How to pass form name dynamically in to a javascript method?

javascripthtml

提问by Fero

I am trying to pass form name dynamically. But this script is showing an error.

我正在尝试动态传递表单名称。但是这个脚本显示了一个错误。

"document.formName is undefined".How to solve this. Thanks in advance.

“document.formName 未定义”。如何解决这个问题。提前致谢。

<script language="javascript">

function showAll(form,fieldName) {
    var formName = form.name;
    alert(formName);
    document.formName.search_mode.value = "";   
    document.formName.fieldName.value="";
    document.formName.submit(); 
}
</script>
<form name = "dealsManagement" method="post" action="<?=$_SERVER['PHP_SELF']?>">
<input type="hidden" name="search_mode" value="<?php echo $_REQUEST['search_mode'];?>" >
<table border="0" cellpadding="0" cellspacing="0" align="center" width="400" style="padding:2px; border:#ccc solid 1px; margin:15px auto 15px auto;">
<tr>
<td colspan="2" class="text3" align="center" height="35" bgcolor="#cccccc">Search</td>
</tr>
<tr>
<td width="153" height="35" align="right" class="text2" style="padding-right:10px;">Search By  City:</td>
<td width="245"><input type="text" name="city" value= "<?php echo $_POST['city']; ?>" size="24" ></input></td>
</tr>
<tr>
<td height="30">&nbsp;</td>
<td><input name="button" type="button" class="btn" onClick="javascript:dealSearchCity()" value="Search" />
<input name="btnShowAll" type="button" class="btn"value="Show All" onClick="javascript:showAll(this.form,'city');" /></td>
</tr>
</table>
</form>

回答by Pekka

What you are doing is not necessary. You can use formdirectly:

你在做什么是没有必要的。您可以form直接使用:

function showAll(form,fieldName) {
    var formName = form.name;
    alert(formName);
    form.elements.search_mode.value = ""; 
    form.elements[fieldName].value="";     
    form.submit(); 
}

two sidenotes:

两个旁注:

The languageattribute is deprecated, better use

language属性已弃用,更好用

<script type="text/javascript">

and you don't need to prefix event handlers with javascript:.

并且您不需要在事件处理程序前加上javascript:.

回答by Quentin

If you want to use a string rather than a literal property name, you have to use square bracket notation.

如果要使用字符串而不是文字属性名称,则必须使用方括号表示法