LovinQuaQua
LovinQuaQua

Reputation: 123

jquery addClass and removeClass when an option is selected

i have a select field, where i have two options in it. If an option is selected i want to add and remove Classe from a div!

On firefox its working fine, not on chrome and safari

Here is the code:

<label for="priv-firma-select">Bestellen als</label><br />
<select id="priv-firma-select" name="firma-privat">
  <option id="privat">Privatperson</option>
  <option id="firma">Firma</option>
</select>

Here is the jquery for it:

$j(document).ready(function() {

    $j("#firma").click(function(){
        $j(".input-company").addClass("show");
        $j(".leweb_button_firma").addClass("hide");
        $j(".leweb_button_privat").removeClass("hide");
    }); 
    $j("#privat").click(function(){
        $j(".input-company").removeClass("show");
        $j(".leweb_button_privat").addClass("hide");
        $j(".leweb_button_firma").removeClass("hide");

    });      

});

Upvotes: 2

Views: 4956

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you're adding click event handlers to option elements. This is not well supported. Instead, add a change event handler to the select and check the chosen value.

Also note that you can use toggle() with a boolean argument to show/hide the elements, instead of adding or removing classes. Try this:

var $j = jQuery.noConflict();

$j("#priv-firma-select").change(function() {
  var val = $j(this).val();
  $j('.input-company, .leweb_button_privat').toggle(val == 'firma');
  $j('.leweb_button_firma').toggle(val != 'firma');
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-company">input-company</div>
<div class="leweb_button_firma">leweb_button_firma</div>
<div class="leweb_button_privat">leweb_button_privat</div>

<br /><br />
<label for="priv-firma-select">Bestellen als</label><br />
<select id="priv-firma-select" name="firma-privat">
  <option value="privat">Privatperson</option>
  <option value="firma">Firma</option>
</select>

Upvotes: 3

user3551009
user3551009

Reputation: 174

$j(document).ready(function() {

  $j("#priv-firma-select").change(function(){
    if($(this).val() == "firma"){
      $j(".input-company").addClass("show");
      $j(".leweb_button_firma").addClass("hide");
      $j(".leweb_button_privat").removeClass("hide");
    }
   else{
      $j(".input-company").removeClass("show");
      $j(".leweb_button_privat").addClass("hide");
      $j(".leweb_button_firma").removeClass("hide");

    }
  }); 
});

Upvotes: 0

Related Questions