NellyCeleste
NellyCeleste

Reputation: 43

Display all selected items from checkboxes

I am using this codepen as a basis.

HTML

<form>
  <div>
    <input type="radio" name="fruit" value="orange" id="orange">
    <label for="orange">orange</label>
  </div>
  <div>
    <input type="radio" name="fruit" value="apple" id="apple">
    <label for="apple">apple</label>
  </div>
  <div>
    <input type="radio" name="fruit" value="banana" id="banana">
    <label for="banana">banana</label>
  </div>
  <div id="log"></div>
</form>

jQuery

$("input").on("click", function() {
  $("#log").html($("input:checked").val() + "");
});

I have changed the radio buttons to checkboxes - but I would like to alter the js so that every selected item is then shown at the bottom of the list, rather than just the first.

The purpose is for a self awareness exercise - i.e. the user could select all statements which apply to them from a long list, and then they get an output that narrows it down to just the ones they've chosen. The form response doesn't need to be saved/submitted anywhere.

How can this be done?

Upvotes: 2

Views: 787

Answers (7)

user3589620
user3589620

Reputation:

Plain JavaScript solutions:

With one loop:

var form = document.getElementById("myForm"),
  checkboxes = form.querySelectorAll("input[type=checkbox]"),
  checked = document.getElementById("checked"),
  res = new Array(checkboxes.length);

function checkChecked() {
  [].forEach.call(checkboxes, (checkbox, i) => {
    checkbox.addEventListener("change", function() {
      checkbox.checked ? res[i] = checkbox.value : res[i] = "";
      checked.innerHTML = res.join(",").replace(/(^[,]+)|([,]+$)/g, "").replace(/(,){2,}/g, ",");
    })
  })
}

checkChecked();
<form id="myForm">
  <div>
    <input type="checkbox" name="fruit" value="orange" id="orange">
    <label for="orange">orange</label>
  </div>
  <div>
    <input type="checkbox" name="fruit" value="peach" id="orange">
    <label for="orange">peach</label>
  </div>
  <div>
    <input type="checkbox" name="fruit" value="apple" id="apple">
    <label for="apple">apple</label>
  </div>
  <div>
    <input type="checkbox" name="fruit" value="banana" id="banana">
    <label for="banana">banana</label>
  </div>
  <div id="log"></div>
</form>
<div id="checked"></div>

With two loops:

var form = document.getElementById("myForm"),
  checkboxes = form.querySelectorAll("input[type=checkbox]"),
  checked = document.getElementById("checked");

function getResult() {
  var res = "";
  [].forEach.call(checkboxes, checkbox => {
    checkbox.checked ? res += checkbox.value + "," : false
  })
  res = res.replace(/(,$)/, "");
  return res;
}

function checkChecked() {
  [].forEach.call(checkboxes, checkbox => {
    checkbox.addEventListener("change", function() {
      checked.innerHTML = getResult();
    })
  })
}

checkChecked();
<form id="myForm">
  <div>
    <input type="checkbox" name="fruit" value="orange" id="orange">
    <label for="orange">orange</label>
  </div>
  <div>
    <input type="checkbox" name="fruit" value="peach" id="orange">
    <label for="orange">peach</label>
  </div>
  <div>
    <input type="checkbox" name="fruit" value="apple" id="apple">
    <label for="apple">apple</label>
  </div>
  <div>
    <input type="checkbox" name="fruit" value="banana" id="banana">
    <label for="banana">banana</label>
  </div>
  <div id="log"></div>
</form>
<div id="checked"></div>

Upvotes: 0

nazmul.3026
nazmul.3026

