Reputation: 158
I want to add class, next to checked input. So, class will be added to span, which is next to a checked input radio.
<label>
<input type="radio" name="option[228]" value="20" checked="checked">
<span data-toggle="tooltip" data-placement="top" title="" data-original-title="Purple (+₹20)">
<img src="http://countrylivings.com/image/cache/catalog/sample/q2-50x50.png" alt="Purple +₹20" width="36px" height="36px">
</span>
</label>
I have tried a no. of ways to do so... But didn't work. like---
$(document).ready(function(){
if ($('label input').is(':checked')) {
$(this.element).next().addClass('hloo');
alert($(this.element).val());
};
});
But i get an alert of undefined when input is checked. So,
if ($('label input').is(':checked')) {
is working fine to detect if checkbox is checked But
$(this) or $(this.element)
is not working. Anyone know what is going wrong?
Upvotes: 0
Views: 41
Reputation: 337560
There's three issues in your code. Firstly ::checked
is not a valid jQuery selector, it's just :checked
.
Secondly, assuming this
is a reference to an Element object (as it is in the vast majority of cases in jQuery) then there is no element
property. Just use $(this)
.
Lastly, if
conditions run under the outer scope, so this
would refer to the document
in your example, not the input
. It's for this reason val()
is undefined; you're looking at document.value
. To fix this, select the element directly before working with it:
$(document).ready(function() {
var $checkedInput = $('label input:checked');
$checkedInput.next().addClass('hloo');
console.log($checkedInput.val());
});
.hloo { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="radio" name="option[228]" value="20" checked="checked">
<span data-toggle="tooltip" data-placement="top" title="" data-original-title="Purple (+₹20)">
<img src="http://countrylivings.com/image/cache/catalog/sample/q2-50x50.png" alt="Purple +₹20" width="36px" height="36px">
</span>
</label>
Upvotes: 4