Cameron Scott
Cameron Scott

Reputation: 1306

Show form fields conditionally based on user input

In my Laravel app, I have a select form field that lists a set of countries:

<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>

Beneath that, I also have a series of select form fields. Each select shows a series of locations within that country.

{!! Form::select('site_id', $australia, null, ['class' => 'js-siteSelect select-australia', null => 'Select a user...']) !!}
{!! Form::select('site_id', $germany, null, ['class' => 'js-siteSelect select-germany']) !!}
{!! Form::select('site_id', $switzerland, null, ['class' => 'js-siteSelect select-switzerland']) !!}
{!! Form::select('site_id', $us, null, ['class' => 'js-siteSelect select-us']) !!}
{!! Form::select('site_id', $uk, null, ['class' => 'js-siteSelect select-uk']) !!}

Based on which country the user selects, I want to show or hide the corresponding form fields:

$('#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');
  }
});

However, since each location dropdown is still loaded into the DOM, the form always submits the first option of the last select—in this example, the UK dropdown.

How can I refactor this so that only the visible select element submits data?

Upvotes: 1

Views: 2172

Answers (1)

cralfaro
cralfaro

Reputation: 5948

this is because you just hide the not used selects, if you mark them as disabled, then the elements wont be send to the server.

Try in place to set

$select.hide()

use

$select.prop('disabled', true)

Upvotes: 1

Related Questions