Reputation: 1008

   function add(element)
{
var fruits=document.getElementById("log").innerHTML;
var fruit=element.value;
if(fruits=="")
{
document.getElementById("log").innerHTML = fruit.toString();
}
else
{
if(document.getElementById(element.id).checked == true)
{
 fruits= fruits+' '+fruit.toString();
}
else
{
 fruits = fruits.replace(element.value,'');
}
document.getElementById("log").innerHTML=fruits;    
}    
}
    <form>
  <div>
    <input type="checkbox"  value="orange"  id="orange" onclick="add(this);">
    <label for="orange">orange</label>
  </div>
  <div>
    <input type="checkbox"  value="apple" id="apple" onclick="add(this);">
    <label for="apple">apple</label>
  </div>
  <div>
    <input type="checkbox"  value="banana" id="banana" onclick="add(this);">
    <label for="banana">banana</label>
  </div>
  <div id="log"></div>
</form>

Upvotes: 0

Rahul Rana
Rahul Rana

Reputation: 455

$( "input" ).on( "click", function(e) {
 if(e.currentTarget.checked){
  var div = document.createElement("p");
  div.id=e.target.value+"1";
   div.innerHTML=e.target.value;
  var tar=document.getElementById("log");
  tar.appendChild(div);
} else {
  var tag = document.getElementById(e.target.value+"1");
  tag.parentNode.removeChild(tag);

 }  
});

You can try this its working. Now when you click orange displayed and unchecked removed.

Upvotes: 1

Gohchi
Gohchi

Reputation: 469

Now you have an array. So, maybe you need something like this?

$( "input" ).on( "click", function() {
  var selectedItems = $( "input:checked" );
  var results = "";
  for(var i = 0; i < selectedItems.length; i++){
    if(i > 0) results += ", ";
    results += selectedItems[i].value;
  }
  $( "#log" ).html( results );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div>
    <input type="checkbox" name="fruit" value="orange" id="orange">
    <label for="orange">orange</label>
  </div>
  <div>
    <input type="checkbox" name="fruit" value="apple" id="apple">
    <label for="apple">apple</label>
  </div>
  <div>
    <input type="checkbox" name="fruit" value="banana" id="banana">
    <label for="banana">banana</label>
  </div>
  <div id="log"></div>
</form>

Upvotes: 0

mngkvn
mngkvn

Reputation: 116

$( ":checkbox" ).on('change',function(){
    var li_id = 'li_'+$(this).attr('id');
  if(this.checked){
     $('#list').append("<li id="+li_id+">"+$(this).val()+"</li>") 
  }else{
     $('#'+li_id).remove();
  }
})

<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>

<ul id='list'>
</ul>

This is just a simple example to add and remove items from the list if they're checked or not. At least it gives you an idea on how you can achieve it.

Upvotes: 0

Dave Thieben
Dave Thieben

Reputation: 5427

a lot of jQuery function like .val() are designed to operate on a single element, i.e., $("input#first-name").val(), and so only return the value for the first element matched if there are multiple matches.

you will probably need a loop to extract a value for each element. fortunately, jQuery provides a function to do this as well.

$( "input" ).on( "click", function() {

    var html = "";
    $( "input:checked" ).each(function() {
         // "this" in this context is the jQuery element in this position in the list
         html += $(this).val() + "";
    }
    $( "#log" ).html(html);

});

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68413

You need to make a couple of changes

  • If want to be able to select multiple radio buttons, then either keep their names different or use checkboxes.

  • Maintain an attribute wasChecked to toggle the checked property.

  • You need to iterate the checked boxes and then get their values.

Demo

$("input").on("click", function(e) {
  var val = [];
  var wasChecked = $(this).attr( "wasChecked" ) == "true";
  if ( wasChecked )
  {
     $(this).prop( "checked", false );
  }
  else
  {
     $(this).prop( "checked", true );
  }
  $(this).attr( "wasChecked", $(this).prop( "checked") );
  $("input:checked").each( function(){
     val.push( $(this).val() );
  });
  $("#log").html( val.join( "," ));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div>
    <input type="radio" name="fruit1" value="orange" id="orange">
    <label for="orange">orange</label>
  </div>
  <div>
    <input type="radio" name="fruit2" value="apple" id="apple">
    <label for="apple">apple</label>
  </div>
  <div>
    <input type="radio" name="fruit3" value="banana" id="banana">
    <label for="banana">banana</label>
  </div>
  <div id="log"></div>
</form>

Upvotes: 0

Related Questions