0

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!

3
  • Do you also want it JS to check when the value changes or just when document is ready? If not you need to reference the addClass() to a specific element not $(this) Commented Feb 13, 2018 at 10:28
  • $(this) is not what you think it is ... Commented Feb 13, 2018 at 10:28
  • 2
    an if - statement does not create its own context. You are adding the class to the document Commented Feb 13, 2018 at 10:28

4 Answers 4

2
  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>

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

Comments

1

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.

Comments

0

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

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

with :

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

Comments

0

Simply do by using

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

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.