Kevin Aartsen Kevin Aartsen - 1 month ago 6
HTML Question

jQuery click event on Select element not working as desired on Chrome 54

I have this code:

HTML

<select class="form-control" name="footerLayout">

<option value="">
</option>
<option value="1">
1 column
</option>
<option value="2">
2 column
</option>

</select>


<div class="column column-1">
<h3>Content</h3>

<textarea class="form-control" type="text" name="footerContent"></textarea>
</div>

<div class="column column-2">
<h3>Content2</h3>

<textarea class="form-control" type="text" name="footerContent"></textarea>
</div>


CSS

.column-1 {
display: none;
}

.column-2 {
display: none;
}


Jquery

$('[name=footerLayout]').click(function() {
var selector = ".column-" + $(this).val(); //Create selector
$(".column").not(selector).hide(); //Hide others
$(selector).show(); //Show column based on selected value
});


If i click on an option from the select tag it doesn't show the hidden div right away. I would have to click it 2 times in order for it to work.

try it yourself:

https://jsfiddle.net/mk425srx/

Notice you must click the option 2 times for it to work, I want this to be 1 time. It has to change directly. How do i achieve this.
EDIT
Its working fine in firefox and chrome 53 apparently its a chrome 54 issue..

Answer

You should use change event instead of click

Just change the event in your JS. The updated code looks like

$('[name=footerLayout]').change(function() {
  var selector = ".column-" + $(this).val(); //Create selector        
  $(".column").not(selector).hide(); //Hide others        
  $(selector).show(); //Show column based on selected value
});

See the working fiddle https://jsfiddle.net/mk425srx/2/

Update

The reason of click event not working as expected is because of, click event get fired when the element is clicked but change event is fired after the value get changed. So click event is fired earlier and before the value selection is changed. That's why click event shouldn't be used to detect change of value.

To be clear about this, try the following code to see the fact.

$('[name=footerLayout]').change(function() {
  console.log($(this).val());
});

$('[name=footerLayout]').click(function() {
  console.log('clicked');
});

Fiddle link: https://jsfiddle.net/mk425srx/3/