samedi 30 juin 2018

(JAVASCRIPT) Pass Value of multiple selected checkboxes into multiple corresponding input fields

I have a code like so;

<label><input type="checkbox" />A</label><br />
<label><input type="checkbox" />B</label><br />
<label><input type="checkbox" />C</label><br />
<label><input type="checkbox" />D</label><br />

<input name="selected_1" />
<input name="selected_2" />
<input name="selected_3" />

$(function() {
    $('input').on('click', function() {
        var values = [];
        $('input:checked').each(function() {
            values.push($(this).parent().text());
        });
        $('[name="selected_1"]').attr({value: values.join(', ')});
    });
});

The code above accurately passes the value of all selected checkboxes (comma-separated) to the input field [selected_1].

However, I want to pass the value of any of the selected checkbox into [name="selected_1"], the second selected checkbox value into [name="selected_2"] and the third selected checkbox to [name="selected_3"] in no given order. Then I want to limit the selection to a maximum of only three check-boxes selected in the form.

This fiddle Limit Checkbox Selection Demonstrates how limiting the selection is achieved.

Now, how do I pass the value of each checkbox selected into the corresponding input field using Javascript or JQuery 3.3.1?

Any help will be greatly appreciated.




Aucun commentaire:

Enregistrer un commentaire