1

I've this simple code:

HTML:

<input type="text" name="name" class="required" />

<select id="options" name="options" size="1">
  <option value="0"> YES </option>
  <option value="1"> NO </option>
</select>


<input type="text" name="email" />
<input type="text" name="city" />

Question:

I want to add class = "required" to email and city fields when options is equal to 1

4 Answers 4

3

Something like:

$('#options').change(function() {
    $('input[name="email"], input[name="city"]')
       .toggleClass('required', this.value === '1');
});

Reference: change, toggleClass

Sign up to request clarification or add additional context in comments.

1 Comment

I love this new solution. Thank you :)
1

I've added Id's to your input elements to make the selector quicker:

 <input type="text" name="email" id="email" />
 <input type="text" name="city" id="city" />

jQuery:

$("#options").change(function() {
    if ($(this).val() == "1") {
        $("#email, #city").addClass("required");
    }
    else {
        $("#email, #city").removeClass("required");
    }
});

1 Comment

If you're referring to the extra bracket on the if statement - I just removed it.
0
if( $('#options').val() == "1"){
   $('#email, #city').addClass('required');
}

Comments

0

assign ids to the inputs and do following logic , ids are always better as it takes less time to execute in case of complex DOMs.

$('#options').change(function(){
if($(this).val() == 1) {
 $('#inputemail').addClass('required');
 $('#city').addClass('required');
}else {
$('#inputemail').removeClass('required');
 $('#city').removeClass('required');
}
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.