0

I'm looking for a plain-Javascript way to fix my following code:

function autoFill(response) {
    var arr = [];
    arr.fn = document.getElementsByName("firstName")[1];
    arr.ln = document.getElementsByName("lastName")[1];
    arr.em = document.getElementsByName("Email")[1];
    arr.pn = document.getElementsByName("phoneNumber")[1];

    if(response === false) {
        alert('false');
        arr.forEach(function(entry){
            entry.value = "";
        });
    }else{
        alert('true');
        arr.fn.value = response.firstName;
        arr.ln.value = response.lastName;
        arr.en.value = response.email;
        arr.pn.value = response.phone;
    }
}

What I'm trying to do:

if response data === false, loop through each element in arr[] and set its text value to empty "".

What's happening:

directly setting the values work (as shown in the else{} block), however looping or iterating through the array throws the error: Uncaught TypeError: Cannot set property 'value' of undefined

question:

how can I loop through a collection of inputs stored in an array and set their values? Why is the undefined error being thrown?

Thanks!

EDIT: changing to the following does nothing; the else{] block still works fine, the loop is the problem I believe.

    function autoFill(response) {
    var arr = [];
    arr["fn"] = document.getElementsByName("firstName")[1];
    arr["ln"] = document.getElementsByName("lastName")[1];
    arr["em"] = document.getElementsByName("Email")[1];
    arr["pn"] = document.getElementsByName("phoneNumber")[1];

    if(response === false) {
        alert('false');
        arr.forEach(function(entry){
            entry.value = "";
        });

    }else{
        alert('true');
        arr["fn"].value = response.firstName;
        arr["ln"].value = response.lastName;
        arr["en"].value = response.email;
        arr["pn"].value = response.phone;
    }
}
6
  • Your array is empty. Arrays are zero-based.
    – SLaks
    Nov 8, 2013 at 20:43
  • In one instance you're using the array as an object, the next as an array.
    – Andy
    Nov 8, 2013 at 20:47
  • @SLaks: the array is not empty. There are index-0 inputs of the same name, that is why the code is referencing [1].
    – tdc
    Nov 8, 2013 at 20:47
  • @Andy: Which is preferable? I was under the impression arrays and objects in JS were essentially synonyms but if I should be doing it another way don't hesitate to enlighten me! :)
    – tdc
    Nov 8, 2013 at 20:48
  • An object, but you would need to change the forEach to a for (var k in obj) loop. Objects are unordered, arrays are ordered by numeric index.
    – Andy
    Nov 8, 2013 at 20:55

4 Answers 4

1

You need to use an object not an array and you should use "dot notation" for better clarity.

EDIT

I changed the code because I dont like to say "no you can't" so here's the new function with loop.

function autoFill(response) {
    var fill = {};
    for (var i=0; i < document.myForm.elements.length; i++) {
        var elm = document.myForm.elements[i]; // Get current element.

        fill[elm.name] = elm; // Associate fill[input name] with current input.

       if (elm.getAttribute("data-autofill") === "undefined" || 
           elm.getAttribute("data-autofill") === null) continue; // Continue if property data-autofill is not set.

        // If response have the input name as key, we set the value otherwise, it would be an empty string or unchecked.
        switch(elm.type) {
            case 'checkbox':
            case 'radio':
                response.hasOwnProperty(elm.name) ? fill[elm.name].checked = response[elm.name] : fill[elm.name].checked = false; // Checked if response if true.
                break;
            default:
                response.hasOwnProperty(elm.name) ? fill[elm.name].value = response[elm.name] : fill[elm.name].value = ""; // Set response text or a empty string.
       }
    }

    return fill; // Return object for later uses.
 }

 var myForm =  autoFill({
        firstName: "John", 
        check: true, 
        ni: "Not supposed to be set" // Won't set because he doesn't have the property data-autofill.
    });

  myForm.lastName.value = "Awesome"; // Now we can set values like this because we returned all form elements.

And the jsFiddle.

3
  • Might be worth changing arr to obj to reduce confusion.
    – Andy
    Nov 8, 2013 at 21:01
  • Perfect. One more question -- how could I do a similar loop for the else{} block? Each element has a unique value from the response object. I'd like to clean this up as much as possible to learn cleaner JS. Thank you.
    – tdc
    Nov 8, 2013 at 21:03
  • You can't because each property have different values. It would be longer to do a loop than assigning them manually.
    – L105
    Nov 8, 2013 at 22:17
1

To reuse the names in each area of the function, add them to an array and iterate over them BUT you need to ensure that the properties in response and your DOM element names match.

function autoFill(response) {

  var arr = ['firstName', 'lastName', 'Email', 'phoneNumber'];

  var obj = {};

  arr.forEach(function (el) {
    obj[el] = document.getElementsByName(el)[1];
  });

  if (response === false) {
    alert('false');
    for (var k in obj) {
      obj[k]['value'] = "";
    }
  } else {
    alert('true');
    arr.forEach(function (el) {
      obj[el]['value'] = response[el];
    });
  }

}
0
0

You should store input fields into an array as arr[0], arr[1] and access them with index.

0
0

you have declared: var arr = []; then assigned arr.fn, arr.ln n so..

Either declare var arr = {}; or assign arr.fn, arr.ln as arr[0], arr[1].

When you assign,

     var arr = [];  
     arr["fn"] = document.getElementsByName("firstName")[1];

and observe the value of arr, it will be empty. so declare it as var arr= {}.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.