我试图从MVC中的select标签调用JS函数onchange。它似乎没有工作。这是代码。
在主页视图中,我有以下div包含select标签
<div class="container">
<!-- beginning of search block -->
<form role="form">
<div class="form-group">
<select class="form-control" id="select1" name="select1" onchange="populate(this.id,'select2')">
<option value="Residential">RESIDENTIAL</option>
<option value="Commercial">COMMERCIAL</option>
</select>
<select class="form-control" id="select2" name="select2"></select>
</div>
</form>
</div>
在_Layout页面中,我使用
引用Scripts文件夹<script src="~/Scripts/searchform.js" type="text/javascript"></script>
我正在调用的javascript函数是
function populate(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value == "Residential") {
var optionArray = ["|", "1bhk|1BHK", "2bhk|2BHK", "3bhk|3BHK", "4bhk|4BHK", "4+bhk|4+BHK"];
}
if (s1.valueOf == "Commercial") {
var optionArray = ["|", "500sft|500SFT", "1000sft|1000SFT", "1500sft|1500SFT", "2000sft|2000SFT", "2500sft|2500SFT"];
}
for (var option in optionArray) {
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
我无法弄清楚为什么函数没有被调用。
答案 0 :(得分:0)
对于第二次检查,您使用的是s1.valueOf
,而不是s1.value
您的功能将是
function populate(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value == "Residential") {
var optionArray = ["|", "1bhk|1BHK", "2bhk|2BHK", "3bhk|3BHK", "4bhk|4BHK", "4+bhk|4+BHK"];
}
if (s1.value == "Commercial") {
var optionArray = ["|", "500sft|500SFT", "1000sft|1000SFT", "1500sft|1500SFT", "2000sft|2000SFT", "2500sft|2500SFT"];
}
for (var option in optionArray) {
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
这对我有用。