简体   繁体   中英

Detecting if input has been entered before

Lately I've been having trouble checking whether an input (player name) has been input more than once. This is not in-database, but just based on arrays contained within JavaScript. What I've been using after a couple of google searches was the indexOf() function. However this does not seem to work. My code is as follows:

var numberPlayers = 1;
var players = [];

var AddPlayer = function() {
    if(!(players.indexOf($(".name")).val() > -1)) {
        players.push($(".name").val());

        $(".players").append("<p>Player number " + numberPlayers + " is " + $(".name").val() + "</p>");
        numberPlayers++;
    }
};

What method of detection would you recommend? I've tried looping, but wouldn't work either.

EDIT: Updated code. Still doesn't work!

Try this - note where the ) is placed:

if(!(players.indexOf($(".name").val()) > -1)) {

instead of:

if(!(players.indexOf($(".name")).val() > -1)) {

and actually, for readability this would be better:

var name = $('.name').val();
if ( players.indexOf(name) == -1)) {

In general, try adding console.log and breakpoints to find your bugs...

You can use an object (read Set / Hash) instead of an array; it should be faster anyway. Note that I'm also using .text() which will escape text.

var numberPlayers = 1;
var players = {};
var AddPlayer = function() {
    var newPlayer = $(".name").val();
    if(!(newPlayer in players)) {
        players[newPlayer] = true;
        $(".players").append($("<p>").text("Player number " + numberPlayers + " is " + newPlayer));
        numberPlayers++;
    }
};

jQuery has a utility function for this:

$.inArray(value, array)

It returns the index of a value in an array. It returns -1 if the array does not contain the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM