Home > database >  My aim is to get a button,when clicked the button the table to should be displayed,but the data is d
My aim is to get a button,when clicked the button the table to should be displayed,but the data is d

Time:09-29

Taking a JSON data and displaying it in a table. The code below is just a skeleton structure, but the button I am creating does nothing even though, I am trying to add an event to the button(click) which will display the table according to the function tablechange().The table is already displayed before I click the button. Kindly help.

var  request= new XMLHttpRequest();
request.open('GET','https://raw.githubusercontent.com/Rajavasanthan/jsondata/master/pagenation.json',true);

request.send();

request.onload=function(){
var data=JSON.parse(request.response);
console.log(data);

var table=document.createElement('table');
table.setAttribute('class','table');
var thead=document.createElement('thead');
thead.setAttribute('class','thead-dark')
var tr=document.createElement('tr');
var tbody=document.createElement('tbody');


var th1=document.createElement('th')
th1.innerHTML='id'
var th2=document.createElement('th');
th2.innerHTML='Name'
var th3=document.createElement('th');
th3.innerHTML='Email';

tr.append(th1,th2,th3);
thead.append(tr);
table.append(thead);


var divis=document.createElement('div');
divis.setAttribute('style','padding:20px');
var button=document.createElement('button');
button.innerHTML="click me";
button.addEventListener('click',tablechange(3));
divis.append(button);
document.body.append(divis);

function tablechange(i=1){
    for(let x=i*5;x<((i 1)*5);x  ){
        let k=data[x];
       
    var td1=document.createElement('td');
    var td2=document.createElement('td');
    var td3=document.createElement('td');
    td1.innerHTML=k.id
    td2.innerHTML=k.name;
    td3.innerHTML=k.email;
    var tr=document.createElement('tr');
    if(x%2===0) tr.setAttribute('style','background-color:#d3d3d3');
    tr.append(td1,td2,td3);
    tbody.append(tr);
    table.append(tbody);

document.body.append(table);
}
}
}
 

CodePudding user response:

By button.addEventListener('click',tablechange(3)); you are calling function tablechange(3) right away

addEventListener should be

button.addEventListener("click", tablechange.bind(null,3), false);

CodePudding user response:

You're calling your function tablchange(3) upon initialization because you have the () call parentheses. In order for it to call only when clicked, it should read

button.addEventListener('click',tablechange)

Of course you can't pass an argument like this, so you'll need to set the argument to variable that your function can access.

  • Related