stackuser stackuser - 7 months ago 22
Javascript Question

Dependable dropdown Menu

I am trying to make a dependable drop down menu.

In my project each user are bound to single parent menu i.e. when a user sign in it will load only one parent menu and based on the single parent menu it will load 2 or 3 sub menu. This process is applicable to all other user's with different parent menu assigned for different users.

My problem is when a user is logged in he will have to click the single preloaded parent menu and it will load sub menu. But I want to load sub menu without clicking on the single preloaded parent menu.

PHP code for generating parent menu is

<select name="ddlstate" id="ddlstate" class="ddlstate" style="width: 200px" >
<?php
require('connect.php');
$list=mysql_query("select id,name from tbl_state where id='$region_session' ");
while($row_list=mysql_fetch_array($list))
{
?>

<?php
$id=$row_list['id'];
$data=$row_list['name_en'];
echo '<option value="'.$id.'">'.$data.'</option>';
?>
</select>


Javascript code for generating submenu is

<script type="text/javascript">
$(document).ready(function()
{
$(".ddlregion").focus(function()
{
var id=$(this).val();
var dataString = 'id='+ id;

$.ajax
({
type: "POST",
url: "menu_update.php",
data: dataString,
cache: false,
success: function(html)
{
$(".ddl_lbtype").html(html);

}
});

});
});

</script>


Thanks in advance

Answer

Your jQuery code waits for the page to be ready, then binds a function to the focus event of the element with class ddlregion.

It sounds like you don't want to wait for the focus event and instead run the function immediately.

All you have to do is take the function you are binding to the focus event and put it directly inside the call to ready (and replace this with the element of the menu).

I couldn't test this, since you didn't provide the HTML, but all I did was make the changes I mentioned and clean up the formatting. Hope it works!

$(document).ready(function(){
    var id=$(".ddlregion").val(); 
    var dataString = 'id='+ id;
    $.ajax({
        type: "POST", 
        url: "menu_update.php",
        data: dataString,
        cache: false,
        success: function(html){
            $(".ddl_lbtype").html(html);
        } 
    });
});

Consider just sending the complete menu to the client or using $.load to bring in the HTML for the menu (assuming your API will allow a GET instead of a POST).