0

I can't figure out why var seatsSelected isn't updated after my function even though it's a global variable. The array logs to the console just fine when it's inside my function but I need to use the array in other functions. Can someone help me edit my code?

$(document).ready(function() {
    var seatsSelected = [];
    var users = [];

    $("#purchase").hide();

    //Inserts seat selection in form input
    $(".seat").on("click", function() {
        $('#purchase').show();
        var indexOfSeat = seatsSelected.indexOf($(this).children('p').text());
        if (!($(this).hasClass("unavailable"))) {
            $(this).toggleClass("selected");
            if (($(this).hasClass("selected"))) {
                seatsSelected.push($(this).children('p').text());
                seatsSelected.forEach(function(each) {
                    $("#seats").val(seatsSelected);
                });
                //Removes unclicked seats
            } else if (!($(this).hasClass("selected"))) {
                seatsSelected.splice(indexOfSeat, 1);
                seatsSelected.forEach(function(each) {
                    $("#seats").val(seatsSelected);
                });
            }
        } else if ($(this).hasClass("unavailable")) {
            alert('This seat is unavailable')
        }
    })

    console.log(seatsSelected);
});
Jennifer Nicole
  • 5
  • 1
  • 1
  • 5
  • 5
    The value isn't affected until the "click" handler runs. – Pointy Jul 18 '16 at 19:00
  • 1
    you're not running the code. you define a click handler, which is essentially instaneous, then immediately log the value in that var. since the code hasn't run, no value has been assigned. – Marc B Jul 18 '16 at 19:01
  • 1
    To add to that, if you need `seatsSelected` to be updated on click, in addition to initialize the page, consider using `$(".seat").trigger('click');` – Charles Jul 18 '16 at 19:02
  • To assign value to seatsSelected you need to trigger click ie. click on any item having class .seat. Then value will be pushed to seatsSelected. After that you can use it in another function and this should work fine. – Amit Kumar Jul 18 '16 at 19:06
  • Thanks for all the responses. This makes sense but I'm having trouble figuring out how that would look in the code. Any suggestions? – Jennifer Nicole Jul 18 '16 at 20:06

0 Answers0