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