简体   繁体   中英

jQuery inArray only looking at first value

$('#client').keyup(function() {
    if ($('#client').val() != $('.recent_client').attr('id')) {
        $('.recent_client').removeClass('recent_client_active').addClass('recent_client_inactive');
    }
    else if (jQuery.inArray(parseInt($('#client').val()), client_ids)) {
        alert('IN ARRAY');
    }
});

My HTML

<p><input type="text" name="client" id="client" placeholder="Click here and start typing your client name..."></p>

<div id="recent_clients">
<p><a href="#" class="recent_client recent_client_inactive" id="Client Name 1">Client Name 1</a><a href="#" class="recent_client recent_client_inactive" id="Client Name 2">Client Name 2</a><a href="#" class="recent_client recent_client_inactive" id="Client Name 3">Client Name 3</a><a href="#" class="recent_client recent_client_inactive" id="Client Name 4">Client Name 4</a><a href="#" class="recent_client recent_client_inactive" id="Client Name 5">Client Name 5</a><a href="#" class="recent_client recent_client_inactive" id="Client Name 6">Client Name 6</a></p>
</div>

I have an array that contains the id values of each a in my #recent_clients div. Simple stuff. I also have an input box. If you type out the full name of one of the recent clients, I want that client name to highlight. So I assumed jQuery.inArray would help out with this, but it doesn't work. If I type out the first value of the array ("Client Name 1"), I get the alert. However, if I type any other client name following ("Client Name 2" for example), nothing happens.

What might I be doing wrong here?

Since inArray() works like indexOf, you should test for the result being > -1

Updated

    var client_ids = ['Client Name 1', 'Client Name 2', 'Client Name 3', 'Client Name 4', 'Client Name 5'];
$('#client').keyup(function() {
    if (jQuery.inArray($('#client').val(), client_ids) > -1) 
        $('#client').css('background-color','#00cc00');
    else
       $('#client').css('background-color','#cc0000');
});

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