jeudi 1 juin 2017

Auto select and retrieving checkbox values in javascript

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 automitacly checked

I hope you guys are aible to help me ! Thanks a lot !

regards




Aucun commentaire:

Enregistrer un commentaire