How to change a css class on a div tag in jquery based on a certain condition

StackOverflow https://stackoverflow.com/questions/22796498

  •  25-06-2023
  •  | 
  •  

Domanda

I have the following HTML:

<div class="required">
<label for="personID">People</label>
<select name="personID" id="personID"  class="select">
<option value="" selected="selected" >No One Selected</option>
<option value="groupA" >Group A</option>
<option value="groupB" >Group B</option>
...

And I have this HTML:

<div class="visControl optional" style="display: none;">
<label for="refNum">Reference Number</label>
<input type="text" value="" name="refNum" id="refNum">
</div>

And I have the following SCRIPT:

<script>
  $('#personID').change(function() {
    if ($('#personID').val() == 'groupB') $('.visControl').show();
    else $('.visControl').hide();
  }); // end .change()
</script>

My script properly controls the visibility of the Reference Number block. But what I want it to also do is change the class attribute from "optional" to "required" to match the visibility.

In other words, when I show the Reference Number block I want the div.optional to become div.required and when I hide the Reference Number block I want the div.required to become div.optional

È stato utile?

Soluzione

Use .toggleClass():

Change:

if ($('#personID').val() == 'groupB') $('.visControl').show();
else $('.visControl').hide();

to:

if ($('#personID').val() == 'groupB') $('.visControl').show().toggleClass('required  optional');
else $('.visControl').hide().toggleClass('required  optional');

jsFiddle example

Altri suggerimenti

Try:

$('div.optional').addClass('required'); 
$('div.optional').removeClass('optional');
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top