简体   繁体   中英

get the values of all closest fields where the input checkbox is checked dynamically with serialize

I use codeigniter and jquery
By example if input#1 is checked, i have to get the value of input#menu-1
if input#2 is checked i get the value of input#menu-2 ... even if all are checked ,
what i tried :

<form id="form">
                    <h2 class="text-uppercase font-weight-light">votre choix : </h2>
                    <div class="flex-row">
                        <input type="checkbox" id="1">
                        <label for="menu-1">item 1<span class="font-weight-bold">($ 500 )</span> x
                        </label>
                        <input id="menu-1" type="number" class="min" maxlength="2" value="1">
                    </div>
                    <div class="flex-row">
                        <input type="checkbox" id="2">
                        <label for="menu-2">item 2<span class="font-weight-bold">(2500 FCFA)</span> x
                        </label>
                        <input id="menu-2" type="number" class="min" maxlength="2" value="0">
                    </div>
                    <button id="next-1" type="submit" class="btn border border-secondary p-2">COMMANDER</button>
                </form>

i have tried :

$('#next-1').click(function (e) {
        e.preventDefault();
        var form = $("#form").serialize();
        $.ajax({
            url: '<?php echo base_url("index.php/user/process") ?>'
            method: 'POST',
            data: form,
            dataType: 'json',
            success: function (reponse) {

            }
        });
    });

my controller :

public function process()
    {
        if ($this->input->is_ajax_request()) {
            $data = $this->input->post();
            echo json_encode($data);
        }
    }

but i don't get values so it doesn't work

Because you are missing name attribute in input. Try this

<input id="menu-1" type="number" class="min" maxlength="2" value="1" name="menu-1"> // check here name attribute at last.

form serialize take value from name attribute.

in your javascript

$("#form").click(function (e) {
        let form = $(this);
//for data filtering
var serializedReturn = form.find('input[name!=menu-1]').serialize(); // here menu-1 be removed.
        console.log(serializedReturn, 'value');
        e.preventDefault();
    });

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