0

I met some difficulties to code a function. I generated some checkboxes in JavaScript.

I would like to auto select the element in the array target[] "March" and "September" and make them appear in the text area. So "March" and "September" appear checked and appear in the textarea.

But I also want to be able to edit the text area by selecting some other options. So if I check "January" and didn't touch to "March" and "September" they appear checked and aprear in the text area.

I really need it in JavaScript with no jQuery.

//array of options
var array = new Array();
array[0] = "January";
array[1] = "February";
array[2] = "March";
array[3] = "April";
array[4] = "May";
array[5] = "Juny";
array[6] = "July";
array[7] = "August";
array[8] = "September";
array[9] = "October";
array[10] = "November";
array[11] = "December";

// values to of checkboxes I want to auto-check
var target = new Array();
target[0] = "March";
target[1] = "September";


var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";

// the loop is creating the checkboxes with name, value...
for (var i in array) {
  //Name of checkboxes are their number so I convert the i into a string. 
  j = i.toString();

  val = j;
  //cap will be the value/text of array[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = array[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
}
* {
  box-sizing: border-box;
}

#data {
  padding: 5px;
  width: 100vw;
}

.multiselect {
  overflow: visible;
  padding: 0;
  padding-left: 1px;
  border: none;
  background-color: #eee;
  width: 100vw;
  white-space: normal;
  height: 50px;
}

.checkboxes {
  height: 100px;
  width: 100px;
  border: 1px solid #000;
  background-color: white;
  margin-left: -1px;
  display: inline-block;
}

label {
  display: inline-block;
  border: 1px grey solid;
  padding: 5px;
}
<form>
  <div id="data">
    <div class="multiselect">
      <div id="c_b">
        <div id="checkboxes">
        </div>
      </div>
    </div>
  </div>
</form>

<textarea id="t"></textarea> March and September have to be automatically checked

2 Answers 2

1

Auto select could be achieved in many ways, like using el.click(). Then you need to loop & see if el is 'checked - I've provided both basic example described in your question & more usable example with .checked.

//array of options
var array = new Array();
array[0]="January";
array[1]="February";
array[2]="March";
array[3]="April";
array[4]="May";
array[5]="Juny";
array[6]="July";
array[7]="August";
array[8]="September";
array[9]="October";
array[10]="November";
array[11]="December";

// values to of checkboxes I want to auto-check
var target = new Array();
target[0]="March";
target[1]="September";


var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in array) {
    //Name of checkboxes are their number so I convert the i into a string. 
	j = i.toString();

	val = j;
	//cap will be the value/text of array[i]
	var cb = document.createElement('input');
	var label= document.createElement("label");

	cap = array[i];
	var text = document.createTextNode(cap);
	cb.type = 'checkbox';
	cbh.appendChild(cb);
	cb.name = cap;
	cb.value = val;
	label.appendChild(cb); 
	label.appendChild(text);
	cbh.appendChild(label);
  cb.addEventListener('click',e=>{
    if (e.target.value) t.value += e.target.name
  })
  //alternate version:
  //cb.addEventListener('click',updateText)
}

//function updateText(){
//  t.value = [null,...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s,el)=>el&&el.checked?s=(s||'')+el.name:s||'')
//}

document.querySelector('[name="March"]').click()
document.querySelector('[name="September"]').click()
* {
box-sizing: border-box;
}
#data {
    padding:5px;
    width:100vw;
}
.multiselect {
    overflow: visible;
    padding:0;
    padding-left:1px;
    border:none;
    background-color:#eee;
    width:100vw;
    white-space: normal;
    height:50px;
}
.checkboxes {
    height:100px;
    width:100px;
    border:1px solid #000;
    background-color:white;
    margin-left:-1px;
    display:inline-block;
}
      
label {
    display: inline-block;
    border: 1px grey solid;
    padding:5px;
 }
<form>
	<div id="data">
		<div class="multiselect">
			<div id="c_b">
				<div id="checkboxes">
				</div>
			</div>
		</div>
	</div>
</form>

<textarea id="t"></textarea>

March and September have to be automitacly checked

Explanation of

[null,...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s,el)=>el&&el.checked?s=(s||'')+el.name:s||'')

