我仍然在学习javascript并需要一些帮助来改变基于所选选项值的“动作”形式。请参阅下面的html代码:
<form method="post" title="myForm" id="myForm" name="myForm" action="test_auth.php">
<fieldset>
<legend>Request Details</legend>
<p><label>Brand: </label>
<select id="Brand" name="Brand">
<option value"">Select...</option>
<option value="brand">Brand 1</option>
<option value="brand">Brand 2</option>
<option value="brand">Brand 3</option>
<option value="brand">Brand 4</option>
<option value="brand">Brand 5</option>
</select>
</p>
<br />
<p class="submit"><input class="button" name="Submit" type="submit" value="Submit" onclick="actionDetermine();" /></p>
所以基本上当选择“Brand 1”选项时,我想将表单“action”更改为test.php。我已经写了一些javascript,见下文,但提交“Brand 1”时提交的表单错误
function actionDetermine() {
var thisform = document.myForm;
if (thisform.elements["brand"] [1].selectedIndex) {
thisform.action ="test.php";
} else if (thisform.elements["brand"] [2].selectedIndex) {
thisform.action="test_auth.php";
} else if (thisform.elements["brand"] [3].selectedIndex) {
thisform.action="test_auth.php";
} else if (thisform.elements["brand"] [4].selectedIndex) {
thisform.action="test_auth.php";
} else if (thisform.elements["brand"] [5].selectedIndex) {
thisform.action="test_auth.php";
} else if (thisform.elements["brand"] [0].selectedIndex) {
thisform.action="test_auth.php";
}
return true;
};
显然上面有问题,有人可以帮帮我吗?
干杯!
答案 0 :(得分:2)
您还可以在数据集中定义操作:
<form method="post" title="myForm" id="myForm" name="myForm" onsubmit="submit_function(this)" action="test_auth.php">
<fieldset>
<legend>Request Details</legend>
<label>Brand: </label>
<select id="Brand" name="Brand">
<option value"">Select...</option>
<option value="brand 1" data-action="test.php">Brand 1</option>
<option value="brand 2">Brand 2</option>
<option value="brand 3">Brand 3</option>
<option value="brand 4">Brand 4</option>
<option value="brand 5">Brand 5</option>
</select>
<button class="button" name="Submit" value="Submit">Submit</button>
</fieldset>
</form>
在您的javascript代码中,您可以:
function submit_function(form) {
var selected = document.getElementById('Brand');
var dataset = selected[selected.selectedIndex].dataset;
if (dataset.action) {
form.action = dataset.action;
}
return true;
};
答案 1 :(得分:0)
我会交换
<input class="button" name="Submit" type="submit" value="Submit" onclick="actionDetermine();" />
到
<input class="button" type="button" value="Submit" onclick="actionDetermine();" />
然后我会让<select>
代码<options>
的值为1,2,3,4。然后使用您的代码执行以下操作。
var actions = ['brand1_process.php', 'brand2_process.php', 'brand3_process.php', 'brand4_process.php'];
//actions correspond to the values of the selector
var brand = document.getElementById('Brand').value;
brand = brand-1;
document.getElementById('myForm').setAttribute('action', actions[brand]);
document.getElementById('myForm').submit();
我很确定这是你需要做的,虽然我很长时间没有弄乱表格。