doupan6648
2012-07-18 13:10
浏览 818

在页面加载时触发onchange html事件

Ok I have a onchange event on a select field. It now works great. When the dropdown "networks" is changed it refreshes the second dropdown. I also want the ajax code at the top to trigger on page load as well as onchange so the second list gets populated. This is due to it being on an edit page. Here is the ajax call im using first

function get_cities(networks) {
    $.ajax({
        type: "POST",
        url: "select.php", /* The country id will be sent to this file */
        beforeSend:     function () {
            $("#folder").html("<option>Loading ...</option>");
        },
        //data: "idnetworks="+networks,
        data: "idnetworks="+networks +"&doc="+ <?php echo $row_rs_doc['parentid']; ?>,
        success: function(msg){
            $("#folder").html(msg);
        }
    });
} 

now the two dropdown boxes

<label for="networks"></label>
<select name="networks" id="networks" onChange='get_cities($(this).val())'>
    <?php
    do {  
    ?>
        <option value="<?php echo $row_rs_net['idnetworks']?>"<?php if (!(strcmp($row_rs_net['idnetworks'], $row_rs_doc['network']))) {echo "selected=\"selected\"";} ?>><?php echo $row_rs_net['netname']?></option>
    <?php
    } while ($row_rs_net = mysql_fetch_assoc($rs_net));
    $rows = mysql_num_rows($rs_net);
    if($rows > 0) {
        mysql_data_seek($rs_net, 0);
        $row_rs_net = mysql_fetch_assoc($rs_net);
    };
    ?>
</select>
<select name="folder" id="folder">
</select>
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanhuang2150 2012-07-18 13:19
    已采纳

    You can use .trigger() to trigger a change event onto the select-box so the onchange code will be called like it would if the user just switched the option.

    jQuery('#networks').trigger('change');
    

    Just include this into the load event/function for the page.

    jQuery(document).ready(function() {
        jQuery('#networks').trigger('change');
    });
    
    已采纳该答案
    打赏 评论
  • doukang7858 2012-07-18 13:17

    I'm not 100% clear what you want but the standard way to do something with JQuery when the page is loaded, is to use

    $(document).ready(handler)
    

    This waits till the page is "ready" which is better.

    So, in your document head you'd have something like this...

    <script type="text/javascript">
    $(document).ready( function(){
      do_some_stuff();
    });
    </script>
    
    打赏 评论
  • doumiang0597 2012-07-18 13:19

    Can't you just call get_cities($('#networks').val()) when the DOM is ready?

    $(function() { // will be run by jQuery when DOM is ready
      get_cities($('#networks').val());
    });
    
    打赏 评论

相关推荐 更多相似问题