Add dynamic click on checkbox and get inputName in jQuery

I have a dynamic inputone that will have checkboxto hide the inputs at the tick checkbox, at the moment I'm trying to add click="getChk()in checkbox, but this only gave me the last indexlogin name.

Say I have input ids (code, sku, id).

My dynamic insertion and verification code line

for (var x = 0; x < searchParams.length; x++) {
     var container = $('#checkBox');
     var inputs = container.find('input');
     var id = inputs.length + 1;
     var inputName = searchParams[x].name;
     $('<textarea />', { id: inputName, name: inputName, placeholder: inputName, rows: "2", class: "search-area-txt col-sm-12" }).appendTo(searchbox);
     $('<input />', { type: 'checkbox', id: 'x' + id, name: inputName }).appendTo(checkBox);
     $('<label />', { 'for': 'x' + id, text: inputName, id: inputName, name: inputName }).appendTo(checkBox);
}

But it will need to be saved in localStorage, so when updating it will keep a hidden input if it exists in localStorage.

Edit : The code below should save the name in the form localStoragein an array.

var inputNames = [];
getChk(id){
 var indexOfItem = inputNames.indexOf(name)
 if (indexOfItem >= 0) {
    inputNames.splice(indexOfItem, 1);
 } else {
    inputNames.push(name);
 }
 localStorage.setItem('chked', JSON.stringify(inputNames))
}

My attempt is to add .click(function(){})

$('<input />', { type: 'checkbox', id: 'x' + id, name: inputName }).appendTo(checkBox).click(function(){
 getChk(id); // only gives me the id name
});

HTML inputs and html checkbox enter image description here

+4
2

, click for, , id .

, , id , :

$('<input />', { type: 'checkbox', id: 'x' + id, name: inputName }).appendTo(checkBox).click(function() {
   getChk(this.id);
});

, @guest271314, localStorage - setItem(), set():

localStorage.setItem('checked', id);
+3

getChk(e){
 localStorage.set('checked', this.id);
 console.log('input id>> ', this.id);
}

.click(getChk);
0

Source: https://habr.com/ru/post/1665341/


All Articles