开发者

jsquery get all elements contained by a div with given name

开发者 https://www.devze.com 2023-03-24 20:21 出处:网络
So I\'ll start off by saying I\'m completely new to JS and JSQuery. So I\'m in the following situation. The page has a structure like:

So I'll start off by saying I'm completely new to JS and JSQuery. So I'm in the following situation. The page has a structure like:

<div id="id1">
   <input name="input1" .... >
   .....
</div>

<div id="id2" disabled="disabled">
   <input name="input1"  ....>
</div>

.....

So the names of the inputs will repeat themselves, only on different divs and only one div will not be disabled at a given moment. I need to be able to get a input element with a given name from a div with a given ID. My approach after reading a bit:

var inputs = $('div[id="' + parent_div +'"] input').filter(function() {
            return (this.hasOwnProperty('name') && (typeof this.name  != "undefined") && this.name == component_name);
        });;
for (input in inputs){
   alert(inputs[input]);
   alert(inputs[input].name);           
    } 

Now I would expect this to return only my given component. However the result is very strange to me as a beginner. The alerts will be return something like the following:

objectHTMLInputElement component_name ---- so the first one is the correct one, but after:

1 undefined

object Object undefined

object HTMLDocu开发者_开发百科ment undefined

div[id="data_modelHR"] input.filter(function () { return (this.hasOwnProperty('name') && (typeof this.name != "undefined") && this.name == component_name); }) undefined

And this goes on for a while with different functions. Any suggestions?

Regards, Bogdan


Don't walk an Array using foo in bar if you want to iterate over it's indexed elements.

See what you will get: http://jsfiddle.net/doktormolle/7qzcv/
You get the indexed elements 0+1, but also all methods/properties of an jQuery-object.

Use:

for (var i=0;i<inputs.length;++i){
   alert(inputs[i]);
   alert(inputs[i].name);           
    } 

Or the jquery-way:

inputs.each(function(i,o){alert(o);alert(o.name); })


That will give you an input with name component_name inside the div with id parent_div:

$('div[id="' + parent_div +'"]').find('input[name="' + component_name + '"]');

You may use only one selector like this:

$('div[id="' + parent_div +'"] input[name="' + component_name + '"]');


Think this is the simplest way of doing this:

$('#' + parent_div + ' input[name="' + component_name + '"]');
0

精彩评论

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