简体   繁体   中英

Activate javascript function with parameter after button click

 function changeForms(data){ document.getElementById("firstname").value = data.firstName; document.getElementById("lastname").value = data.lastName; document.getElementById("email").value = data.emailAddress; } 

I want to call this function with this button:

 <button class="button" id="autofill" onclick="">Fill</button> 

My problem is, that the parameter data is from another function, but i dont want to call the changeForms function after the function getData like below:

 function getData(data) { data= data.values[0]; changeForms(data); } 

I want to start the function changeForms after the click, but with the data from getData. Is it possible to stop a function until a buttonclick or maybe store the data somewhere?

Thanks in advance

Marcel

first suggestion don't do inline javascript, this looks ugly, hard to maintain and not that flexible.

I suggest:

add to your button an id, like "buttonWithId" then write following javascript code:

var myButton = document.getElementById("buttonWithId");
myButton.addEventListener("click", function() {
   // your code goes here....
});

here some docu on this:

https://www.w3schools.com/jsref/met_element_addeventlistener.asp

then you allway can use the return value of your `getData``

var getData = function() {
    return someData;
}

then the call looks like this:

var someData = getData();
changeForms(someData);

put this inside the empty function defined earlier.

Note: if your function getData is async, you have to use a callback function or a promise (my personal favorite choice).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM