简体   繁体   中英

How do I set a default value for my .onchange function and still keep the 'onchange' functionality?

I have created a custom search application showing results of a user input. In the application I have included a way for the user to control the amount of results that display.

HTML

<select id="countShow">
    <option selected="selected">10</option>
    <option>25</option>
    <option>50</option>
    <option>100</option>
</select>

jQuery

$("select").on('change', function () {
    $('#countShow').val(10);
    var str = "";
    $("select option:selected").each(function () {
    str = $(this).text();
    str = parseInt(str) - 1;
});
    $('div > #result:gt('+str+')').remove();
    console.log(str);
})

My console.log shows the original value as 10 when the page loads and I understand that it is waiting for the control to change.

I have tried adding the following before the function to create a default value:

$('#countShow').val(10); //the value stays 10 and will not change on event
$('div > #result:gt(9)').remove(); //does the same as the first

you can call it on page load:

$(document).ready(function(){
  $("select").trigger('change');
});

trigger simulates the change event on loading the page

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