¿Cómo determinaría si el elemento devuelto por un filtro de entrada en jQuery es un cuadro de texto o una lista de selección?
Quiero tener un comportamiento diferente para cada uno (el cuadro de texto devuelve el valor del texto, la selección devuelve tanto la clave como el texto)
Configuración de ejemplo:
<div id="InputBody"> <div class="box"> <span id="StartDate"> <input type="text" id="control1"> </span> <span id="Result"> <input type="text" id="control2"> </span> <span id="SelectList"> <select> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select> </span> </div> <div class="box"> <span id="StartDate"> <input type="text" id="control1"> </span> <span id="Result"> <input type="text" id="control2"> </span> <span id="SelectList"> <select> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select> </span> </div>y luego el guion:
$('#InputBody') // find all div containers with class = "box" .find('.box') .each(function () { console.log("child: " + this.id); // find all spans within the div who have an id attribute set (represents controls we want to capture) $(this).find('span[id]') .each(function () { console.log("span: " + this.id); var ctrl = $(this).find(':input:visible:first'); console.log(this.id + " = " + ctrl.val()); console.log(this.id + " SelectedText = " + ctrl.find(':selected').text()); });Podrías hacer esto:
if( ctrl[0].nodeName.toLowerCase() === 'input' ) { // it was an input }o esto, que es más lento, pero más corto y más limpio:
if( ctrl.is('input') ) { // it was an input }Si quieres ser más específico, puedes probar el tipo:
if( ctrl.is('input:text') ) { // it was an input }alternativamente, puede recuperar las propiedades DOM con .prop
aquí hay un código de muestra para el cuadro de selección
if( ctrl.prop('type') == 'select-one' ) { // for single select } if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }para cuadro de texto
if( ctrl.prop('type') == 'text' ) { // for text box }Si solo desea verificar el tipo, puede usar la función .is() de jQuery,
Como en mi caso, usé a continuación,
if($("#id").is("select")) { alert('Select'); else if($("#id").is("input")) { alert("input"); }