While clicking the button Array append or array push inside for loop using javascript

55 views Asked by At

I have an idea for making single array value dynamically created while clicking button this is code i run on local,

function clearr()
{
      var exp ='25';  
      let btn = document.getElementById("clear");
      let val = btn.value;
      var d=0;
for($i=0; $i<=3;$i++){
  if(val=='C')
    { 
       if(d==1){
            d=d;
        }else if(d===undefined){
             d=0;
           // alert(d);
            // return false;
        }else{
            d=d;
        }
      const Vio=[];
     Vio.push(exp);
     console.log(Vio);
     d++;
    }
   }
}
1

There are 1 answers

0
fireshadow52 On

I think I understand what you're going for, and it looks like you're overthinking things. To have the button append to an array, the array needs to be defined at a global scope, not local to the function, as you have it. Furthermore, the list can't be const, as that means you cannot modify it.

For this simple case, you don't need any if conditionals. All your function needs to do is retrieve the current value of the button and push the value onto the array.

I'll whip up a snippet to demonstrate. For this, the input will come from a text field rather than a button. Clicking "Add" will call the add function, which appends the text field's value onto the array some_list. Clicking "Print" will print out the list's contents to the console.

var some_list = []

function add() {
    // Get a handle to the text field
    var element = document.getElementById("textfield")
    
    // Add the current text field's value to an array
    some_list.push(element.value)
}
<input id ="textfield" type = "text"></input>
<!-- This button will cause the value in the above text field to be added to a running list-->
<button onclick="add()">Add</button>
<br><br>
<!-- Print out the array-->
<button onclick="console.log(some_list)">Print</button>