You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将SweetAlert2中表单下拉框的值传递到then{}代码块?

如何获取SweetAlert中下拉框的值并传递到then代码块?

你遇到的核心问题是:SweetAlert里的表单是动态插入到DOM中的,和页面原本的表单并非同一个元素,所以不能直接用原来的.myfrom选择器去取值。这里给你一个简单直接的解决方案:

在用户点击确认按钮(也就是result.value为true时),直接定位到SweetAlert弹窗内部的下拉框元素,获取它们的值即可。SweetAlert的弹窗内容会被包裹在特定容器中(通常是带.swal2-html-container类的元素,不同版本可能略有差异,你可以通过浏览器开发者工具确认),我们基于这个容器来选择内部的select元素就不会出错。

修改后的代码示例如下:

var form = $('.myfrom').html();
swal({
  title: 'edit form',
  html: form,
  showCancelButton: true
}).then((result) => {
  if (result.value) {
    // 从SweetAlert弹窗中获取三个下拉框的值
    const name1Val = $('.swal2-html-container select[name="name1"]').val();
    const name2Val = $('.swal2-html-container select[name="name2"]').val();
    const name3Val = $('.swal2-html-container select[name="name3"]').val();

    swal({
      title: 'done',
      text: 'it has been done!',
      type: 'success',
    });

    // 在AJAX请求中传递这些值
    $.ajax({
      url: '你的请求地址',
      method: 'POST', // 可根据需求改为GET
      data: {
        name1: name1Val,
        name2: name2Val,
        name3: name3Val
      },
      success: function(response) {
        // 请求成功后的处理逻辑
      },
      error: function(xhr) {
        // 请求失败后的处理逻辑
      }
      // 其他AJAX配置项...
    });
  }
});

关键点说明:

  • 用.swal2-html-container作为父容器选择select,确保拿到的是弹窗内的下拉框,而非页面原本的表单元素
  • 若你的SweetAlert版本较旧,容器类可能是.swal-content,可以打开浏览器开发者工具查看弹窗DOM结构来确认正确的容器类名
  • 获取到值后,直接将其放入AJAX的data参数中,就能传递给后端接口了

内容的提问来源于stack exchange,提问作者Areza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:41:26