skip to Main Content

I have a select box. The selected option is sent with ajax to a server side script. This works well.

the select box

<select id="main_select">
    <option selected="selected">50</option>
       <option value="40">40</option>
       <option value="30">30</option>
       <!-- other options -->
</select>

How can I extend the .change function that the default value <option selected="selected">50</option>is automatically send with the page load.

script:

$(document).ready(function () {
    $('#main_select').change(function () {
           $.ajax({
               url: "itemscript.php",
               type: "post",
               data: {option: $(this).find("option:selected").val()},
               success: function(data){

                   $("#details").html(data);
               }
           });
       });
});

2

Answers


  1. Just trigger the change event when the page is loaded.

    $(document).ready(function() {
      $('#main_select').change(function() {
        $.ajax({
          url: "itemscript.php",
          type: "post",
          data: {
            option: $(this).val()
          },
          success: function(data) {
            $("#details").html(data);
          }
        });
      }).change();
    });
    

    Also, you can use $(this).val(), that gets the value of the selected option.

    Login or Signup to reply.
  2. Why not extract the functionality to a seperate function? This helps to avoid hacks like triggering a change manually – if you had multiple listeners for such a change event, all would fire, and this might not be what you expect to happen 😉

    function getData(select) {
        $.ajax({
            url: "itemscript.php",
            type: "post",
            data: { option: $(select).find("option:selected").val() },
            success: function(data) {
                $("#details").html(data);
            }
        });
    }
    
    $(document).ready(function () {
        getData($('#main_select'));
        $('#main_select').change(getData);
    });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search