Javascript 根据用户输入有条件地显示表单字段

Javascript 根据用户输入有条件地显示表单字段,javascript,php,jquery,forms,laravel,Javascript,Php,Jquery,Forms,Laravel,在我的Laravel应用程序中,我有一个selectform字段,其中列出了一组国家: <select id="js-countrySiteSelect"> <option>Select Your Country</option> <option>United States</option> <option>Australia</option> <option>Germ

在我的Laravel应用程序中,我有一个
select
form字段,其中列出了一组国家:

<select id="js-countrySiteSelect">
    <option>Select Your Country</option>
    <option>United States</option>
    <option>Australia</option>
    <option>Germany</option>
    <option>Switzerland</option>
    <option>United Kingdom</option>
</select>
根据用户选择的国家,我想显示或隐藏相应的表单字段:

$('#js-countrySiteSelect').change(function(e) {
  e.preventDefault();
  $('.js-siteSelectLabel').addClass('js-show');
  if ( $(this).val() == 'United States' ) {
    $('.js-siteSelect').removeClass('js-show');
    $('.select-us').addClass('js-show');
  } else if ( $(this).val() == 'Australia' ) {
    $('.js-siteSelect').removeClass('js-show');
    $('.select-australia').addClass('js-show');
  } else if ( $(this).val() == 'Germany' ) {
    $('.js-siteSelect').removeClass('js-show');
    $('.select-germany').addClass('js-show');
  } else if ( $(this).val() == 'Switzerland' ) {
    $('.js-siteSelect').removeClass('js-show');
    $('.select-switzerland').addClass('js-show');
  } else if ( $(this).val() == 'United Kingdom' ) {
    $('.js-siteSelect').removeClass('js-show');
    $('.select-uk').addClass('js-show');
  }
});
但是,由于每个位置下拉列表仍加载到DOM中,因此表单始终提交最后一个
选择的第一个选项-在本例中为UK下拉列表


我如何重构它以便只有可见的
select
元素提交数据?

这是因为您只是隐藏了未使用的选择,如果您将它们标记为禁用,那么这些元素将不会发送到服务器

试到位

$select.hide()
使用


switch语句将清理代码,而不是加载
elseif
。或者更好的方法是,将字段的名称作为数据属性添加到每个可选项中,只需JQuery使用例如
$(“.select[data country='Australia']”)选择匹配项。addClass('js-show')
Yep,就可以了。谢谢。@cralfaro你是隐藏并禁用它还是只是禁用它?@Marvin只是禁用它
$select.hide()
$select.prop('disabled', true)