Quentin Skousen
Quentin Skousen

Reputation: 1045

Dynamically set input values in HTML with non-specific names

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);
}

Upvotes: 2

Views: 486

Answers (1)

lonesomeday
lonesomeday

Reputation: 237817

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);
}

Upvotes: 1

Related Questions