将表单重置为特定值

Reset form to specific value

本文关键字:表单      更新时间:2023-09-26

我正在尝试编写重置后将 rrpmax 设置为 3000 的代码。它适用于IE,但在Firefox和Chrome中不起作用。

    <html>
<head>
<script type="text/javascript">
function formReset()
{
var fields = document.getElementsByTagName( "input" );
for ( i = 0; i < fields.length; i++ )
{
if ( fields[ i ].type == "checkbox" )
fields[ i ].checked = false;
}
document.getElementById( 'rrpmax' ).selectedIndex = 3;
}
</script>
</head>
<body>
<input type="button" value="reset" onclick="formReset()"/>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<select id="rrpmax">
<option>1000</option>
<option>2000</option>
<option>3000</option>
</select>
</body>
</html>
这是一个

常见的错误

1)首先,索引从零开始,您应该瞄准index 2

2)其次是浏览器兼容性,以防忘记在javascript中的适当用法 用作设置选择的名称和值

<select name="rrpmax" id="rrpmax">
<option value="1000">1000</option>
<option value="2000">2000</option>
<option value="3000">3000</option>
</select>

3)您可以使用

document.getElementById( 'rrpmax' ).value='3000';

只使用表单提供的reset功能怎么样?
不使用任何JavaScript

<form>
    <input type="reset" value="reset"/>
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
    <select id="rrpmax">
        <option>1000</option>
        <option>2000</option>
        <option selected>3000</option>
    </select>
</form>

http://jsfiddle.net/P6RR6/演示

尝试为您的选项赋予值

<select id="rrpmax">
    <option value="1000">1000</option>
    <option value="2000">2000</option>
    <option value="3000">3000</option>
</select>

并编辑选择的吸引力

document.getElementById('rrpmax').value = 3000;

你可以添加selected参数http://www.w3schools.com/tags/att_option_selected.asp