我正在我的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>发布于 2018-06-11 16:26:37
我向您的console.log函数中添加了一个showMe,以确认页面加载时没有调用它(如果您不使用控制台进行调试,这将非常有用!)我不相信你选择的那批货做了什么。
这是我用来测试如何解决问题的代码:
<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来完成这两种操作。
如果有用就告诉我!
https://stackoverflow.com/questions/50729145
复制相似问题