使用javascript比较来自表单的下拉菜单中的值

时间:2013-01-25 17:37:40

标签: javascript

在我的表单上,我使用了javascript来验证用户输入,但是我想比较两个不同下拉菜单的值来检查它们是不一样的。 两个下拉菜单“拿起位置”和“目的地”包含完全相同的城镇名称,因此用户可以轻松地为两者选择相同的城镇,这是我不想要的。 如果可能的话,如何实现这一目标?感谢

代码:

function validateFormOnSubmit(theForm) {
var reason = "";

reason += validatepickuplocation(theForm.pickuplocation);

if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}

return true;
}

function validatePickuplocation(fld) {
var pickuplocation = document.getElementById("pickuplocation");
var destination = document.getElementById("destination");

if (pickuplocation.options[pickuplocation.selectedIndex].value ==   destination.options[destination.selectedIndex].value) {
fld.style.background = 'Yellow';
error = "Make sure 'Pick up location' and 'Destination' are not the same locations.\n"
} else {
fld.style.background = 'White';
}
return error;
}

HTML:

<tr>
<td><label for="pickuplocation">Pick up location:</label></td>
<td><select name="pickuplocation" size="1">
<OPTIONS>
</select></td></tr>

<tr>
<td><label for="destination">Pick up location:</label></td>
<td><select name="destination" size="1">
<OPTIONS>
</select></td></tr>

1 个答案:

答案 0 :(得分:1)

当然,只需将每个下拉框值设置为单独的变量并进行比较:

var a = document.getElementById("dropDownA");
var b = document.getElementById("dropDownB");

if (a.options[a.selectedIndex].value == b.options[b.selectedIndex].value) {
    // Do Some stuff
} else {
    // Do other stuff
}