First, we're taking all checkboxes within id with "querySelectorAll('#checkboxes [type="checkbox"]')"

Next, prepend "..." to treat Node list as Array while forming new array with [ ] (also, adding "null" at index 0 for easier code later)

Then, .reduce( ) to output string, looping each element of array, providing 2 arguments - s - same variable, passed between elements, adding strings to it, and el - each element from array (inpyt checkbox element).

It's es6, so arguments for reduce callback comes before "=>", ald after "=>" there's auto-returned expression.

Inside this expression, there's "if" shorthand - if el is .checked we're adding el.name to "s" (or empty string if we're just beginning), and if el isn't checked - we're just passing "s"(or empty string) further down the loop

Example based on watching target[] changes:

//array of options
var array = new Array();
array[0]="January";
array[1]="February";
array[2]="March";
array[3]="April";
array[4]="May";
array[5]="Juny";
array[6]="July";
array[7]="August";
array[8]="September";
array[9]="October";
array[10]="November";
array[11]="December";

var arrayChangeHandler = {
  get: function(target, property) {
    return target[property];
  },
  set: function(target, property, value, receiver) {
    target[property] = value;
    array.forEach(n=>(target.includes(n) != document.querySelector('[name="'+n+'"]').checked) ? document.querySelector('[name="'+n+'"]').click() : null)
    return true;
  }
};

var target = new Proxy([], arrayChangeHandler);



var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in array) {
    //Name of checkboxes are their number so I convert the i into a string. 
	j = i.toString();

	val = j;
	//cap will be the value/text of array[i]
	var cb = document.createElement('input');
	var label= document.createElement("label");

	cap = array[i];
	var text = document.createTextNode(cap);
	cb.type = 'checkbox';
	cbh.appendChild(cb);
	cb.name = cap;
	cb.value = val;
	label.appendChild(cb); 
	label.appendChild(text);
	cbh.appendChild(label);
  cb.addEventListener('click',updateText)
}

function updateText(){
  t.value = [null,...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s,el)=>el&&el.checked?s=(s||'')+el.name:s||'')
}

//document.querySelector('[name="March"]').click()
//document.querySelector('[name="September"]').click()
target[0]="March";
target[1]="September";
* {
box-sizing: border-box;
}
#data {
    padding:5px;
    width:100vw;
}
.multiselect {
    overflow: visible;
    padding:0;
    padding-left:1px;
    border:none;
    background-color:#eee;
    width:100vw;
    white-space: normal;
    height:50px;
}
.checkboxes {
    height:100px;
    width:100px;
    border:1px solid #000;
    background-color:white;
    margin-left:-1px;
    display:inline-block;
}
      
label {
    display: inline-block;
    border: 1px grey solid;
    padding:5px;
 }
<form>
	<div id="data">
		<div class="multiselect">
			<div id="c_b">
				<div id="checkboxes">
				</div>
			</div>
		</div>
	</div>
</form>

<textarea id="t"></textarea>

March and September have to be automitacly checked

This example uses kinda new technogy - proxy, so it might not be 100% reliable, and won't work in older browsers, but i guess it's best bet without reactive framework.

Sign up to request clarification or add additional context in comments.

11 Comments

Hi, thank you for your answer. I got a problem with your code. If you click 5 times on the same options, the text area will make appear 5 time the same one.
Yup, so uncomment commented code & comment first "cb.addEventListener('click',e=>{...." and it'll refresh textarea after each click, preventing duplicates
Waow, thank you very much ! Is it possible for ou to explain or edit your post with comments to explain your function updateText() ? I don't clearly understand all you did. It would also helpful for the one after me who will see the answer. TY
Sure, hope it's explained now :)
Thank you. I realized that you write the values ​​to be automatically selected (March and April). I would like that if I change the values ​​of the table, the values ​​of the table target [], the values ​​are automatically selected. It will be perfect.
|
0

You can set checkbox to checked like this,

cb.checked = true;

When you iterate through the array check for your desired values and set checked to true.

1 Comment

I know but I would like to retrieve from the array target[] the values of array[] and make them appear in the text area. So when I click, the texte area display the value of the checkbox selected. But also the options automaticly selected by the array target[]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.