0

I have a form using rows to receive user input. The user can click a link to get a new row. The link calls a function that, after creating a new row and cell, creates a new element. When the element is created another function is called that, when needed, uses AJAX to receive the SELECT options. This works fine.

When the new element is complete, a function is called to copy selected element values from the previous row into the new row. However, what happens is beyond me.

Copying an INPUT value from the previous row to the new row works. Copying the selectedIndex from a SELECT only works when an alert box is shown before new_element.selectedIndex is set.

The function:

function CopyPreviousValue(new_element, old_element_name, new_id) {
  if (new_id > 1) {
    var old_element = document.getElementsByName(old_element_name)[0];
    switch (old_element.tagName) {
      case "SELECT":
        //alert("[old_element.selectedIndex] "+old_element.selectedIndex);
        new_element.selectedIndex = old_element.selectedIndex;
        if (old_element.selectedIndex != -1) new_element.disabled = false;
        break;
      case "INPUT":
        new_element.value = old_element.value;
        if (old_element.value != "") new_element.disabled = false;
        break;
    }
  }
}

I can't see anything spectacular here.. Can someone please enlighten me on why this happens and how to fix this?

1 Answers1

0

Your select boxes are probably not rendered yet when this code runs. The browser may be clearing the selectedIndex while rendering for options with the attribute selected="selected". The alert gives the browser time to render the select before the selectedIndex is copied which is why it works with the alert and not without.

Try adding this code after you set the selected index.

if (old_element.selectedIndex != -1) {
    new_element.options[old_element.selectedIndex].setAttribute('selected','selected');
    new_element.disabled = false;
}
Ralph Ritoch
  • 3,260
  • 27
  • 37
  • Thanks Ralph..Because I'm using the same selectedIndex multiple times, I changed my code to include: `var n = old_element.selectedIndex;` And in the place you suggested: `new_element.options[n].setAttribute('selected', 'selected');` In the JS error console, I see now: `Error: TypeError: new_element.options[n] is undefined` So, since n is correctly defined (I checked that using an alert), this must indeed be because the options of new_element aren't fully rendered.. I have multiple select elements in a row.. Is there a way to wait for this to happen without using an alert? – Storm49152 Dec 30 '13 at 11:37
  • Okay, so I found out this happens because AJAX is asynchonous and that the not-recommended way to fix this is to make he .open method synchronous.. I'm now trying to fix it in a recommended way.. For reference: [link](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Storm49152 Dec 30 '13 at 11:55