2

I am just using inArray() function in jquery but its not working. Actually I want check value in an array. I got lots of solutions on stackoverflow but nothing working that's why I created new post.

There is an hours format 1-24 and user can select their time slot like 1-3, 5-9, etc..

here is my code

jQuery('.select_hours').click(function(){ 
            var favorite = new Array();
            jQuery.each(jQuery("input[name='hour_count']:checked"), function(){            
                favorite.push(jQuery(this).val());
            });

            console.log(favorite);

            var max_v = Math.max.apply(Math,favorite);
            var min_v = Math.min.apply(Math,favorite);

            // check the number sequence
            for(var i = min_v; i <= max_v; i++){

                if(jQuery.inArray(i,favorite) != -1){
                    alert('Hours in sequence!');
                }else{
                    alert('Please select hours in sequence!');
                }
            }

        });

Please help me in this..

Here is the HTML checkboxes and button:

<input type="checkbox" name="hour_count" id="hour_count_1" value="1"><input type="checkbox" name="hour_count" id="hour_count_2" value="2"><input type="checkbox" name="hour_count" id="hour_count_3" value="3"><button type="button" id="select_hours" class="select_hours">Select Hours</button>
0

3 Answers 3

1

Running val() on a checkbox returns a string containing the set value of the checkbox. But your for loop requires numbers. That's why you need to push numbers, not strings into your array. Use

favorite.push(parseInt(jQuery(this).val()));

Working example: https://jsfiddle.net/websiter/f2kgetec/

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much @Andrei, you save me. I just spoiled my whole day for this silly mistake.
You're welcome, @ManishNegi. And it's not a silly mistake. It's a common one, which you'll learn to avoid. Happy coding!
0

jQuery.inArray returns the index of the element if found or -1 if it isn't -- not a boolean value. So the correct is

if(jQuery.inArray(i, favorite) !== -1)
{
     console.log("is in array");
     alert('Hours in sequence!');
}
 else {
    console.log("is NOT in array");
    alert('Please select hours in sequence!');
}

Comments

0

The inArray method uses a strict comparison. Maybe the issue is just that you are comparing strings and numbers. Try to convert the max_v and minx_v to strings int his way:

var max_v = "" + Math.max.apply(Math,favorite);
var min_v = "" + Math.min.apply(Math,favorite);

And then in the for uses a parseInt(min_v) parseInt(max_v) for cycling.

p.s. Updating as per comment, you can of course also parse directly the .val()

Cleaner solution would be to use an array of numbers directly converting the .val()

favorite.push(parseInt(jQuery(this).val()))

Then if you want to look for an element inside the array, just use standard indexOf method

if (favorite.indexOf(myValueToCheck !== -1))

7 Comments

A better way would be to parseInt on .val()s. But, as a rule of thumb, you should not make assumptions when answering. It is best you do not answer a question that does not provide sufficient information about the source of the problem.
Yeah, sure you can directly convert to int the .val(). About answering, I think there are enough info about. The problem should be the comparison between strings and numbers. And you posted the answer as well highlighting this issue :)
Yes, after testing, I realized checkbox's .val() always returns a string and a for loop always requires integers. However, both existing answers suggested pushing strings into the array and subsequently parsing them to ints, rather than pushing ints to the array, which is much cleaner.
To be honest the cleaner solution is to use array of numbers and use a simple indexOf for finding if the element is in.
There are several ways to do it and whether one is better than the other is clearly debatable. But considering the current code, the easiest fix, IMHO, is the one I proposed. Of course, one could go about and streamline the entire script above into a one-liner but, most probably, that would cease to be an answer about inArray() :).
|

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.