Set up a button listener - javascript

I have a problem with buttons on my website. I have taken it from a colleague and want to change the function of the keys.
At the moment this is solved directly in HTML. That looks like this:
<table class="formButtons">
<tr>
<td>
<form method="post">
<p> <input name='"Variable".allowStart' value="1" type="hidden"> </p>
<p> <input class="Start" value="Start" type="submit"> </p>
</form>
</td>
<td>
<form method="post">
<p> <input name='"Variable".allowStart' value="0" type="hidden"> </p>
<p> <input class="Stop" value="Stop" type="submit"> </p>
</form>
</td>
</tr>
</table>
When pressing the Start or Stop button, the whole page is reloaded. I do not want that.
As you can see, my variable '"Variable".allowStart"' is called and set to value=1. Now I want to set the value of the variable to 1 in Javascript. But I do not know how. Can you help me?
And please, detailed answers, I am a total beginner in programming.
Extra information:
'"Variable".allowStart'
is a variable that I get from my Siemens PLC.
It works as shown in the example. All I have to do is add the variable as a comment in the HTML file. Like this:
<!-- AWP_In_Variable Name='"Variable".allowStart' -->

I don't understand your '"Variable".allowStart' , but if you are able to use it in your javascript then you can proceed with this answer.
To stop the Start & Stop button from reloading the page, you can prevent the default behavior of the input elements by using preventDefault() and do your desired stuff from there.
Check out the modified HTML & the javascript for this:
window.onload = function (){
var start = document.getElementById('Start');
var stop = document.getElementById('Stop');
start.onclick = function (e) {
e.preventDefault();
//add desired code here
console.log('Clicked Start');
}
stop.onclick = function (e) {
e.preventDefault();
//add desired code here
console.log('Clicked Stop');
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weird Buttons</title>
</head>
<body>
<table class="formButtons">
<tr>
<td>
<form method="post">
<p> <input name='"Variable".allowStart' value="1" type="hidden"> </p>
<p> <input id="Start" class="Start" value="Start" type="submit"> </p>
</form>
</td>
<td>
<form method="post">
<p> <input name='"Variable".allowStart' value="0" type="hidden"> </p>
<p> <input id="Stop" class="Stop" value="Stop" type="submit"> </p>
</form>
</td>
</tr>
</table>
</body>
</html>

Related

window.alert not working when a form quiz is submitted

So, I am trying to make a quiz with html/js. I searched up how to reference an ID from js but even then the js function isn't working when I click the D option and submit.
Basically, I'm trying to get a window alert once someone has pressed submit on an answer option.
What the code outputs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="missingletter.css">
<title>Missing letter</title>
</head>
<body>
<div class="images"></div>
<div class="wordToGuess"></div>
<form action="">
<p class="question">What is the missing letter?</p>
<!-- image of cat -->
<p class="cat">_ A T</p>
<input type="radio" id="c" name="cat" value="cat">
<label for="cat" class="answer options">C</label><br><br>
<input type="radio" id="m" name="mat" value="mat">
<label for="cat" class="answer options">M</label><br> <br>
<input type="radio" id="d" name="dat" value="dat">
<label for="cat" class="answer options">D</label><br> <br>
<input type="submit" value="submit">
</form>
<script>
if ($('radio').attr("d") == "submit") {
window.alert("Correct")
} else {
window.alert("try again")
}
</script>
<div class="letters"></div>
</body>
</html>
You have a multitude problems.
To use the jQuery $ function you must load the jQuery library. You can get it from its website
The selector radio does not look up an element by its ID, it looks up all <radio> elements… which don't exist in your document or in HTML. To look up an element by its ID you need $('#The_ID')
attr(...) fetches the value of the attribute with the name passed from the selected element. None of your elements have d="something".
You are running this code while the document loads, which is before the user will have had a chance to pick an option. You need to listen for the submit event (and then stop the form from submitting to the server)
Your checkboxes all have different names, so multiple of them can be selected at once
The for attribute of a <label> has to match the id of the input it is associated with.
Assuming your goal is:
WHEN the user clicks the submit button
FIND which checkbox they checked
CHECK if they picked option dat (although that is the wrong answer)
Then you need something along the lines of:
$('form').on('submit', event => {
event.preventDefault();
const choice = $('input[name="missing"]:checked').val();
if (choice === 'dat') {
alert("Correct");
} else {
alert("try again");
}
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<form action="">
<p class="question">What is the missing letter?</p>
<!-- image of cat -->
<p class="cat">_ A T</p>
<input type="radio" id="c" name="missing" value="cat">
<label for="c" class="answer options">C</label><br><br>
<input type="radio" id="m" name="missing" value="mat">
<label for="m" class="answer options">M</label><br> <br>
<input type="radio" id="d" name="missing" value="dat">
<label for="d" class="answer options">D</label><br> <br>
<input type="submit" value="submit">
</form>
You must add a submit listener to the form. From there, you can check if the value is correct to show the correct alert. When using radio button, use the same name attribute to group them.
<form id="myForm" action="">
<p class="question">What is the missing letter?</p>
<!-- image of cat -->
<p class="cat">_ A T</p>
<input type="radio" name="answer" value="cat">
<label for="cat" class="answer options">C</label><br><br>
<input type="radio" name="answer" value="mat">
<label for="cat" class="answer options">M</label><br> <br>
<input type="radio" name="answer" value="dat">
<label for="cat" class="answer options">D</label><br> <br>
<input type="submit" value="submit">
</form>
$('#myForm').on('submit', function (e) {
e.preventDefault();
if ($('#myForm input[name="answer"]:checked').val() === 'cat') {
window.alert("Correct");
} else {
window.alert("try again");
}
});
Try This
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="missingletter.css">
<title>Missing letter</title>
</head>
<body>
<div class="images"></div>
<div class="wordToGuess"></div>
<form action="" id="theform">
<p class="question">What is the missing letter?</p>
<!-- image of cat -->
<p class="cat">_ A T</p>
<input type="radio" name="option" value="cat">
<label for="cat" class="answer options">C</label><br><br>
<input type="radio" name="option" value="mat">
<label for="cat" class="answer options">M</label><br> <br>
<input type="radio" name="option" value="dat">
<label for="cat" class="answer options">D</label><br> <br>
<button type="submit" id="btn">Submit</button>
</form>
<script>
const btn = document.querySelector('#btn');
btn.onclick = function(){
const options = document.querySelectorAll('input[name="option"]');
let selectedValue;
for (const option of options) {
if (option.checked) {
selectedValue = option.value;
break;
}
}
if(selectedValue == 'cat'){
alert('Correct.')
}else{
alert('Try Again.')
}
};
</script>
<div class="letters">
</div>
</body>
</html>

How to populate an html table with Javascript form elements?

Essentially I want to display 10 lines of a table and have them update with people's names as they submit forms. So essentially I need to write the form inputs to the table cells. WHen more than 10 people fill out the form I want the table to only show 10 so it will bump one of the earlier ones. So far this is what I am trying but I don't really know how to proceed.
<html>
<h2>Change Our Lights:</h2>
<form name="leds" id="ledSend" method="get" target="_blank" action="https://agent.electricimp.com/Fk43xPMkSrWF">
Lamp Control: <input type="radio" name="led" value="0" checked>Off
<input type="radio" name="led" value="1">On<br>
How long should the Lights stay on? <input type="text" name="timer" value="10">seconds<br>
Your name? For Our Records <input id="name" type="text" name="user" placeholder="Your name here"<br>
<br>
<input type="submit" value="Update!" onclick="updateTable();return false;"/>
</form>
<script type="text/javascript">
function updateTable(){
if (!document.getElementsByTagName) return;
tabBody=document.getElementsByTagName("tbody").item(0);
row=document.createElement("tr");
cell1 = document.createElement("td");
textnode1=document.forms['leds'].elements[3].value;
cell1.appendChild(textnode1);
row.appendChild(cell1);
tabBody.appendChild(row);
}
</script>
<body>
<h1>Who has Changed Our Lights?</h1>
<table border='1' id='mytable'>
<tbody>
<tr>"This Could Be You"</tr>
</tbody>
</table>
</body>
</html>
I can't get the form elements to appear in the table at all.
Your HTML had some typos and other problems. Your JavaScript was on the right track, but overly complicated (and generally it is good practice to put all of it in the head section of the HTML). Here is a workable test-page:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Test Page</title>
<script type="text/javascript"> <!--
var tabBody, row, cell;
function updateTable(){
tabBody=document.getElementById("editable");
row=document.createElement("tr");
cell = document.createElement("td");
cell.innerHTML=document.forms['leds'].elements[3].value;
row.appendChild(cell);
if(tabBody.childNodes.length==10)
tabBody.removeChild(tabBody.childNodes[0])
tabBody.appendChild(row);
}
// -->
</script>
</head>
<body>
<h2>Change Our Lights:</h2>
<!-- <form name="leds" id="ledSend" method="get" target="_blank" action="https://agent.electricimp.com/Fk43xPMkSrWF"> -->
<form name="leds" id="ledSend" action="" onsubmit="return false;">
Lamp Control: <input type="radio" name="led" value="0" checked />Off
<input type="radio" name="led" value="1" />On<br>
How long should the Lights stay on? <input type="text" name="timer" value="10" />seconds<br>
Your name? For Our Records <input id="name" type="text" name="user" placeholder="Your name here" /><br>
<br>
<input type="submit" value="Update!" onclick="updateTable();return false;"/>
</form>
<h1>Who has Changed Our Lights?</h1>
<table border='1'>
<thead><tr><th>This Could Be You</th></tr></thead>
<tbody id="editable"></tbody>
</table>
</body>
</html>

Button not like Chrome

Hello , I have little problem with this html script :
<!DOCTYPE html>
<html>
<body>
<td>
<form name="tsform">
<p align="center">
<font face="Arial">Choisir un Pseudo :
<br>
<input type="text" name="NICKNAME"><br />
<input type="button" value="Se connecter" onClick="javascript:location.href='ts3server://ts.xxxxxxxxx.fr/?port=9987&channel=Accueil&nickname=' + tsform.NICKNAME.value">
</font>
</p>
</form>
</a>
</td>
</body>
</html>
This scipt work fine if you click , but I want click and push Enter key
I modify :
input type="button" value="Se connecter"
to
input type="submit" value="Se connecter"
And work fine only on FireFox , not work on IE and Chrome
Have you any idea ?
One I would suggest using a submit button just a lot less annoying than onClick, and have modified the form made it cleaner and easy to see (also i left your <br /> tags in but i would suggest you dont use them and use css instead)
<td>
<form name="tsform"action="ts3server://ts.xxxxxxxxx.fr/"method="get">
<input type="hidden" name="port" value="9987"><input type="hidden" name="channel" value="Accueil">
<p align="center">
<font face="Arial">Choisir un Pseudo :
<br>
<input type="text" name="NICKNAME">
<br />
<input type="submit" value="Se connecter" />
</font>
</p>
</form>
</a>
</td>
Add the action attribute to the form tag:
<form name="tsform" action="javascript:location.href='ts3server://ts.xxxxxxxxx.fr/?port=9987&channel=Accueil&nickname=' + tsform.NICKNAME.value">
Pressing enter will submit the form but since there is no action (eg. URL) the submission doesn't do anything. I would utilize the default form behaviour and add the URL to an action attribute on the form element as well as setting the method (eg. get). Then add the 2 default values (port and channel) to hidden inputs.
Also, rather than attaching an onClick event listener to the button I would use a submit button which will trigger the same form submit as pressing enter.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<td>
<form name="tsform" action="ts3server://ts.xxxxxxxxx.fr/" method="get">
<input type="hidden" name="port" value="9987">
<input type="hidden" name="channel" value="Accueil">
<p align="center">
<font face="Arial">Choisir un Pseudo :
<br>
<input type="text" name="nickname">
<br />
<input type="submit" value="Se connecter" />
</font>
</p>
</form>
</a>
</td>
</body>
</html>

HTML button onclick event

This might be a very basic question; believe me I found very hard to find the answer to this question on the internet. I have 3 HTML pages stored in my server (Tomcat locally) & i want to open these HTML pages on a button click. Any help would be highly appreciated.
Here is my code,
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Online Student Portal</title>
</head>
<body>
<form action="">
<h2>Select Your Choice..</h2>
<input type="button" value="Add Students">
<input type="button" value="Add Courses">
<input type="button" value="Student Payments">
</form>
</body>
</html>
Try this:-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Online Student Portal</title>
</head>
<body>
<form action="">
<input type="button" value="Add Students" onclick="window.location.href='Students.html';"/>
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';"/>
<input type="button" value="Student Payments" onclick="window.location.href='Payment.html';"/>
</form>
</body>
</html>
You should all know this is inline scripting and is not a good practice at all...with that said you should definitively use javascript or jQuery for this type of thing:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Online Student Portal</title>
</head>
<body>
<form action="">
<input type="button" id="myButton" value="Add"/>
</form>
</body>
</html>
JQuery
var button_my_button = "#myButton";
$(button_my_button).click(function(){
window.location.href='Students.html';
});
Javascript
//get a reference to the element
var myBtn = document.getElementById('myButton');
//add event listener
myBtn.addEventListener('click', function(event) {
window.location.href='Students.html';
});
See comments why avoid inline scripting and also why inline scripting is bad
on first button add the following.
onclick="window.location.href='Students.html';"
similarly do the rest 2 buttons.
<input type="button" value="Add Students" onclick="window.location.href='Students.html';">
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';">
<input type="button" value="Student Payments" onclick="window.location.href='Payments.html';">
Having trouble with a button onclick event in jsfiddle?
If so see Onclick event not firing on jsfiddle.net
This example will help you:
<form>
<input type="button" value="Open Window" onclick="window.open('http://www.google.com')">
</form>
You can open next page on same page by:
<input type="button" value="Open Window" onclick="window.open('http://www.google.com','_self')">
<body>
"button" value="Add Students" onclick="window.location.href='Students.html';">
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';">
<input type="button" value="Student Payments" onclick="window.location.href='Payments.html';">
</body>

unable to add new text box on onclick() using javascript and disable an element

I am not able to add a new input box after the onclick event is called and is there way to disable the select options after the input box appears? I am sorry for such a noob question but I am at the dead end here, been trying this for an hour. Please link me to a place where I can easily learn JS with examples.
<script>
function funcGet(val)
{
if(val=="Create new category")
{
var element = document.createElement("input");
element.setAttribute("type", "input");
element.setAttribute("name", "new_cat");
var foo = document.getElementById("cat");
foo.appendChild(element);
}
}
</script>
<div name="cat">
<form method="post" action="">
<input type="text" placeholder="Enter a topic name" name="word"><br/>
<select name = "category" onchange="funcGet(this.value);">
<?php
displayCat();
?>
</select>
</div>
<select name = "site_type">
<?php
displaySitetype();
?>
</select>
<input type="submit" value="Submit data">
</form>
Try changing <div name="cat"> to
<div id="cat">
.getElementById only works on IDs,
as in
document.getElementById("cat");
If you want to leave <div name="cat"> you should use .getElementsByTagName[0] instead.
As foir a a link to learn JavaScript by example, I recommend the W3Schools JavaScript Tutorial, as they let you try out code as you learn it on their website. Once you become more familiar, you can reference the Mozilla Developer Network.
Here
var foo = document.getElementById("cat"); is giving null
There is no element exist with id cat
Error is:TypeError: foo is null
Change this:
<div name="cat">
To this:
<div id="cat">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>
Untitled Document
</title>
<script>
function generateRow() {
var d=document.getElementById("div");
d.innerHTML+="<td><input type='text'<td><input type='text'<td><input type='text' name='food'name='food'name='food'name='food'>";
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<label>
<input name="food" type="text" id="food" />
</label>
<td>
<input name="food" type="text" id="food" />
</td>
<td>
<input name="food" type="text" id="food" />
</td>
<div id="div">
</div>
<td>
<input type="button" value="Add" onclick="generateRow()"/>
</td>
<td>
<label>
<input type="submit" name="Submit" value="Submit" />
</label>
</td>
</form>
</body>

Categories