0
Good afternoon.
I need to check if a dynamically created checkbox (is inside a modal) is marked. As it was created dynamically, I thought of the following code:
$(document).ready(function () {
$(document).on('click', '#elemento', function () {
if($(document).on("input[id='elemento']:checked")) {
alert('Sim');
} else {
alert('Não');
}
});
});
The problem is that this function always returns true. I cannot use this checked. pq it will reference Document, not checkbox. I can’t understand what’s wrong. Someone has some idea?
dps of the line code you create this check , you can put
$("input").each(function(){ if($(this).is(":checked") == true)console.log("checked")}
– Vinicius Shiguemori
I happen to be opening the modal by data-target, without writing jquery code.
– Paulo Vitor
You want to check the checkbox without writing code?
– Sam
No. The code experienced in jquery is in the question. The modal that is opened directly by the id defined in the modal div, in the HTML itself.
– Paulo Vitor
Yes, but this will refer to Document, not the element. The central point is that the checkbox is created dynamically when the modal is shown. I was able to insert the function in the checkbox click event $(Document). on('click', '#element', Function(), so this part is ok. The problem is in the if($(Document). on("input[id='element']:checked"), which always returns true and I can’t understand the reason. I’m a beginner in jquery.
– Paulo Vitor
The
$(this)
will refer to the#elemento
, who was informed on.on("click")
.– Sam
If I had only
$(document).on('click', function () {
, then it would be to the document... but you put#elemento
as a reference.– Sam
In fact, it worked. I did what you suggested, it turns out I had tested it before and I hadn’t been able to. I must have forgotten something the first time. Thank you very much.
– Paulo Vitor
All right. Thanks again.
– Paulo Vitor
As I put it in the answer, the error was because if was checking if the element exists and if it was not checked. When you put an element inside the if, without making any comparison, for example.:
if( $('#elemento') ){
means you want to know if the element exists, already so:if( !$('#elemento') ){
(with "!" exclamation) means you want to know if the element doesn’t exist. I’m glad I helped. If you can mark in the answer to finish, it would be good. Abs!– Sam
Marquei! I had not scored before pq I’m still familiarizing myself with stackoverflow. Abs
– Paulo Vitor