dapperwaterbuffalo
dapperwaterbuffalo

Reputation: 2748

issue retrieving child input type. currently returning as 'undefined'

so the best way for you to understand what I am trying to achieve is to view this demo: live demo.

the problem is that the type being returned is 'undefined' rather that 'text'.

Can anybody please explain why this happening?

many thanks,

Upvotes: 0

Views: 362

Answers (4)

tildy
tildy

Reputation: 1009

The problem is that, that you try to find a non-hidden input element - child in the ".question" div.

But your function doesn't pickup the grand-child element , and in this case is that one . that's why you get back "undefined" response.

Upvotes: 1

fearofawhackplanet
fearofawhackplanet

Reputation: 53388

Think about what your code is doing:

// for each '.question' element
$(".question").each(function() { 
    // find the 'input' children which are not 'type=hidden'
    var children = $(this).children('input[type != "hidden"]');
    // get the type
    var type = children.attr('type');
}

You have two question elements. The first one contains no elements matching the children selector (the text input is not a direct child as it is nested in h3), so you have an empty array.

In the first iteration of each, you are trying to read attr('type') from an empty array, which is giving you undefined.

In the second iteration of each, you are trying to read attr('type') from an array with more than one element.

I presume what you are trying to do is something more along the lines of...

$(".question").each(function(){
    $(this).find('input[type != "hidden"]').each(function() {
         alert($(this).attr("type"));
    });   
});

Note that find seaches through all children, not just the immediate children as children does.

Upvotes: 2

Sylvain
Sylvain

Reputation: 3873

If you don't want to change your HTML, this code is working :

$(".question").each(function(){
        var type = $('input[type != "hidden"]',this).attr("type");
        alert(type);
});

// Or

$(".question").each(function(){
        var type = $(this).find('input[type != "hidden"]').attr("type");
        alert(type);
});

Upvotes: 0

Naftali
Naftali

Reputation: 146300

It is because the input type=text is inside an h3:

<h3>The binary language consists of <input type='text' name='response[4][answer]'>digit(s).</h3>

Fix your HTML to:

<h3>The binary language consists of </h3><input type='text' name='response[4][answer]'>digit(s).

Fiddle: http://jsfiddle.net/maniator/Z6jDR/12/

Upvotes: -1

Related Questions