【问题标题】:Jquery form submission via radio button change通过单选按钮更改 Jquery 表单提交
【发布时间】:2016-06-24 18:56:05
【问题描述】:

我的网站有一个新闻管理脚本,允许我添加、更新和删除新闻。我决定使用 jQuery 来让事情变得更顺畅,虽然我已经让添加/编辑/删除部分工作了,但我想在默认页面上添加一个简单的函数来进行新闻编辑。

当您访问默认新闻页面时,您会看到一个简单的以前新闻帖子的列表。显示的列是:

新闻标题、作者、发布日期、活动、编辑

对于“活动”列,我想要一个简单的开关来设置为“活动”或“非活动”。一旦该开关被翻转,相应的新闻帖子就会被更新,而无需重新加载整个页面。它只是执行。

(UI 的附注:我还想为该新闻帖子的表格的单元格颜色设置动画,但这将是我稍后可以解决的问题)

目前 news-list.php 脚本像这样加载每一行:

$news_edit_options .= "<tr id=\"" . $row["newsid"] . "\">";
$news_edit_options .= "     <td>" . $row["title"] . "</td>";
$news_edit_options .= "     <td>" . $row["login"] . "</td>";
$news_edit_options .= "     <td>" .$row["date_released"] . "</td>";
$news_edit_options .= "     <td>";
$news_edit_options .= "       <form method=\"post\" action=\"news-activator.php\" class=\"news-activator\">";
$news_edit_options .= "          <input type=\"hidden\" name=\"newsid\" value=\"" . $row["newsid"] . "\">";
$news_edit_options .= "          <input type=\"radio\" name=\"active\" value=\"0\"";
if ($row["active"] == 0) {
     $news_edit_options .= " checked";
}
$news_edit_options .= "> inactive <br />";

$news_edit_options .= " <input type=\"radio\" name=\"active\" value=\"1\"";
if ($row["active"] == 1) {
     $news_edit_options .= " checked";
}
$news_edit_options .= "> active";
$news_edit_options .= "  </form>";
$news_edit_options .= "</td>";
$news_edit_options .= "     <td><button type=\"button\" class=\"btn btn-primary newsbutton\" data-toggle=\"modal\" data-target=\"#newsModal\" id=\"" . $row["newsid"] . "\">Edit</button></td>";
$news_edit_options .= "</tr>";

这很好。现在进入 jQuery:

$.when(LoadAPage('#news-list','news-list.php')).done(function() {
    $("input[type=radio]").change(function() {
        $(this).closest("form").submit(function() {
        // do stuff here
        });
    });
});

这行不通。 .submit(function() {}); 部分完全不起作用。但是,当我将其更改为:

$.when(LoadAPage('#news-list','news-list.php')).done(function() {
    $("input[type=radio]").change(function() {
        $(this).closest("form").submit();
    });
});

这会“工作”,但表单只是提交,我无法使用 jQuery 捕获数据并做我想做的所有事情。我确实尝试了复选框,但遇到了同样的问题。

我有一种感觉,我只是遗漏了一些东西或接近这一切都是错误的。有什么想法吗?

【问题讨论】:

    标签: php jquery forms radio-button


    【解决方案1】:

    试试这个。我认为您的两次尝试都完成了一半,您只需将它们组合在一起即可:)

    $.when(LoadAPage('#news-list','news-list.php')).done(function() {
        $("input[type=radio]").change(function() {
            $(this).closest("form").submit(function(e) {
               e.preventDefault();
               alert("the form was submitted");
            });
            $(this).closest("form").submit();
        });
    });
    

    第一个提交函数告诉 jQuery 在提交表单时要做什么。 e.preventDefault(); 阻止默认操作(即在您有时间执行任何其他 jQuery 之前提交表单并重新加载页面)。

    第二个.submit(); 触发表单提交,它运行来自我们提交处理函数的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 2013-06-10
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 2019-07-20
      • 2018-10-14
      • 2014-03-20
      相关资源
      最近更新 更多