Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
        }
    }
}
like image 393
user48202 Avatar asked Dec 03 '22 14:12

user48202


2 Answers

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.

like image 86
Christian C. Salvadó Avatar answered Dec 22 '22 02:12

Christian C. Salvadó


I'm not sure, but maybe startSeat+i concats the strings and not doing the mathematical add you expect. Try alerting to screen:

alert(document.getElementById("s"+(startSeat+i))); 

Is it the field name?

like image 38
Faruz Avatar answered Dec 22 '22 00:12

Faruz