Search code examples
javascriptobjectloopsplane

Javascript getElementById acting odd


I'm using a for loop to cycle through some elements with a starting value (seats on a plane).

Here it is:
seatNum - Number of seats to be cycled through
startSeat - seat to begin cycling

I'm calling the function from a form "onsubmit".

The problem comes in the for loop when i try and go get elements with an id naming convention of "s1" "s2" "s3" etc... "s45" "s46" etc... based on the loop counter added to the starting seat. Counting from 0(starting seat) up to seatNum(how many seats).

any idea why by id isn't resolving properly? All others work fine except the last one inside the for loop.

Yes I'm new to programming so i probably don't have the best practices, please be forgiving stylistically.

function check() {
    var startSeat;
    var fName = document.getElementById('fName').value
    var lName = document.getElementById('lName').value
    var address = document.getElementById('address').value
    var city = document.getElementById('city').value
    var state = document.getElementById('state').value
    var zip = document.getElementById('zip').value
    var phone = document.getElementById('phone').value
    var seatNum = document.getElementById('seatNumber').value
    var y=document.getElementById('seatList1').value;
    var z=document.getElementById('seatList2').value;

    if (z >= y) {
        startSeat = y;
    }
    else {
        startSeat = z;
    }

    if ( (fName == "") || (lName == "") || (address == "") || (phone == "") || (zip == "") || (state == "") || (city == "") ) {
        alert("You must fully complete the form");
        return false;
    }

    for (var i = 0; i < seatNum; i++) {
        if (document.getElementById("s"+(startSeat+i)).className=="taken"){
            alert("Selected seat(s) already booked.");
            return false;
        }
    else {
            continue;
        }
    }
}

Solution

  • Convert your y and z variables to number:

    var y = +document.getElementById('seatList1').value;
    var z = +document.getElementById('seatList2').value;
    
    var startSeat = (z >= y) ? y : z; // or simply startSeat = Math.min(z,y);
    

    That will fix the problem that @Faruz pointed out.