Friday, 19 September 2014

PHP: Get values from Dynamically created textboxes and checkboxes linked to textbox

<form method="POST">
    <div class="data_class">
        <div class="fieldset" data-group="A">
            <input class="textbox_class" name="form_values[A][textbox]" type="text" />
            <input class="checkbox_class" name="form_values[A][checkbox][]" type="checkbox" value="1" />1
            <input class="checkbox_class" name="form_values[A][checkbox][]" type="checkbox" value="2" />2
            <input class="checkbox_class" name="form_values[A][checkbox][]" type="checkbox" value="3" />3
            <input class="checkbox_class" name="form_values[A][checkbox][]" type="checkbox" value="4" />4
            <input class="checkbox_class" name="form_values[A][checkbox][]" type="checkbox" value="5" />5
        </div>
    </div>
    <button type="button" id="spawn">Spawn More</button><br/>
    <input type="submit" name="submit" />
</form>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

    $('#spawn').on('click', function(){
        var $initial = $('div.fieldset:last').clone();
        // or just increment a number instead
        var next = String.fromCharCode($initial.attr('data-group').charCodeAt(0) + 1);
        $initial.children('.textbox_class').attr('name', 'form_values['+next+'][textbox]');
        $initial.children('.checkbox_class').attr('name', 'form_values['+next+'][checkbox][]');
        $('.data_class').append('<div class="fieldset" data-group="'+next+'">'+$initial.html()+'</div>');
    });

});
</script>
<?php

if(isset($_POST['submit'])) {
    $values = $_POST['form_values'];
    echo '<pre>';
    print_r($values);
    echo '</pre>';
}

?>

0 comments:

Post a Comment