mardi 23 janvier 2018

How to dynamically get values from multiple check-boxes (jquery) and copy it to textarea?

so, there is an checkbox "Cut image" which will on select expand four more check-boxes (up, left, right, down) where you can select where image will be cut.

By default, these expanded check-boxes are selected.

What I want to achieve is:

  1. If "cut image" checkbox is selected (and by default all other expanded check-boxes) append text value "Cut image: up, left, right, down" to textarea

  2. If one of the expanded check-boxes are not selected (lets say "up"), remove it's value from appended text in textarea, and show only selected ones, "Cut image: left, right, down"

Html

<input type="checkbox" id="cut-image">
<label for="">Cut image</label>


<div id="main-group">

  <input type="checkbox" class="cut-image-up" checked>
  <label for="">up</label>

  <input type="checkbox" class="cut-image-left" checked>
  <label for="">left</label>

  <input type="checkbox" class="cut-image-right" checked>
  <label for="">right</label>

  <input type="checkbox" class="cut-image-down" checked>
  <label for="">down</label>

</div>


<textarea name="" id="checkbox-values" cols="20" rows="10"></textarea>

Javascript

$(function(){

 $('#cut-image').on('change', function(){
   $('#main-group').toggle();

   if($(this).is(':checked')){
     $('#checkbox-values').val('Cut image (up, left, right, down)');
   }else{
     $('#checkbox-values').val('');
   }

  });
})

Here is an jsfiddle also.

I would appreciate any suggestions on how to achieve this behavior.

Thanks.




Aucun commentaire:

Enregistrer un commentaire