-1

So im a newbie and I need some basic help. I wanna make a program that checks whether room is free or taken. I dont know if i can make just a variable with all free rooms or should i do this the other way. I'm kinda stuck on solving the problem.

function action() {
    var room = document.getElementById('text');
    var free = [1, 2, 3];
    if (room.value == free) {
        alert('Hello');
    } else {
        alert('Taken');
    }
}

document.getElementById('button').onclick = function() {
    action();
}

I wanna ask if is it possible to just compare variable i enter to other variable with list of free rooms if not, how to make this work then?

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392

4 Answers4

2

You can't just compare your number with an array. You need to check if your number is in the array:

if (free.indexOf(room.value) > -1)

Also, assuming you're using a text field, you'll need to convert room.value to a Number (instead of String) before checking:

if (free.indexOf(+room.value) > -1)

You can learn more about indexOf() on MDN.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
1

The line if (room.value == free) compares a string (the value) with an array. That won't usually be true.

To find a value in an array, you use Array#indexOf. It does strict comparison, so since your values in the array are numbers, you have to make sure that your value is a number as well.

So

if (free.indexOf(+room.value) != -1) {
    // Yes it's there
}

The unary + is one way to convert strings to numbers. Another is parseInt, which lets you specify a radix (number base):

if (free.indexOf(parseInt(room.value, 10)) != -1) {
    // Yes it's there
}

You have other options as well; this answer lists the various options and the pros and cons of them.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

You can try this. Going further, you can remove the room number taken from the list of free rooms and push them into list of rooms already taken.

function action() {
  var isRoomAvailable = false;
  var room = document.getElementById('text').value;
  var freeRoom = [1, 2, 3]; // 4-10 are taken rooms.
  var takenRooms = [4, 5, 6, 7, 8, 9, 10];
  for (var i = 0; i < freeRoom.length; i++) {
    if (room == freeRoom[i]) {
      alert('Hello, You can take room '+room);
      isRoomAvailable = true;
      return;
    }
  }
  if (!isRoomAvailable) alert("Sorry, Room number " + room + " is taken");
}



document.getElementById('button').onclick = function() {
  action()
}
Enter Room number(1-10):
<input type="text" id="text" />

<button id="button">Search Room</button>
Sandeep Nayak
  • 4,649
  • 1
  • 22
  • 33
1

You should perhaps use a 0 and 1 system for storing whether a room is taken. So 0 is for taken and 1 is for free or vice versa depending on your liking. So all it would have to do is test for whether in the array, the room's value is 0 or 1

S. T. Lam
  • 9
  • 4