manx
manx

Reputation: 37

If input value equals specific string add class

I know there is some topics similiar to this one. But those didnt hel me. I have html like this:

<span class="wpcf7-list-item first">
 <label>
  <input type="checkbox" name="checkbox-143[]" value="customer service">
  <span class="wpcf7-list-item-label">medicine</span>
 </label>
</span>

For now I have jquery like this:

$(document).ready(function(){
  if ($("input").val() == "customer service") {
      $(this).addClass("cust-serv");
  }
});

What I whand to do is add Class to input when it has specivic value. In this example this value is "customer service" and I want to add class "cust-serv".

Can You help me with that? Thx!

Upvotes: 0

Views: 788

Answers (4)

Sanjeev Kumar
Sanjeev Kumar

Reputation: 85

Simply do by using

$(document).ready(function(){ 
$("input").each(function(){
if($(this).val() == "customer service"){
 $(this).addClass("cust-serv"); 
}});
 });

Upvotes: 0

L&#233;o R.
L&#233;o R.

Reputation: 2698

In your example, "this" is not linked to your class so replace :

$(this).addClass("cust-serv");

with :

  $("input").addClass("cust-serv");

Upvotes: 0

guradio
guradio

Reputation: 15555

  1. Loop through all the input so you can use the context this

$("input").each(function() {
  if ($(this).val() == "customer service") {
    $(this).addClass("cust-serv");
  }


})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="wpcf7-list-item first">
 <label>
  <input type="checkbox" name="checkbox-143[]" value="customer service">
  <span class="wpcf7-list-item-label">medicine</span>
</label>
</span>

Upvotes: 2

void
void

Reputation: 36703

In your code this does not refers to your input field. So instead of using this use "input" again

$(document).ready(function(){
  if ($("input").val() == "customer service") {
      $("input").addClass("cust-serv");
  }
});

Though I would suggest you to use some more specific class as a selector.

Upvotes: 1

Related Questions