我使用3个选项
创建了一个表单来保存参数- ABC
- DEF
- OTHER
当我选择ABC时会保存id = 1
当我选择DEF时,将保存id = 2
但是当我选择OTHER时,javascript技巧会显示其他带选项的选择框
- GHI
- JKL
当我选择GHI时会保存id = 3
当我选择JKL时会保存id = 4
问题是它只在我选择GHI和JKL时有效,但是当我选择ABC或DEF时,不保存id = 1或id = 2.
也许我需要写一个条件。
以下是演示:
请有人帮助我吗?
答案 0 :(得分:1)
试试这个:
<form action="#" class="new_invoice" id="new_client_form" method="post">
<select id="select1">
<option value="">PLEASE SELECT AN OPTION</option>
<option value="1">ABC</option>
<option value="2">DEF</option>
<option value="A">OTHER</option>
</select>
<select id="info1" style="display: none;">
<option value="3">GHI</option>
<option value="4">JKL</option>
</select>
<input id="invoice_submit" name="commit" type="submit" value="Create">
</form>
var select1 = document.getElementById("select1");
var select2 = document.getElementById("info1");
select1.onchange = function () {
if (select1.value == "A") {
select2.style.display = "inline";
select1.removeAttribute('name');
select2.setAttribute('name', "select1");
}
else {
select2.style.display = "none";
select2.removeAttribute('name');
select1.setAttribute('name', "select1");
}
};
//this section used to serialize the form data and display it in alert box.
//don't use this in your project it is used for demo.
$("#new_client_form").on("submit", function (evt) {
evt.preventDefault();
alert($(this).serialize());
});
以下是更新的 Demo
答案 1 :(得分:1)
您可以尝试这个例子:
<强> HTML 强>
<form onsubmit="return showId()" action="#">
<select onchange="mainId(this.value)" id="main">
<option value="1">ABC</option>
<option value="2">DEF</option>
<option value="">OTHER</option>
</select>
<select id="sub">
<option value="3">GHI</option>
<option value="4">JKL</option>
</select>
<input type="hidden" name="id" id="id"/>
<input type="submit"/>
</form>
<强>脚本强>
var showId = function()
{
console.log('showId');
var id = document.getElementById('id');
var v = document.getElementById('main').value;
if('' == v)
{
v = document.getElementById('sub').value;
}
id.value = v;
alert(id.value);
return false;
};
var mainId = function(v)
{
console.log('mainId: ' + v);
var sub = document.getElementById("sub");
sub.style.display = ('' === v ? 'inline-block' : 'none');
};