I faced an issue since I can't get a just created element with a PHP script.
I have a list of tags loaded with PHP:
<ul>
<li>
<input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="4">
Some tag
<li>
<ul>
Thanks to AJAX I append another element inside the UL
jQuery(document).ready(function($) {
$('.add-tag-btn').click(function(event) {
var tag_title = $('.tag-search').val();
$.ajax({
url: 'add-tag.php',
type: 'POST',
dataType: 'json',
data: {
'tag_title': tag_title
},
success:function(result){
$('.tag-search').val('');
$('.new-tags').append('<li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="'+result.tag_id+'">'+tag_title+'</li>');
console.log(result.tag_id);
}
});
});
});
Thus I have a new UL
<ul>
<li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="4">Value #4</li>
<li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="5">Value #5 (new value generated with jQuery and AJAX)</li>
</ul>
But once I submit the form, only the existed value is added to DB.
if (isset($_POST['submit'])) {
....
bla bla bla
foreach ($_POST['check_list_tags'] as $value) {
$arr2[] = $value;
}
bla bla bal
}
Looks like that PHP can't handle a new value without the page reloaded. At the same time, I add
checked="checked"
dynamically and that works just perfect.
Can anyone explain me how to force PHP to see the newly created elements (the elements that were appended to the existed HTML by the means of jQuery).
Thanks everyone for the assistance.
upd:
This is how I add the "checked"
jQuery(document).ready(function($) {
$('.adm-checkbox').click(function(event) {
if (this.checked) {
this.setAttribute("checked", "checked");
console.log('checked');
} else {
this.removeAttribute("checked");
}
});
});
This is how the form looks like:
<form class="" action="<?php echo $router->url ?>" method="post" enctype="multipart/form-data">
.....
<ul class="new-tags">
</ul>
<ul>
<?php foreach ($admin->getAdmTags() as $value): ?>
<li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="<?php echo $value['id'] ?>"><?php echo $value['title'] ?></li>
<?php endforeach; ?>
<ul>
</form>
UPD # 2:
May be the reason is that I use two separate functions in jQuery for "checked"??!?!
$('.adm-checkbox').click(function(event) {
if (this.checked) {
this.setAttribute("checked", "checked");
console.log('checked');
} else {
this.removeAttribute("checked");
}
});
and
$('.adm-tags').on('click', '.adm-checkbox', function(event) {
if (this.checked) {
this.setAttribute("checked", "checked");
console.log('checked');
} else {
this.removeAttribute("checked");
}
});
I do it because onclick doesn't work for the newly created elements.
P.s: It doesn't matter where I put a newly created "li"...
Thank everyone for participation. I've created a new page and did everything again. And now it works. Now I need to find the mistake in my full code.