Obtener valores de elementos agregados dinámicamente

http://jsfiddle.net/R89fn/9/

If any of the text input/Box added are empty then the page must not submit.when I try to retrieve values from the text inputs using their id`s nothing gets retrieved is it possible to retrieve values from elements added dynamically?

 $("#submit").click(function (event) {
                var string = "tb";
                var i;
                for (i = 1; i <= count; i++) {
                    if (document.getElementById(string+1).value=="") {
                        event.preventDefault();
                        break;
                    }
                }
            });

The above code is what I am using to get the value from the text fields using there id

preguntado el 28 de mayo de 14 a las 12:05

pólipo string = "tb" may work, note that #tb debe usarse para document.querySelector or some jquery method. -

por qué no usar algo como $('.newTextBox').each(function(index) { }) also as you are getting the div rather than the input, the .value won't have a value -

@KingKing No luck I tried $(string+1).val() earlier to get the value that didn`t work I forgot change back the string value :P sorry about that let me update the question -

es el jquery version of your loop - as all your new divs have the class newTextBox, you can just select them and then loop through them, instead of trying to get them with their id like you're doing. I suspect your problem is you are trying to get the value of the input though but your code is trying to get the value of the div (which it won't have one) try: $('.newTextBox').children('input').each(function(index) { console.log(this.value); }) -

not sure about performance - I would have thought getting all the elements with the class and looping through would be faster than getting one at a time, but I would just add a class to the input and then use the each loop (removing the need for the child selector) as you're using jQuery, I find it more readable and easier to maintain, but that's just a personal preference -

4 Respuestas

I took a look on the code in the JSFiddle. It appears that the input textboxes are not given the intended IDs; the IDs are given to the container div.

The code for the add button should use this,

var inputBox = $('<input type="text" id="td1">') //add also the needed attributes
$(containerDiv).append(inputBox);

contestado el 28 de mayo de 14 a las 12:05

Check out this solution on fiddle: http://jsfiddle.net/R89fn/15/

var count = 0;
$(document).ready(function () {

    $("#b1").click(function () {
        if (count == 5) {
            alert("Maximum Number of Input Boxes Added");
        } else {
            ++count;
            var tb = "tb" + count;
            $('#form').append("<div class=\"newTextBox\" id=" + tb + ">" + 'InputField : <input type="text" name="box[]"></div>');
        }
    });

    $("#b2").click(function () {
        if (count == 0) {
            alert("No More TextBoxes to Remove");
        } else {
            $("#tb" + count).remove();
            --count;
        }
    });

    $("#submit").click(function (event) {
        var inputBoxes = $('#form').find('input[type="text"]');;

        if (inputBoxes.length < 1) {
            alert('No text inputs to submit');
            return false;
        } else {
            inputBoxes.each(function(i, v) {
                if ($(this).val() == "") {
                    alert('Input number ' + (i + 1) + ' is empty');
                    $(this).css('border-color', 'red');
                }
            });

            alert('continue here');
            return false;
        }
    });

});

contestado el 28 de mayo de 14 a las 12:05

@AAB you don't need return false si ya tienes event.preventDefault();... just so you know - Alex

I know I wanted to break the loop the moment a text field is empty so the return false - AAB

<form name="form" id="form" action="htmlpage.html" method="POST">
<input type="button" id="b1" name="b1" value="Add TextBox" />
<input type="button" id="b2" name="b2" value="Remove TextBox" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

</script>

<script>
    var count = 0;
    $(document).ready(function() {

        $("#b1").click(function() {
            if (count == 5) {
                alert("Maximum Number of Input Boxes Added");
            } else {
                ++count;
                var tb = "tb" + count;
                $(this).before("<div class=\"newTextBox\" id= "+ tb +" >" + 'InputField : <input type="text" name="box[]"></div>');
            }
        });
        $("#b2").click(function() {
            if (count == 0) {
                alert("No More TextBoxes to Remove");
            } else {
                $("#tb" + count).remove();
                --count;
            }
        });
        $("#submit").click(function(event) {
            var string = "#texttb";
            var i;
            for (i = 1; i <= count; i++) {
            if ($('input[type = text]').val() == "") {
                    event.preventDefault();
                    break;
                }
            }
        });
    });

</script>

<style>
    .newTextBox
    {
        margin: 5px;z
    }
</style>


Reason:

you had given id to the div element. so its not get retrive. i had updated the answer with the usage of jquery functions and changed your code for this requirement. 

contestado el 28 de mayo de 14 a las 13:05

If I understand correctly, your only issue atm is to make sure that the form is not sent if one of the inputs are empty? Seems the solution to your problem is simpler. Simply add required at the end of any input and HTML5 will ensure that the form is not sent if empty. For example:

<input type="text" required />

contestado el 28 de mayo de 14 a las 12:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.