2

This is a jquery to generate dynamic input text field in html. TO give different name to each text field, 'num ' is incremented . I even try ".attr('name', 'device' + num);"... But its not working .

$(document).ready(function() {
    $("#add").click(function() {
        var intId = $("#buildyourform div").length + 1;
        var num=0;
        num++;
        var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");

**var fName = $("<input type=\"text\" class=\"fieldname\" name=\"' + num + '\" />");**

        var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
        removeButton.click(function() {
            $(this).parent().remove();
        });
        fieldWrapper.append(fName);

        fieldWrapper.append(removeButton);
        $("#buildyourform").append(fieldWrapper);
    });

});

if 3 new text fields are generated now, how can i add the value in each text field onkeyup

2 Answers 2

3

You override the num on each click, and messed up the string notations.
Put the num declartion outside the callback:

var num=0;
$("#add").click(function() {
    var intId = $("#buildyourform div").length + 1;
    num++;
    $('<input type="text" class="fieldname" name="' + num + '" />');

A tip of the day, in javascript you can use ' and " for strings notations, you them both and you won't need to escape the other notation.

Sign up to request clarification or add additional context in comments.

4 Comments

By declaring num outside the function & changing the below line solved the problem var fName = ($('<input type="text" name="' + num + '" />'));
how can i add the value in each text field onkeyup
@Prads, I didn't understand what you asked.
i managed to do this in php ... Is there a way to sum the value in each dynamically generated text field (onkeyup event).
0

There is a syntax error in your code, you mess with single and double quotes...

Should be something like this

var fName = $('<input type="text" class="fieldname" name="' + num + '" />');

OR:

var fName = $("<input type=\"text\" class=\"fieldname\" name=\"" + num + "\" />");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.