2011-10-25 10 views
6

Estoy tratando de crear un ARRAY de JavaScript y obtener el nombre de los elementos de un elemento.
(no necesito elementos span, única entrada, seleccionar y área de texto)jQuery: cree un ARRAY de javascript desde NIÑOS de un elemento

HTML:

<div id="new"> 
    ID: <input name="id" /> 
    <span>Date: </span> 
    <input name="date" /> 
    <select name="status"> 
     <option>New</option> 
     <option>Old</option> 
    </select> 
    <textarea name="memo"></textarea> 
... etc. 
</div> <!-- END: #new --> 


jQuery:

var elements=new Array(); 
$("#new").each(function() 
{ 
    elements = $(this).children('input, select, textarea').attr("name"); 
}); 


con este código Solo obtengo el nombre de 1 elemento ("id"). Cuando pruebo la matriz, con el índice 0, funciona. Pero cuando se utiliza un índice diferente, digamos ... para alertar "fecha" o "estado", no funciona:

alert(elements[0]); //Output: "id" 
alert(elements[2]); //Output: "undefined". It should alert "status" instead 

Respuesta

11

una versión más limpia que atrapa todos los campos que requieren una entrada del usuario:

jQuery

var elements = []; 

//iterates through each input field and pushes the name to the array 
$("#new :input").each(function() { 
    var name = $(this).attr("name"); 
    elements.push(name); 
}); 

Y sí, es necesario limpiar el HTML. Debería tener este aspecto:

HTML

<div id="new"> 
    ID: <input name="id" /> 
    <span>Date: </span> 
    <input name="date" /> 
    <select name="status"> 
     <option>New</option> 
     <option>Old</option> 
    </select>  
    <textarea name="memo"></textarea> 
</div> 
+0

http: // jsfiddle.net/TeLwS/ – Omar

+0

Esta es una buena también: P – Omar

+0

La razón por la que voté por esta solución sobre @ ipr101 es porque cuando uso la solución * ipr101 para enviar la matriz a través de ajax/php, no me "gusta" la matriz y yo obtener un mensaje de error Con * hollandben solución, ajax/php toma la matriz muy bien. Sin embargo, me gusta que * ipr101 responda mejor. – Omar

5

usted podría utilizar map (docs) -

var arr = $("#new").children('input, select, textarea').map(function() { 
    return $(this).attr("name"); 
}); 

map iterará sobre cada elemento en el conjunto de elementos seleccionado y devolverá el valor especificado en la matriz arr.

También es necesario para poner en orden su HTML un poco como que se está perdiendo algunas etiquetas de cierre que está causando la colección children para rellenar incorrectamente -

<div id="new"> 
    ID: <input name="id"/> 
    <span>Date: </span> 
     <input name="date"/> 
    <select name="status"> 
     <option>New</option> 
     <option>Old</option> 
    </select>  
    <textarea name="memo"></textarea> 
</div> 

Demo - http://jsfiddle.net/M52G4/1

+0

Usted se echa en falta un ");" after var arr ...} En mi sitio web, todo mi HTML tiene TODAS las etiquetas adecuadas. Debería copiar y pegar: P – Omar

+0

@Omar - gracias por señalar el error tipográfico, corregido ahora. – ipr101

+0

¡GRACIAS mucho por su ayuda! ¿Por qué $ ("# new"). Each() no funcionó? – Omar

0

rápido y sucio, no lo recomendaría para la vida real, pero en teoría:

var arr = new Array(); //initialise array 
$('#new').children().each(function(){ 

    //iterate through the children of the div - 
    //there shouldn't be more than one #new, unless you aren't 
    //following best practices :) 

    if ($(this).attr('name')) 
    { 
     //if the name attr is defined, push it to the array 
     arr.push($(this).attr('name')); 
    } 
});   
alert(arr); 

violín: http://jsfiddle.net/GMNKm/

Cuestiones relacionadas