Getting items by children with a specific jQuery tag

I am trying to get all input elements from a specific form from jQuery, specifying only the form name and only knowing that these desired fields are input elements.

Say:

<form action='#' id='formId'>
<input id='name' />
<input id='surname'/>
</form>

How do I access them separately using jQuery? I tried something like $('#formId > input')without success, in fact the error returned to the console"XML filter is applied to non-XML value (function (a, b) {return new (c.fn.init)(a, b);})"

Maybe I need to do this with .children or something like that? I'm new to jQuery and I don't like documents. Mootools was a lot friendly, or maybe I just need to get used to it.

Oh, and last but not least, I saw him asking before, but for the final answer, I can’t create a new dom element with jQuery and work with it before inserting it (if I ever) into the code? In mootools we had something like var myEl = new Element(element[, properties]);  and you can refer to it in the following expressions, but I don’t understand how to do it in jQuery

What I finished was something like this: $('#where').before("<a id='linkId' href='#'>Link Text</a>")but it violates the requirement to work with it before inserting it, if you know what I mean.

Thanks in advance.

+3
source share
4 answers

I hope this answers your questions.

<script type="text/javascript">

$(document).ready(function() {
        // Question part 1
    var formInputs = $("form#formId :input");
    formInputs.each(function(index) {
         alert(index + ': ' + $(this).attr("id") + "=" + $(this).val());
    });

        // Question part 2
    var a = $("<a id='linkId' href='#'>Link Text</a>");
    a.click(function(){alert("hello")});
    $('#where').before(a);


});
</script>

<form action="#" id="formId">
  <input id="name" type="text" value="foo" />
  <input id="surname" type="text" value="bar" />
  <div>
  <input id="phone" type="text" value="911"/>
  </div>
</form>
</div>
<div id="where"></div>
+3
source

, @woland. , >

$('#form').children('input')

Wolands , .

<form action='#' id='formId'>
<input id='name' />
<input id='surname'/>
<div>
<input id='phone'/>
</div>
</form>
+5

:

$('#formId input')
+1
source

If you want to iterate over all inputs, look at each()function in jQuery:

+1
source

Source: https://habr.com/ru/post/1736634/


All Articles