3

I need $('.mk[value=x]') to work, but it does Not while $('.mk[value=1]') does. Please someone help

<body>
<span class="mk" value="1">1</span>
<span class="mk" value="1">1</span>
<span class="mk" value="3">3</span>
<input id="update" type="button" value="1" />
</body>

<script type="text/javascript">
$('#update').click(function(){
    var x = this.value //--> x =1 
       $('.mk[value=x]').each(function(key, value) { //--> NOT WORKING !
       $('.mk[value=1]').each(function(key, value) { //--> WORKING !
       $(this).replaceWith('<span class="mk" value="2">2</span>')
       });
    })
</script>

6 Answers 6

7

You need to append the x variable to the string:

$(".mk[value='" + x + "']").each(function(key, value)

Also, you should note that value is not a valid attribute of span, so this code will cause validation issues.

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

4 Comments

+1 for (aside from being right) quoting the attribute value in the selector.
@MДΓΓБДLL: Quotes for simple attribute values are not required.
@amnotiam they may not be required, but they are good practice IMO.
Thanks a lot for the quick answer !
1

Try that way:

$('.mk[value='+x+']').each(

Comments

1

You need to either concatenate it to the string

$('.mk[value='+ x +']').each(function(key, value)

or use .filter()

$('.mk').filter(function(){return this.value === x;}).each(function(key, value)

or since you already use each on them you can do the filtering there

$('.mk').each(function(key, value) {
      if (this.value === x) {
          this.replaceWith('<span class="mk" value="2">2</span>');
      }
   });
})

Comments

1

The reason why it doesn't work is that '.mk[value=x]' is a standard string and it doesn't get parsed.

Try changing the selector to '.mk[value=' + x + ']' and x will be replaced with the variable's value.

Comments

0

change this

$('.mk[value=x]')

to

$('.mk[value='+x+']')

Comments

0

You need to put your value into the selection string like this:

$('#update').click(function(){
var x = this.value 
 $(".mk[value='" + x + "']").each(function(key, value) {
  this.replaceWith('<span class="mk" value="2">2</span>')
 });
})

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.