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>
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.
Try the following:
$('.mk[value='+x+']').each(
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>');
}
});
})
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.
change this value
$('.mk[value=x]')
to
$('.mk[value='+x+']')
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>')
});
})