peace_love
peace_love

Reputation: 6471

How can I start my jquery function only on input change, not on page load?

I have a select box, which autoselects automatically the appropriate value of my input field. It works very well:

<input id="count" value="2.00" type="number">

<select class="autoselect">
  <option data-number="1000000000000" selected value="dog">dog</option>
  <option data-number="2000000000000" value="horse">horse</option>
  <option data-number="4000000000000" value="cat">cat</option>
  <option data-number="5000000000000" value="bird">bird</option>
</select>

Here is the query code:

$(document).ready(function(){
    var count = 1000; 
    $('#count').change(function () {
            var that = parseInt($(this).val()*Math.pow(count, 4), 10);                          
            $('.autoselect option:gt(0)').each(function () {
                $(this).prop('disabled', ($(this).data('number') < that))
                .prop('selected', ($(this).data('number') >= that && $(this)
                .prev().data('number') < that));
            })
            if (that <= $('.autoselect option:eq(1)').data('number')) $('.autoselect option:eq(1) ').prop('selected', true);
            $('select.autoselect option[data-number=0]').prop('disabled', false);       
        }).change()
}

What I want to achieve is actually a simple thing. On page load, "dog" should always be selected. Only by changing the input, my script should start to work. But it is already selecting "horse" on page load, even if I wrote the function on input change.

Upvotes: 0

Views: 60

Answers (1)

Māris Kiseļovs
Māris Kiseļovs

Reputation: 17295

Your second .change() function is triggering this event on page load. jQuery event functions without callbacks are event triggers. Just remove second .change() at end of your code.

Upvotes: 3

Related Questions