1

我想用 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);
4

1 回答 1

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();  

});
于 2012-07-04T23:01:32.527 回答