我正在我的rails应用程序中开发一个表单。使用隐藏/显示功能时出现问题。现在它设置为显示相应的文本框:onchange。如何在视图页面加载时显示相应的文本框?如果有类别的参数,请说“其他”,并且用户将加载到表单中。其他选项不加载它。他们必须单击其他内容,然后再次单击“其他”以加载文本框。
application.css
function showMe(e) {
var strdisplay = e.options[e.selectedIndex].value;
var e = document.getElementById("Other");
var x = document.getElementById("Pcba");
if(strdisplay != "Other") {
e.style.display = "none";
} else {
e.style.display = "block";
}
if(strdisplay != "PCBA") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
查看
<div class="form-group">
<label>Category</label>
<%= f.select(:category, [["Select...","Select..."],["PCBA","PCBA"], ["Other","Other"]], {}, { :class => 'form-control', :onchange => "showMe(this)", :onload => "showMe(this)", :default => 'Select...'})%>
</div>
<div class="form-group" id="Other" style="display: none">
<label>Quantity</label>
<%= f.number_field :quantity, class: "form-control", placeholder: "Enter Quantity", required: true %>
</div>
<div id="Pcba" class="form-group" style="display: none">
<label>Serial Number</label>
<%= f.text_field :serial, class: "form-control", placeholder: "Enter Serial", required: true %>
<br>
<label>Software Revisions</label>
<%= f.text_field :serial, class: "form-control", placeholder: "Enter Serial", required: true %>
</div>
答案 0 :(得分:0)
我在showMe函数中添加了一个console.log,以确认在加载页面时没有调用它(如果你不使用控制台进行调试,那么它非常有帮助!)。我不相信你选择的onload正在做任何事情。
这是我试图解决如何解决问题的代码:
<html>
<head>
<script>
function showMe(e) {
console.log('showMe called');
var strdisplay = e.options[e.selectedIndex].value;
var e = document.getElementById("Other");
var x = document.getElementById("Pcba");
if(strdisplay != "Other") {
e.style.display = "none";
} else {
e.style.display = "block";
}
if(strdisplay != "PCBA") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
window.onload = function() {
showMe(document.getElementById('category'));
};
</script>
</head>
<body>
<div class="form-group">
<label>Category</label>
<select id="category" onchange="showMe(this)" onload="showMe(this)">
<option>Select...</option>
<option selected>PCBA</option>
<option>Other</option>
</select>
</div>
<div class="form-group" id="Other" style="display: none">
<label>Quantity</label>
<input id="quantity" />
</div>
<div id="Pcba" class="form-group" style="display: none">
<label>Serial Number</label>
<input id="serial" />
<br>
<label>Software Revisions</label>
<input id="serial" />
</div>
</div>
</body>
</html>
我正在使用window.onload在页面加载时调用showMe函数。由于期望传递你的select元素,我使用document.getElementById来获取元素并将其传递给showMe函数。您也可以使用jQuery执行这两个操作。
让我知道它是否有效!