2012-05-02 7 views
6

Aquí es mi HTML y CSS vigente código:Cuando se rellenan todos los campos anteriores, agregar nuevo campo de entrada

<form method="post" id="achievementf1" action=""> 
    <span>1.</span> 
    <input type="text" name="achievement1" id="achievement1" /> 
    <br /> 
    <span>2.</span> 
    <input type="text" name="achievement2" id="achievement2" /> 
    <br /> 
    <span>3.</span> 
    <input type="text" name="achievement3" id="achievement3" /> 
    <br />      
    <input type="submit" name="submit1" value="Registrate" /> 
    </form> ​ 
#border #info-box #info #box input[type="text"] { 
    float: left; 
    margin-top: 10px; 
    margin-bottom: 10px; 
    height: 25px; 
    width: 650px; 
    outline: none; 
} 
#border #info-box #info #box input[type="submit"] { 
    margin-left: 500px; 
    margin-top: 10px; 
    margin-bottom: 10px; 
    height: 35px; 
    color: #fff; 
    font-size: 20px; 
    border: 2px solid #fff; 
    border-radius: 8px 8px 8px 8px; 
    padding-left: 15px; 
    padding-right: 15px; 
    padding-top: 3px; 
    cursor: pointer; 
}​ 

Se puede ver en acción en http://jsfiddle.net/mzNtj/2/. Me gustaría saber cómo puedo agregar automáticamente un nuevo campo de entrada cuando todos los demás se hayan completado. Tengo una idea básica, leer en el valor de cada campo y verificarlo con una declaración if. Luego, si ninguno está vacío, agregue uno nuevo.

¿Es esta una forma adecuada de verificar, o alguien tiene alguna idea mejor?

+0

Bienvenido a Stack Overflow, Pienskabe, +1 por su pregunta. Preferimos que las preguntas y las respuestas funcionen por sí solas sin requerir que las personas sigan enlaces fuera del sitio para darles sentido. jsFiddle es un gran sitio y es una excelente idea vincular tus ejemplos con tu pregunta, pero no es exactamente conocida por su estabilidad y tiempo de actividad. –

Respuesta

6

Pruebe el siguiente código:

$(function(){ 
    $(document).on("change","input", function(){ 
     var allGood=true; 
     var lastInputField=0; 
     $("input").each(function() { 
      if ($(this).val() =="") { 
       allGood=false; 
       return false; 
      } 
      lastInputField++; 
     }); 

     if (allGood) { 
      $("<span>" + lastInputField + "<input type='text' id='lastinputfieldId" + lastInputField +"'" + 
       "name='lastinputfieldName" + lastInputField + "'></span>").appendTo("form"); 
     } 
    }); 
}); 
​ 

Demostración: http://jsfiddle.net/mzNtj/3/.

+0

Fuiste primero, gracias;)! – Pienskabe

0

primera ocultar lo que cada vez que desee agregar cuando están llenos todos los campos ... luego, cuando último campo es llamar a una función utilizando detector de teclas y en el que la función de hacer que el campo visible

+0

Hola, bueno, básicamente, lo haría feo y no es exactamente lo que quería hacer, pero gracias, lo tendré en cuenta, si no descubro algo más. – Pienskabe

0

prueba este:

http://jsfiddle.net/F8qR2/

el código es:

function AllInputsFilled() { 
    return $("input[type='text']", $("#achievementf1")).filter(function() { 
     return $(this).val().trim() === ""; 
    }).size() === 0; 
} 

function AdditionEvent() { 
    if (AllInputsFilled()) { 
     AddInput();  
    } 
} 

function AddInput() { 
    var cnt = $("input[type='text']", $("#achievementf1")).size() + 1; 
    $("<br><span>" + cnt + "</span><input type='text' name='achievement" + cnt+ "' id='achievement" + cnt+ "' />").insertAfter("#achievementf1 input[type='text']:last"); 
    $("input", $("#achievementf1")).unbind("keyup").bind("keyup", function(){ AdditionEvent() }); 

} 

$("input", $("#achievementf1")).bind("keyup", function(){ AdditionEvent() });​ 
0

bien, echar un vistazo a este jsFiddle: http://jsfiddle.net/Ralt/mzNtj/4/

Lea atentamente los comentarios de entender lo este código hace:

// First, listen for the "onkeypress" event instead of the "blur" or "change". 
// Why? For the UX, since the user will think he can click the submit 
// button as soon as the third field is filled in if you use the "blur" or 
// "change" event. 
document.forms[ 'achievementf1' ].onkeypress = function(e) { 
    // Some cross-browser handling 
    var e = e || window.event, 
     target = e.target || e.srcElement; 

    // If the target is an INPUT 
    if (target.nodeName === 'INPUT') { 

     // Now here is the tricky part: 
     // The "every" method returns false if *one* callback returns false, 
     // otherwise it returns true. 
     // And we use !! to check if it's not empty. 
     var allNotEmpty = [].every.call(this.elements, function(el) { 
      return !!el.value; 
     }) 

     // If it's true, it means all the fields are not empty 
     if (allNotEmpty) { 

      // So let's create an input 
      var newInput = document.createElement('input') 
      // Set some properties 
      // And then... insert it before the submit button :-) 
      this.insertBefore(newInput, this.elements[ 'submit1' ]); 
     } 
    } 
} 

Lo sé, mi código es raro ya que me importa el navegador cruzado para manejar eventos, pero every no es compatible con los navegadores heredados. Oh, bueno ...

Cuestiones relacionadas