I have a form with combo boxes and calculations based on the value of the combo box. I set a default value in the combo box on loading the form but this value is not seen for calculations unless i go and reselect it with a mouse pick. What is happening and how can I avoid having to reselect the item with a mouse pick. I assume there is a code I can create to simulate a mouse pick but I have not been able to figure this out. Any help would be appreciated.

Dani AI

Generated

Quick diagnosis: when a select has a default option already shown but your calculations only update after a manual reselect, the calculation code is relying on an event that never fires on page load (for example the user-generated change), or the calculation runs before the DOM/select value is ready. As hinted, the event choice/timing is the usual culprit; s symptoms match this pattern.

A reliable pattern is: attach listeners on DOM ready, ensure the select really has the intended value, then run the calculation once explicitly. Example pattern:

document.addEventListener('DOMContentLoaded', function () {
  var sel = document.getElementById('mySelect');
  sel.addEventListener('change', calculate, false);
  // ensure default exists, or set it here:
  sel.value = 'defaultValue';   // or sel.selectedIndex = 1;
  calculate();                  // force initial calculation
});

function calculate() {
  var sel = document.getElementById('mySelect');
  var v = parseFloat(sel.value) || 0;
  // do calculation and update UI
}

If you prefer to simulate the user action instead of calling your handler, dispatch a change event (modern browsers) or fall back for older IE; jQuery has $('#mySelect').trigger('change'). For dispatching see MDN on dispatchEvent (dispatchEvent). For proper startup use the DOMContentLoaded event (DOMContentLoaded).

Troubleshooting checklist: confirm each <option> has a value, check the value in the console (console.log(sel.value, sel.selectedIndex)), convert values with parseFloat/parseInt (use radix when using parseInt) and make sure the initial calculation runs after listeners are attached or simply call the calculation manually. See parse rules here: parseInt.

Recommended Answers

All 2 Replies

You're using the wrong event.. Have a look at the others (I know this has been discussed before, I thought even with you)

Liz i have tried many events and they are not working. I changed the code so the person has to select an item manually.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.