根据选择值切换输入字段 – jQuery和HTML
所以我有以下输入字段,默认情况下是隐藏的。
当用户选择行业时,相应的字段应该是可见的。 当然,如果选择更改,则前一个字段应切换回隐藏,并且新选择切换为显示。
我明白我可以在jquery中有一个条件来切换输入,即
if(selection == "SaaS") { $("#SaaSMeetings").show(); }
但是,根据下拉选择,我不确定如何在每个“更改”事件上切换字段。
在此先感谢您的帮助!
HTML
Telesales Media/Advertising SaaS Insurance Automobile
javascript:
$('#industry').on('change',function(){ var selection = $(this).val(); console.log("Detected change..." + selection); //TODO: Show the input field based on this selection, and on each change, make sure the correct field is displayed. });
使用带参数的.toggle()
来显示隐藏决策:
$("#SaaSMeetings").toggle($(this).val()=="SaaS");
完整代码:
$('#industry').on('change',function(){ var selection = $(this).val(); console.log("Detected change..." + selection); $("#SaaSMeetings").toggle($(this).val()=="SaaS"); });
工作演示
只需隐藏所有内容,只显示所选内容。
$('#industry').on('change',function(){ var elms = $('[placeholder^=How]'); elms.hide().filter(function(){ return this.id.toLowerCase().indexOf($(this).val().toLowerCase()) > -1; }).show(); });
我们使用$.fn.filter
来过滤元素然后我们显示它,而其余的已经隐藏了。
使用switch语句,或更改您的选择选项值以匹配您的输入ID;
$('#industry').on('change',function(){ var selection = $(this).val(); console.log("Detected change..." + selection); $(".myInput").each(function(){ $(this).hide(); }); $("#" + selection).show(); });
这是更长的切换方式:
switch(selection){ case "Telesales": $("#telesalesCalls").show(); $("#SaaSMeetings").hide(); $("#MediaMeetings").hide(); $("#InsuranceCalls").hide(); break; }
我将在输入字段上使用数据属性,以指示select元素中应该可见的值。
HTML
使用Javascript
$('#industry').on('change',function(){ // get the selected value var selection = $(this).val(); // get all input fields that has a valueref attribute containing the selected value, and show them var showinputs = $('input[data-valueref~="' + selection + '"]').show(); // hide all other input fields $('input').not(showinputs).hide(); });
这种方法实际上允许您为多个值显示单个输入。 选择SaaS或保险时会显示以下内容
使用额外的类过滤输入字段可能是个好主意,以避免影响同一页面上的其他输入字段。
–
var showinputs = $('input.valueref[data-valueref~="' + selection + '"]').show(); $('input.valueref').not(showinputs).hide();