2

Long time lurker, first time poster.

I have a page that can dynamically (with Javascript / jQuery) add key => value pair inputs to a form. These fields need to be returned to PHP as an array for processing, so the keys are all named "complete_fields[]" and the values are all named "complete_values[]". Now here is my problem. If I fill in some inputs then want to add another key => value pair, I can click on a button and the Javascript will work its magic. However, because the HTML "value=" part is not filled out, the inputs I have already filled out are erased by the Javascript. So my question is this: How can I dynamically set the HTML value of the input with JS, even though all the inputs are named the same? If this is not possible, how can I add to the end of a div without erasing all the rest of the HTML?

Here is the Javascript add input code:

function addCompleteField() {
    var oldhtml = $("#complete_fields").html();
    var newrow = '<tr><td><input type="text" name="complete_fields[]" > => <input type="text" name="complete_values[]" ></td></tr>';
    $("#complete_fields").html(oldhtml+newrow);
}

1 Answer 1

1

Rather than mucking around with HTML, just clone the elements using jQuery's clone method:

function addCompleteField() {
    var table = $('#complete_fields'),
        lastRow = table.find('tr').last(),
        newRow = lastRow.clone(true);

    newRow.find('input').val(''); // blank the new row's input elements
    newRow.appendTo(table);
}
Sign up to request clarification or add additional context in comments.

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.