JQuery variable in selector

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

to work but doesn't work $('.mk[value=1]')

. Please help someone.

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

      

+3


source to share


6 answers


You need to add a variable x

to the line:

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

      



Also, you should notice that value

this is not a valid attribute span

, so this code causes validation issues.

+7


source


Try the following:



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

      

+1


source


You need to either concatenate it into a 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 are already using each

on them you can do filtering there

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

      

+1


source


The reason it doesn't work is because it '.mk[value=x]'

is a standard string and is not parsed.

Try changing the selector to '.mk[value=' + x + ']'

and x will be replaced with the value of the variable.

+1


source


change this value

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

      

to

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

      

0


source


You need to put your value in the select 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>')
 });
})

      

0


source







All Articles