Reputation: 165
I am creating fully flexible contact us form where user can drag and drop input elements. so in that case I am stuck in a problem
the html structure is:
<div class="ns_field_box">
<input type="text" data-name="checkbox_label" class="nsdummy-label" value="CheckBox">
<span class="nscheckbox"></span> <input type="text" data-name="checkbox_desc" value="Add checkbox description">
<div class="nshandle">
<span class="dashicons dashicons-move"></span>
<span class="dashicons dashicons-trash nsremove_feild"></span>
</div>
</div>
I stored <div class="ns_field_box">
this element in a javascript variable and want to find and store all input elements inside this variable
javascript code :
$(document).on('click', '#submit_form', function () {
var allelems = $('#B .ns_field_box');
for (i = 0; i < allelems.length; i++) {
var elem = allelems[i];
console.log(elem.children('input')); // at this line browser console says
// 'elem.children is not a function'
}
})
Required files are already set in a proper order
// jquery file
<script src='https://siga.local/nitin/plugins/wp-content/plugins/ns-contact-form/inc/assets/js/jquery.min.js?ver=3.6.0' id='ns_cf_jquery-js'></script>
<script src='https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js?ver=3.6.0' id='ns_cf_sortablejs-js'></script>
<script src='https://cdn.jsdelivr.net/npm/jquery-sortablejs@latest/jquery-sortable.js?ver=1.14.0' id='ns_cf_jquerysortablejs-js'></script>
// main javascript file where the code I wrote
<script src='https://siga.local/nitin/plugins/wp-content/plugins/ns-contact-form/inc/assets/js/main.js?ver=1.0.0' id='ns_cf_js-js'></script>
and the browsers javascript console says
main.js?ver=1.0.0:34 Uncaught TypeError:
elem.children is not a function
at HTMLButtonElement.<anonymous> (main.js?ver=1.0.0:34)
at HTMLDocument.dispatch (jquery.min.js?ver=3.6.0:2)
at HTMLDocument.v.handle (jquery.min.js?ver=3.6.0:2)
Thank you to all who help me in advance
Upvotes: 1
Views: 216
Reputation: 158
$(document).on('click', '#submit_form', function () {
var allelems = $('#B .ns_field_box');
for (i = 0; i < allelems.length; i++) {
var elem = $(allelems[i]);
console.log(elem.children('input'));
}
})
Upvotes: 0
Reputation: 28621
Using jqueryCollection[i]
returns a DOM object, but you're trying to use a jquery's children() method.
One solution is to change to
var elem = $(allelems[i]);
to keep elem
as a jquery object.
You can make your code more succinct with the use of jquery's .each
and using
var elem = $(this);
to ensure elem
continues on as a jquery object with all of jquery's methods.
You snippet would be updated to:
$(document).on('click', '#submit_form', function () {
var allelems = $('#B .ns_field_box');
allelems.each(function() {
var elem = $(this);
console.log(elem.children('input').length);
}
})
Upvotes: 1