开发者

Getting elements children with certain tag jQuery

开发者 https://www.devze.com 2022-12-22 22:18 出处:网络
I\'m trying to get all the input elements from a certain form from jQuery by providing only the name of the form and only knowing that those wanted fields are input elements.

I'm trying to get all the input elements from a certain form from jQuery by providing only the name of the form and only knowing that those wanted fields are input elements.

Let's say:

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

How do I access them individually with jQuery? I tried something like $('#formId > input') with no success, in fact an error came back on t开发者_如何学Pythonhe console "XML filter is applied to non-XML value (function (a, b) {return new (c.fn.init)(a, b);})"

Maybe I have to do it with .children or something like that? I'm pretty new at jQuery and I'm not really liking the Docs. It was much friendlier in Mootools, or maybe I just need to get used to it.

Oh and last but not least, I've seen it asked before but no final answer, can I create a new dom element with jQuery and work with it before inserting it (if I ever do) into de code? In mootools, we had something like var myEl = new Element(element[, properties]); and you could then refer to it in further expressions, but I fail to understand how to do that on jQuery

What I ended up doing was something like this: $('#where').before("<a id='linkId' href='#'>Link Text</a>") but this defeats the requirement of working with it before inserting it if you know what I mean.

Thanks in advance.


If you want all descendants then @woland's answer works. If you really only want the direct children as indicated by your > then

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

Wolands matches name, surname and phone. Mine matches just name and surname

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


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>


Here's how it works:

$('#formId input')


If you want to loop through all of the inputs, take a look at the each() function in jQuery:

0

精彩评论

暂无评论...
验证码 换一张
取 消