Home > Mobile >  Problem when linking onclick button with a simple JS function
Problem when linking onclick button with a simple JS function

Time:10-11

I've been trying to apply some HTML/CSS functionality to the simple JS code you see below, which consists of returning a random sentence based on two arrays.

I would like to create a simple onclick button showing the sentences generated but I still can't get it to work. Do you have any ideas or clues? I've managed to get it done with variables/text but I have some issues when it comes to accessing the function, which is of course the point of the program.

Thank you all in advance for the help.

JS:

const personArr = ["Father Burgundy", "Constable Grey"];
const locationArr = ["the sauna", "the larder"];

const selectArr = (array) => {
 return(array[Math.floor(Math.random()*array.length)]);
}

const createMessage = () => {
 const message = "It was "   selectArr(personArr)   " in "   selectArr(locationArr)"!";
 return message;
};

const init = () => {
 const message = createMessage();
 console.log(message);
};

init();

----------------------------

function demo() {
 document.getElementById("output").innerHTML = init();
}

HTML:

<button id="btn" onclick="demo()">Click here!</button>
<p id="output"></p>

CodePudding user response:

Return the message in init() and add before the last string i createMessage()

const personArr = ["Father Burgundy", "Constable Grey"];
const locationArr = ["the sauna", "the larder"];

const selectArr = (array) => {
 return(array[Math.floor(Math.random()*array.length)]);
}

const createMessage = () => {
 const message = "It was "   selectArr(personArr)   " in "   selectArr(locationArr)   "!";
 return message;
};

const init = () => {
 const message = createMessage();
 console.log(message);
  return message;
};

function demo() {
 document.getElementById("output").innerHTML = init();
}
<button id="btn" onclick="demo()">Click here!</button>
<p id="output"></p>

CodePudding user response:

You just need to return value from the init() function, so here is a working jsfiddle.

https://jsfiddle.net/vuks89/2cy1fbkd/

const init = () => {
 const message = createMessage();
 console.log(message);
 return message;
};

Also, I'm not sure why you need a call to init(); after its definition. If it's just for this use case, it's likely unnecessary, because it will be called once button has been clicked.

  • Related