2

I have an array and it has some data in it. This array contains id, firstname, lastname, email, phone. I also have five form input elements. Now I want to add data in array in these elements. For example, ID should be inserted in ID form field, name should be inserted in name input element etc. how can I achieve this?

here is my code

insert_data_in_form: function(data) {
    var form = $("#dataform");
    var form_arr = new Array();

    form.each(function(i) {
        var form_el = form.children("input[type='textfield']");
        form_arr.push(form_el);
        console.log(data.length);
        //for(var j = 0; j < 5; j++) {
            form_el.val(data[i]);
        //}
    });
}

2 Answers 2

2

If the values in data array are in the same order as they are in the form then you can do this

insert_data_in_form: function(data) {
    var formElems = $("#dataform input[type='text']");
    formElems.each(function(i,elem) {
        $(this).val(data[i]);
        // or even better use the following faster way 
        // if they are always text boxes
        // this.value = data[i];
    });
}

Demo: http://jsfiddle.net/joycse06/AJhEW/

UPDATE (Alternate Way):

You can also achieve this using Implicit Looping with this .val(function(index,val) variant of the .val() function like this

var insert_data_in_form =  function(data) {
    var formElems = $("#dataform input[type='text']");
    formElems.val(function(i) {
       return data[i];
    });
};

Demo: http://jsfiddle.net/joycse06/AJhEW/2/

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

Comments

0

el -> arr:

form_arr[form_el.attr('name')] = form_el.val();

arr -> el:

form_el.val(form_arr[form_el.attr('name')]);

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.