2

Hi I'm trying to loop and check an array with specific values. If the value already exists that the user want to use in the input a message will be displayed, if the username is a correct one and new it will be uploaded to my firebase! It works for the first element in the array but if i set .length in the loop it takes all but sends the false value anyway?

<form id="">
    <label>Your username: </label><input type="text" id="userName">
</form>

<script src="text/javascript">
    var invalidUser=['value1','value2','value3','value4'];
    var myDataRef = new Firebase('https://leastflyingwasps.firebaseio.com/');

    $('#userName').keypress(function (e) {
        if (e.keyCode == 13) {
            var name = $('#userName').val();
            for (var i = 0;i<invalidUser;i++) {
            }

            if (invalidUser[i] === name) {
                alert('Not a valid username')
            }
            else {
                myDataRef.push({name: name});
            }
        }
    });
</script>
4

1 に答える 1

4

最初の問題は、チェックが実際にはforループの外で行われているためです。次に、次を使用してこれを単純化できます$.inArray()

var invalidUser = ['value1', 'value2', 'value3', 'value4'];

$('#userName').keypress(function (e) {
    if (e.keyCode == 13) {
        var name = $('#userName').val();

        if ($.inArray(name, invalidUser) != -1) {
            alert('Not a valid username')
        }
        else {
            var myDataRef = new Firebase('https://leastflyingwasps.firebaseio.com/');
            myDataRef.push({ name: name });
        }
    }
});
于 2013-10-15T15:08:52.787 に答える