check if a checkbox is checked jquery
Pergunta
Does anyone know why this isn't working. It will always print 'unchecked'.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function msg(x)
{
if($(x).attr('checked')){
alert('checked!!');
}
else{
alert('unchecked');
}
}
</script>
</head>
<body>
<form>
<input type="checkbox" id="fname2" onClick="msg(this.id)" /><br/>
</form>
</body>
</html>
Solução
You are sending this.id
to the function, then you are wrapping it in the $()
. This does not work. You need just to send this
to msg: onClick="msg(this)"
.
Outras dicas
Use
function chkChecked(elmt) {
if($(elmt).is(':checked')) {
alert('checked!!');
}
else alert('unchecked');
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow