Javascript/HTML button click error - javascript

I am using JavaScript with my html page to try an get a button to show a message to the user, but when I click the button, nothing happens. Is there something I am doing wrong?
<input type="button" name="get" id="getmsg" value="Get Message"/>
<script type="text/javascript">
document.getElementById("getmsg").onclick = msgtouser;
function (msgtouser)
{
var msg = "";
var topick = "012345";
for(var i = 0; i < 8; ++i)
{
msg += topick[Math.floor((Math.random()*topick.length)+1)];
}
alert(msg);
}
</script>

That is not how you define a function
function (msgtouser)
should be
function msgtouser ()

Try on this way:
document.getElementById("getmsg").onclick = msgtouser;
function msgtouser()
{
var msg = "";
var topick = "012345";
for(var i = 0; i << 8; ++i)
{
msg += topick[Math.floor((Math.random()*topick.length)+1)];
}
alert(msg);
}
Note function msgtouser() instead function (msgtouser).

Here are some of the points which you need to correct:
function (msgtouser) should be function msgtouser ()
Use window.load or .ready() function.
My guess is you are trying to generate random number between 1 and 012345 i.e topick.length,if so then remove that outer array topick[].
Here is a working code:
window.onload=function(){
document.getElementById("getmsg").onclick = msgtouser;
function msgtouser()
{
var msg = "";
var topick = "012345";
for(var i = 0; i < 8; ++i)
{
msg += Math.floor((Math.random()*topick.length)+1);
}
alert(msg);
}
}

Related

can't access value through input using button

I'm doing some exercises and come across where I can't pass the value from the input box to a function inside a script, I don't really know what I have done wrong, I tried different things but didn't really work out. How can I make it work? I want to able to enter a number then press a button so that it prints pyramid according to given number, here is my code :
window.onload = function() {
let aantalLijnen = parseInt(document.getElementById('number').value);
document.getElementById("button").onclick = stars();
function stars() {
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
<p>Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button></p>
You're calling stars() and assigning the result to the onclick handler.
You need to pass the function itself...
document.getElementById("button").onclick = stars;
Or just create an anonymous function directly...
document.getElementById("button").onclick = function() {
...
}
As pointed out by #j08691, you are setting the value of aantalLijnen on the page load.
Instead you want to get the value at the time the function runs, so you need to move it into the function itself...
window.onload = function() {
document.getElementById("button").onclick = function () {
let aantalLijnen = parseInt(document.getElementById('number').value);
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
<p>Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button></p>
you have to get the value from input every time you click on the button
window.onload = function () {
const numberElem = document.getElementById('number');
document.getElementById("button").addEventListener('click', stars);
function stars() {
let aantalLijnen = parseInt(numberElem.value);
for (var i = 1; i <= aantalLijnen; i++) {
var row = '';
for (var j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
}
};
Besides what already said by others
Don't use onclick handlers. Stick to cumulative listeners with addEventListener
You could use String.prototype.repeat();
Defer your script or place it right before the closing </body> tag
Learn the difference between let and const
function stars() {
const num = parseInt(document.getElementById('number').value, 10);
if (num < 2 || num > 10) return console.log("Use from 2 to 10 inclusive");
const row = '*'.repeat(num);
console.log(row)
}
document.getElementById("button").addEventListener('click', stars);
Give a number betweeen 2 and 10
<input type="number" id='number'>
<button id="button">Click</button>

How not to make <br> a tag

<script>
var y="<br>"
function repeater(num){
for (var i=0;i<num;i++)
{document.write(y) }
}
document.write(repeater(4))
</script>
My goal is to make the tag appear
4 times, not the actual breaks. The result shows undefined.
Since the question is asking for Javascript solution not JQuery (since no jQuery tags), I'll add the answer using Javascript.
<script>
var y = "<br>"
function repeater(num) {
for (var i=0; i < num; i++) {
document.body.innerText += y;
}
}
repeater(4);
</script>
or maybe you need to set a text into the spesific element (<div id="app"><div>)? no problem, we can improve the code a little bit.
<script>
var y = "<br>"
function repeater(el, num) {
for (var i=0; i < num; i++) {
el.innerText += y;
}
}
var el = document.getElementById('app');
repeater(el, 4);
</script>
<script>
var res = "";
var y="<br>";
function repeater(num){
for (var i=0;i<num;i++) {
res = res + y;
}
$('#customDiv').text(res);
}
(repeater(4))
You can put a custom <div id="customDiv"></div> inside your html file.

JS, a way to have a button refresh the result and print it on the page

<script>
function makeid() {
var text = "";
var char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < l; i++) {
text += char_list.charAt(Math.floor(Math.random() * char_list.length));
}
return text;
}
console.log(makeid(8));
makeid(8);
document.write(makeid());
</script>
Hey, guys. I have this code currently in my HTML, I'm wondering how I can have the output of this code printed on the page and then refreshed everytime I click an HTML button. If you have any questions I'll try to answer them best I can.
This worked for me
<div id="content"></div>
<button id="myBtn"></button>
<script>
var btn = document.getElementById('myBtn');
var content = document.getElementById('content');
btn.onclick = function(){
function makeid(l) {
var text = "";
var char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < l; i++) {
text += char_list.charAt(Math.floor(Math.random() * char_list.length));
}
return text;
}
console.log(makeid(8));
var id = makeid(8);
content.innerHTML = id;
}
</script>
Everytime the button is clicked, your function will be triggered and the generated Id will be put inside the <div id="content"></div>
Here is the codepen for testing

How do I create different button for each item in an array / JavaScript

Here's my code:
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML = "<button>" + never[i] + "</button>";
}
}
I have a button in my HTML that invokes this function but it only creates a button for the last item (7). How can I create a different button for each one of the items in the array? Any help is appreciated.
The best way is to append created buttons in container.Each by each
var never = [1,2,3,4,7];
function please () {
var more=document.getElementById("more");
for (var i = 0; i < never.length; i++) {
var butt=document.createElement("button");
butt.innerHTML=never[i];
more.appendChild(butt);
}
}
By appending to innerHTML instead of assigning, like
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML += "<button>" + never[i] + "</button>";
}
}
please();
<div id="more">
</div>

HtmlService: google.script.run not recognizing gs function

I'm currently trying to pass an array of values from a Google Sheet to the HtmlService where I will have the user choose an option and eventually pass it back to the .gs script. I have been using these two links as references:
1. Google Documentation
2. Stack Overflow example
When running the code, I looked at my console and noticed this error:
VM3051:4 Uncaught TypeError: google.script.run.withSuccessHandler(...).getVersionArray is not a function
It appears that getVersionArray() is not being passed correctly. When removing this function from the rest of that google.script.run call, the error goes away.
Also, per link two, I tried that code with the template and never even got a window to pop up, so I have been using the HtmlOutput example from the Google documentation link as a starting point. I have also tried the code with and without the SandboxMode declaration.
gs code:
function bugPieChart() {
getVersionArray();
openDialog();
function getVersionArray() {
var ss = SpreadsheetApp.getActive();
var valuesR = ss.getSheetByName("report").getRange('R1:R').getValues();
var valuesS = ss.getSheetByName("report").getRange('S1:S').getValues();
var versionRSArray = [];
for (var i = 0; i < valuesR.length; i++) {
versionRSArray.push(valuesR[i][0]);
}
for (var i = 0; i < valuesS.length; i++) {
versionRSArray.push(valuesS[i][0]);
}
versionRSArray.sort();
var uniqueArray = [];
uniqueArray.push(versionRSArray[0]);
for (var i in versionRSArray ) {
if((uniqueArray[uniqueArray.length-1]!=versionRSArray[i]) && (versionRSArray[i] !== "")) {
uniqueArray.push(versionRSArray[i]);
}
}
return uniqueArray;
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showModalDialog(html, 'Dialog title');
var htmlOutput = html.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return htmlOutput;
}
}
index.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function() {
google.script.run.withSuccessHandler(buildOptionsList)
.getVersionArray();
});
function buildOptionsList(uniqueArray) {
var list = $('#optionList');
list.empty();
for (var i = 0; i < uniqueArray.length; i++) {
list.append('<option value="' + uniqueArray[i].toLowerCase() + '">' + uniqueArray[i] + '</option>');
}
}
</script>
</head>
<body>
<select id="optionList">
<option>Loading...</option>
</select>
<input type="button" value="Close" onclick="google.script.host.close()" />
</body>
</html>
I think your just missing a closing bracket on the function above it.
function bugPieChart() {
getVersionArray();
openDialog();
}
function getVersionArray() {
var ss = SpreadsheetApp.getActive();
var valuesR = ss.getSheetByName("report").getRange('R1:R').getValues();
var valuesS = ss.getSheetByName("report").getRange('S1:S').getValues();
var versionRSArray = [];
for (var i = 0; i < valuesR.length; i++) {
versionRSArray.push(valuesR[i][0]);
}
for (var i = 0; i < valuesS.length; i++) {
versionRSArray.push(valuesS[i][0]);
}
versionRSArray.sort();
var uniqueArray = [];
uniqueArray.push(versionRSArray[0]);
for (var i in versionRSArray ) {
if((uniqueArray[uniqueArray.length-1]!=versionRSArray[i]) && (versionRSArray[i] !== "")) {
uniqueArray.push(versionRSArray[i]);
}
}
return uniqueArray;
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showModalDialog(html, 'Dialog title');
var htmlOutput = html.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return htmlOutput;
}

Categories

Resources