2011-12-21 10 views
9

Tengo un div principal y dentro de este, hay una gran cantidad de texto de entrada y botón de opción. De esta manera:Jquery Obtiene automáticamente los valores de todos los elementos dentro de un div

<div id="mainDiv"> 
    <input type="text" name="text-1" /> <br/> 

    <input type="radio" name="radio-1" />Yes 
    <input type="radio" name="radio-1" />No <br/> 

    <input type="text" name="text-2" /> <br/> 
    <input type="text" name="text-3" /> <br/> 
</div> 
<img src="img/img.gif" onclick="getAllValues();" /> 

quiero definir los "getAllValues ​​()" función de jQuery que reciben todos los valores en "mainDiv" y guardarlos en una cadena. ¿Es posible?

+1

¿Ha echado un vistazo a '.serialize()' (http://api.jquery.com/serialize/)? ¿Eso se ajusta a tu factura? Si no, ¿por qué? – PPvG

Respuesta

16

Para lograr esto, puede seleccionar todos los campos del formulario y usar map() para crear una matriz a partir de sus valores, que se pueden recuperar en función de su type. Prueba esto:

function getAllValues() { 
    var inputValues = $('#mainDiv :input').map(function() { 
     var type = $(this).prop("type"); 

     // checked radios/checkboxes 
     if ((type == "checkbox" || type == "radio") && this.checked) { 
      return $(this).val(); 
     } 
     // all other fields, except buttons 
     else if (type != "button" || type != "submit") { 
      return $(this).val(); 
     } 
    }) 
    return inputValues.join(','); 
} 

La declaración if se puede unir juntos aquí, pero me dejó separados para mayor claridad.

+0

Funciona con texto de entrada, pero con los botones de opción solo tomaría los valores seleccionados. ¡Gracias, Rory! – Danilo

+0

@Danilo no hay problema, mira mi actualización –

5

intentar algo así como que:

function getAllValues() { 
    var allVal = ''; 
    $("#mainDiv > input").each(function() { 
    allVal += '&' + $(this).attr('name') + '=' + $(this).val(); 
    }); 
    alert(allVal); 
} 
2

Aquí está la solución que se está construyendo una cadena JSON. Se está poniendo los valores de los campos de texto, casillas de verificación y seleccione elementos:

function buildRequestStringData(form) { 
    var select = form.find('select'), 
     input = form.find('input'), 
     requestString = '{'; 
    for (var i = 0; i < select.length; i++) { 
     requestString += '"' + $(select[i]).attr('name') + '": "' +$(select[i]).val() + '",'; 
    } 
    if (select.length > 0) { 
     requestString = requestString.substring(0, requestString.length - 1); 
    } 
    for (var i = 0; i < input.length; i++) { 
     if ($(input[i]).attr('type') !== 'checkbox') { 
      requestString += '"' + $(input[i]).attr('name') + '":"' + $(input[i]).val() + '",'; 
     } else { 
      if ($(input[i]).attr('checked')) { 
       requestString += '"' + $(input[i]).attr('name') +'":"' + $(input[i]).val() +'",'; 
      } 
     } 
    } 
    if (input.length > 0) { 
     requestString = requestString.substring(0, requestString.length - 1); 
    } 
    requestString += '}'; 
    return requestString; 
} 

Usted puede llamar a la función como esta:

buildRequestStringData($('#mainDiv')) 

Y el resultado http://jsfiddle.net/p7hbT/

Cuestiones relacionadas