2

our 10 year old software used to be written in PHP, combined with HTML and SQL snippets. I am forced to make the best out of it.

Having no experience at all with JavaScript, I have to use jQuery's inArray to get the index by value.

Although everything seems to be right, inArray returns -1 all the time, although I should get the proper index. So what have I done wrong?

$html1 .= "<script src='/js/jquery-3.2.1.min.js'> </script>
<script>  var juseridarray = ".json_encode($useridarray).";

$(document).ready(function()
{
    $('#chiefname').change(UpdateInfo);
    $('#chiefid').change(UpdateInfo);                                                                                            
    $('#chiefs').change(UpdateInfo);
});
function UpdateInfo()
{
    var chiefname = $('#chiefname').val();                                                                                      
    var chiefid = $.inArray( chiefname, juseridarray);
    var chief = chiefid;
    $('#chief').val(chief);
    console.log(juseridarray);
    console.log(chiefname);
}

</script>";

Excuse me, I forgot to mention the log output. So this is a snippet of juseridarray log output which I copied from firebug:

Object[430]
1: "Administrator"
3: "Bob"
8: "Wegner, Meike "
10: "Uhrenbauer, Sonja"
[426 more...]

The array seems to have an correct index and correct values. So when I search for 'Bob', inArray returns -1, although 'Bob' is expected to return 3. On the other hand, I get 'Bob' in return when using

console.log(juseridarray[3]);

The array content is static. It doesn't change in runtime. And if it would, usernames would always keep their id (stored as index)

2
  • negative one means not found according to the API, meaning you may not have what you think you do in that array Commented Oct 5, 2017 at 14:53
  • We need more info to help. Please edit your question to include the output of $useridarray. Does it change or is it static? Commented Oct 5, 2017 at 14:59

1 Answer 1

1

First of all, it is not an array you are operating with, it's an object.

You cannot use inArray of an object like you intend to do. The code below should however, return the id, of the user with the given username, if it exists.

function findUserIdByUsername(user, userArray){
     var user_id = false;
     $.each(userArray, function(id, username){ 
          if( user == username ) user_id = id
     });
     return user_id;
}

var chiedif = findUserIdByUsername('bob', juseridarray);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it gives the expected result. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.