【问题标题】:Prevent loading page when changing select value更改选择值时阻止加载页面
【发布时间】:2020-06-01 18:16:30
【问题描述】:

我的表单中有这个选择标签,其中包含房间的名称

<select class = 'form-control' id = 'room_select' name = 'room'>".$rooms."</select>

我有 4 个房间,所以这个选择包含 4 个选项

$(document).ready(function(){
$("select").msDropDown();
$("#room_select").change(function(e){
    e.preventDefault();
    $("#room_select_form").submit();  
});
$("#room_select option[value='<?php echo $room; ?>']").attr('selected', 'selected');
});

然后我得到了这个文档准备功能,第一个.msDropDown(); 是能够在选项中获取图像。然后我得到了更改功能,我在谷歌上搜索并放入了一个 preventdDefault 以不刷新页面,(仍然刷新)我认为我可以使用 ajax 功能来做到这一点,但我真的不知道如何写下来,或者即使它作品。

所以目前的问题是我的函数改变了代码中最后看到的房间值,但它刷新了选择标签,我再次看到房间 nr 1,

【问题讨论】:

    标签: javascript jquery ajax preventdefault


    【解决方案1】:

    您的页面正在刷新,因为您在 onchange 侦听器中提交表单。您需要将e.preventDefault(); 放入表单提交侦听器中以防止默认表单提交,然后您可以在提交侦听器中调用ajax。

    $(document).ready(function(){
    $("select").msDropDown();
    $("#room_select").change(function(e){
        $("#room_select_form").submit();  
    });
    $("#room_select option[value='<?php echo $room; ?>']").attr('selected', 'selected');
    $("#room_select_form").submit(function(e){
      e.preventDefault(); // to prevent page refresh
      // your Ajax call goes here....
    
    });
    });
    

    【讨论】:

    • 感谢您的回答,这部分现在至少可以工作了,现在我只需要弄清楚如何做 ajax
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    相关资源
    最近更新 更多