john
john

Reputation: 1273

How to add a class to an input when input containes a certain value with jquery

i have a form with 4 input fields.

<input class='radio' type='radio' name='radiovote' value='<?php echo $key; ?>'>
<input class='radio' type='radio' name='radiovote' value='<?php echo $key; ?>'>
<input class='radio' type='radio' name='radiovote' value='<?php echo $key; ?>'>
<input class='radio' type='radio' name='radiovote' value='<?php echo $key; ?>'>

One of these input has the value 2. I want to add a class alert-success to this input field which contains the value 2

I tried this but it does not work:

$('input:contains("2")').closest('.radio').addClass('alert alert-success'); 

Upvotes: 1

Views: 37

Answers (1)

MEDZ
MEDZ

Reputation: 2295

Assuming this happen on page load(not after the page is loaded) .You can use jQuery's .filter()to filter by value:

$('input').filter('[value=2]').addClass('alert alert-success');

If the value changes to 2 after the page is loaded. You need to attach an event:

$('input').change((event) => {
   $(this).addClass('alert alert-success');
});

Upvotes: 2

Related Questions