What can i add to my JS to toggle the class of the text in the inputs? at the moment the row background gets .remove toggled, but I can not figure out how to toggle class of the text inside the input.
My HTML:
<div class='row shopping'>
<div><input type='text' id='item' value='1'></div>
<div><input type='text' id='cost' value='1'></div>
<div><input type='text' id='group' value='1'></div>
<div><input type='text' id='code' value='1'></div>
</div>
MY JS:
$('.shopping').click(function(){
$(this).toggleClass('remove');
});
MY CSS:
.remove{
background-color:red;
}
CodePudding user response:
Consider the following.
$(function() {
$('.shopping').click(function() {
$("input", this).toggleClass('remove');
});
});
.remove {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='row shopping'>
<div><input type='text' id='item' value='1'></div>
<div><input type='text' id='cost' value='1'></div>
<div><input type='text' id='group' value='1'></div>
<div><input type='text' id='code' value='1'></div>
</div>
<div class='row shopping'>
<div><input type='text' id='item' value='2'></div>
<div><input type='text' id='cost' value='2'></div>
<div><input type='text' id='group' value='2'></div>
<div><input type='text' id='code' value='2'></div>
</div>
When the click
event is called, this
relates to the element that was clicked or called upon. We then want to target the input
elements within that element.
The selector $("input", this)
is the same as $(this).find("input")
, so either can be used.
CodePudding user response:
In this code:
$('.shopping').click(function(){
$(this).toggleClass('remove');
});
The keyword this
refers to the element which has the click
handler attached to it, which in this case is any element with the shopping
class. Without altering the markup, you can instead target the <input>
elements within that .shopping
element:
$('.shopping input').click(function(){
$(this).toggleClass('remove');
});
In this case, this
would refer to the <input>
since that's the element which is getting the click
handler attached to it.