user3071304
user3071304

Reputation: 17

Ajax - form select onchange and window load

I have a bit of code for an ecommerce website were developing at the moment when a user lands on the product details page they have the option to select a clothing size. Once the size is selected it shows the price and whether it is in stock. This is triggered by an onchange event on the select menu.

When the page loads the first size auto selected but doesn't display the contents i.e price and stock level. is there anyway i can simply show this information when the pages loads? any help greatly appreciated.

function showProducts(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        };
        xmlhttp.open("GET","<?php echo ROOT; ?>ExtraProducts.php?q="+str,true);
        xmlhttp.send();
    }
}

Upvotes: 0

Views: 200

Answers (1)

Esko
Esko

Reputation: 4207

You need to call the method when the dom has loaded. One easy way of doing this is by putting that script and the call at the very end of the body. Also change the method slightly to retrieve the selectedvalue itself so that you don't have to pass the value to the function:

function showProducts() {
  var s = document.getElementById("sizeSelect");
  var str = s.options[s.selectedIndex].value;
  console.log(str);
  /* Your old code here... */
}

showProducts();
<select onchange="showProducts();" id="sizeSelect">
  <option value="1">First</option>
  <option value="2" selected>Second</option>
</select>

Upvotes: 1

Related Questions