<ul>
<li>
<input type="radio" name="letter_type" data-custom="Something" value="0"> Something
</li>
<li>
<input type="radio" name="letter_type" data-custom="Something1" value="1"> Something1
</li>
<li>
<input type="radio" name="letter_type" data-custom="Something2" value="2" > Something2
</li>
</ul>
<script>
if ($("input[data-custom='Something1']")) {
alert(true);
$(this).attr('checked', true);
};
</script>
The list is generated by my PHP (in a loop) script, I wonder why is this not working. I need the Something1
to be checked by default after drawing the list.
您不需要if
。
$("input[data-custom='Something1']").attr( 'checked', true );
You need to check the length for if
as jQuery always returns an object which has length
property, if it doesn't find the element and an object is truthy . Also use prop
instead of attr
to set the checked
value.
var elm = $("input[data-custom='Something1']");
if(elm.length){
alert(true);
elm.prop('checked', true);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.