【问题标题】:Pass checkbox values with Jquery to PHP and display result in div使用 Jquery 将复选框值传递给 PHP 并在 div 中显示结果
【发布时间】:2023-03-16 16:09:01
【问题描述】:

我想用 jQuery 过滤实时结果(就像在这个网站上 http://shop.www.hi.nl/hi/mcsmambo.p?M5NextUrl=RSRCH 一样)。因此,当有人选中复选框时,结果应该实时更新(在 div 中)。现在我是 jQuery 的新手,我尝试了很多例子,但我无法让它工作。这是我的代码,谁能告诉我做错了什么?非常感谢!

HTML

<div id="c_b">
    Kleur:<br />
    <input type="checkbox" name="kleur[1]" value="Blauw"> Blauw <br />
    <input type="checkbox" name="kleur[2]" value="Wit"> Wit <br />
    <input type="checkbox" name="kleur[3]" value="Zwart"> Zwart <br />
    <br />
    Operating System:<br />
    <input type="checkbox" name="os[1]" value="Android"> Android <br />
    <input type="checkbox" name="os[2]" value="Apple iOS"> Apple iOS <br />
    </div>

<div id="myResponse">Here should be the result</div>

jQuery

function updateTextArea() {         
     var allVals = [];
     $('#c_b :checked').each(function() {
       allVals.push($(this).val());
     });

     var dataString = $(allVals).serialize();

    $.ajax({
        type:'POST',
        url:'/wp-content/themes/u-design/filteropties.php',
        data: dataString,
        success: function(data){
            $('#myResponse').html(data);
        }
    });
  }

$(document).ready(function() {
   $('#c_b input').click(updateTextArea);
   updateTextArea();  
});

PHP

//Just to see if the var passing works
echo var_export($_POST);

【问题讨论】:

  • 你想用.serialize() 实现什么,因为它对表单元素进行操作。

标签: php jquery checkbox


【解决方案1】:

您错误地使用了.serialize(),它仅适用于表单元素。

有了这段代码,我想你会得到你需要的。

Javascript / JQuery

function updateTextArea() {         

    var allVals = "";

    $('#c_b input[type=checkbox]:checked').each(function() {

        currentName = $(this).attr("name");
        currentVal  = $(this).val();

        allVals = allVals.concat( (allVals == "") ? currentName + "=" + currentVal : "&" + currentName + "=" + currentVal );

    });

    $.ajax({
        type:'POST',
        url:'/wp-content/themes/u-design/filteropties.php',
        data: allVals,
        dataType: "html",
        success: function(data){
            $('#myResponse').html(data);
        }
    });

  }

$(document).ready(function() {

   $('#c_b input[type=checkbox]').click(updateTextArea);

   updateTextArea();  

});

【讨论】:

  • 嗨,Marcio,感谢您的回答,这正是我所需要的(包括名称值)。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
  • 2018-03-09
相关资源
最近更新 更多