1

If i have a list of checkboxes and they have the same name and different values. I want to write the value from the checkboxes i have checked in a new column in real-time. How can i do this ?

<div id="checkboxes">
<input type="checkbox" name="prod" value="Option 1" checked="checked" />Option 1
<input type="checkbox" name="prod" value="Option 2" />Option 2
<input type="checkbox" name="prod" value="Option 3" />Option 3
<input type="checkbox" name="prod" value="Option 4" checked="checked" />Option 4
</div>

Result:

Option 1
Option 4
patrikc
  • 33
  • 1
  • 5

3 Answers3

0

you can listen for click/change events on your inputs - see this : Catch checked change event of a checkbox

And then use jquery's val() function to get the value

Community
  • 1
  • 1
sooks
  • 688
  • 1
  • 8
  • 20
0

I suggest you to use jQuery. Here a live sample that can inspire you:

$("#checkboxes input").click(function () {
  $("#output").text($("#checkboxes input:checked").map(function () {
    return $(this).val();
  }).get().join());
}).click().click();

// or
// var updateOutput = function() {
//  $("#output").text($("#checkboxes input:checked").map(function () {
//    return $(this).val();
//  }).get().join());
//};
//$("#checkboxes input").click(updateOutput);
//updateOutput();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="checkboxes">
<input type="checkbox" name="prod" value="Option 1" checked="checked" />Option 1
<input type="checkbox" name="prod" value="Option 2" />Option 2
<input type="checkbox" name="prod" value="Option 3" />Option 3
<input type="checkbox" name="prod" value="Option 4" checked="checked" />Option 4
</div>
<div id="output"></div>

2 JS options :

  • double click
  • use an external function (in comment)
Nicolas Albert
  • 2,586
  • 1
  • 16
  • 16
0

var x = new Array();

$('input[name="prod"]').each(function(index){

    if($(this).is(':checked')){

        x[index] = $(this).val();

    }

});

console.log(x[0]); // gives option 1 console.log(x[1]); // gives option 4

x is an array that contains the checked value which you may use as per your wish!! :)

radiopassive
  • 556
  • 1
  • 5
  • 15