根据选择值切换输入字段-jQuery和HTML [英] Toggle input fields based on select value - jQuery and HTML

查看:105
本文介绍了根据选择值切换输入字段-jQuery和HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有以下输入字段,默认情况下是隐藏的.

So I have the following input fields, which by default are hidden.

当用户选择一个行业时,相应的字段应该可见.当然,如果选择更改,则前一个字段应切换回隐藏状态,而新选择则切换为显示.

When the user selects an industry, the corresponding field should be visible. Of course, if the selection changes, the previous field should toggle back to hidden, and the new selection toggled to show.

我知道我可以在jquery中有一个条件来切换输入,即

I understand I could just have a conditional inside the jquery that toggles the input i.e.

if(selection == "SaaS") {
   $("#SaaSMeetings").show();
}

但是,我不确定如何根据下拉选择来获取字段以在每个更改"事件上切换.

However, I am not sure how I can get the fields to toggle on each "change" event, based on the dropdown select.

感谢您的任何帮助!

HTML

<label for="">Industry?</label>
    <select id="industry">
        <option value="Telesales">Telesales</option>
        <option value="Media">Media/Advertising</option>
        <option value="SaaS">SaaS</option>
        <option value="Insurance">Insurance</option>
        <option value="Automobile">Automobile</option>
    </select>

<!-- Show Metric Input based on Industry Selection -->

<input type="text" id="telesalesCalls" placeholder="How many calls?" style="display:none">
<input type="text" id="SaaSMeetings"  placeholder="How many meetings?" style="display:none">
<input type="text" id="MediaMeetings" placeholder="How many meetings?" style="display:none">
<input type="text" id="InsuranceCalls" placeholder="How many calls?" style="display:none">

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()与参数一起做出隐藏显示的决定:

Use .toggle() with argument to make show hide decision:

 $("#SaaSMeetings").toggle($(this).val()=="SaaS");

完整代码:

$('#industry').on('change',function(){
  var selection = $(this).val(); 
  console.log("Detected change..." + selection);
  $("#SaaSMeetings").toggle($(this).val()=="SaaS");
});

工作演示

这篇关于根据选择值切换输入字段-jQuery和HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