简体   繁体   中英

Pass checkbox values with Jquery to PHP and display result in div

I want to filter realtime results with jQuery (just like on this site http://shop.www.hi.nl/hi/mcsmambo.p?M5NextUrl=RSRCH ). So when someones checks a checkbox the results should update realtime (in a div). Now I'm a newbie with jQuery and I've tried lots of examples but I can't get it to work. Here's my code, could anyone tell what I'm doing wrong? Thank you very much!

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

You are using .serialize() incorrectly, it works only with form elements.

With this code i think you'll get what you need.

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM