How to make an html form start a function - javascript

I'm wondering if there is an easy way to make a form button with text input start a form that will check if the answer's correct and then proceed to tell you. Here's what I have, can you tell me what I need?
<!doctype html>
<body>
<center>
<form name="Input" action="Answer" method="get">
<input type="text" name="Input">
<input type="submit" value="submit">
</form>
<script type="text/javascript">
var A = Math.floor(Math.random()*11);
var B = Math.floor(Math.random()*11);
var C = A+B;
var Input = document.getElementById('Input');
document.write(A + "+" + B)
function Answer()
{
alert("correct!!");
}
</script>
</body>
</html>

function calculateAnswer()
{
var A = Math.floor(Math.random()*11);
var B = Math.floor(Math.random()*11);
var C = A+B;
var Input = document.getElementById('Input');
if(Input.value == C)
{
document.body.innerHTML += (A + "+" + B);
// Or another thing to do if the answer's correct
}
}
Also, attach an event listener to the submit button to make it run the function:
referenceToTheSubmitButton.addEventListener("click", calculateAnswer);
Indent as needed.
Enjoy! :D

I know you aren't using jQuery, but are you looking for something of this nature?
It can easily be changed to plain javascript. I just wanted to use bootstrap for the easy visual effect of the alerts.
The html would be something along these lines (with jQuery and bootstrap):
<div class="alert alert-danger" id="correct">Your answer is currently
<span id="type"> INCORRECT </span>
</div>
<form>
<input name="answer" id="answer">
</form>
<p>Hint: the answer is "correct"</p>
and the script would work like this:
$("#answer").keyup(function(){
if($(this).val() === "correct"){
$("#correct").removeClass("alert-danger")
.addClass("alert-success");
$("#type").text("CORRECT!")
}
else{
$("#correct").removeClass("alert-success")
.addClass("alert-danger");
$("#type").text("INCORRECT!")
}
}).keyup();
This is just a basic implementation of an input that checks for an answer. In this case, typing "correct" makes the alert green.

Related

How to remove elements from array

Thanks for viewing. I have a program that can create a list of user inputs. The program can add people & remove people (starting from the top). This program also limits inputs to 7.
When the limit is reached, the oldest input in the array gets erased, and then the new input is going to appear. Basically:
a b c d e f g
(a is the oldest, and the g is the newest)
Becomes:
b c d e f g h
However, even if the program can already add elements in the array, what I can't understand is that although my program has the pop()function to remove people, I still can't remove anyone from my list. Furthermore, the input limitations is not followed.
Is there a missing part in my code that does the problem? Thanks.
var people = [7];
function myFunction() {
var x = document.getElementById("list");
people.push(document.getElementById("input").value);
x.innerHTML = people.join('<br/>');
}
function myFunctions() {
var x = document.getElementById("list");
people.pop();
console.log(people);
}
<!DOCTYPE html>
<html>
<body>
<form>
<input id="input" type=text>
<input type=button onclick="myFunction()" value="Add" />
<input type=button onclick="myFunctions()" value="Remove" />
</form>
<div id="list">
</div>
</body>
Please, check if it was you want?
It seems you expect that vanilla javascript variables be reactive as in vue js or react js but they don't.
<!DOCTYPE html>
<html>
<style>
</style>
<script>
var people = [7];
function myFunction()
{
if(people.length === 7) // you should check the array size
return console.log("it can't add more people!");
var x = document.getElementById("list");
people.push(document.getElementById("input").value);
x.innerHTML = people.join('<br/>');
}
function myFunctions()
{
var x = document.getElementById("list");
people.pop();
x.innerHTML = people.join('<br/>'); // you should update the list
console.log(people);
}
</script>
<body>
<form>
<input id="input" type=text>
<input type=button onclick="myFunction()" value="Add"/>
<input type=button onclick="myFunctions()" value="Remove"/>
</form>
<div id="list">
</div>
</body>
I'm not sure if you remember the definition of index, but an array list of 7 is supposed to be [6], as the corresponding index to every variable in the list starts with 0 instead of 1.
Try to update your list before you go straight to console.log!

Im learning JS and i have a task to make the numbers that i input reverse and pop up in an alert

i made the script that reverses the numbers but i dont know how to make the alert pop up the result of the reversed numbers
I need help to figure this out it probably has a simple solution but i dont know
The code added to snippet is below:
function okreni () { // removed "s" parameter
var a = ' ';
// s = s.toString();
const s = document.getElementById("broj").value.toString();
for (var i = s.length - 1; i>=0; i--) {
a += s[i];
}
window.alert (a);
};
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
</body>
EDIT -
The s = s.toString() has been changed to get the information from the input-value.
alert doesn't display if there's no value to display. in your case you have to passe a value to "okreni()" function.
<button value="okreni" onclick="okreni(**value**)">Okreni</button>
Apparently, you suppose to get the input value as s in okreni(s). However, this is not possible. You have to get the value programatically from the input. Following the working code. I've also created this CodeSandbox for you to try it out:
<!DOCTYPE html>
<html>
<head>`enter code here`
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="" />
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
<script type="text/javascript">
function okreni() {
var a = " ";
let inputValue = document.querySelector("#broj").value;
const s = inputValue.toString();
for (var i = s.length - 1; i >= 0; i--) {
a += s[i];
}
window.alert(a);
}
</script>
</body>
</html>
You could also try something like this to reverse your string. In looks much cleaner in my opinion and can even be condensed to a single line if needed.
Apart from that, the reason you are getting an error is because of what alexanderdavide mentioned in his answer. To elaborate further, the okreni function does not require a parameter to be passed. Instead, within the fucntion we look for the value in the input element with the id of broj. So, when you click on the button, the function checks the string in that input, reverses it and then performs an alert.
function okreni() {
let s = document.getElementById('broj').value
s = s.split("").reverse().join("")
window.alert(s)
}
<label for="broj">Unesite Broj:</label>
<input type="text" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>

I want to join two inputs in one var at html on Wordpress

I'm using wordpress but making my own form for payments, i have two inputs of type select, like this:
<div id="S03" class="Selectos"><select tabindex="4" name="Mes" required="">
<option...[Code goes on]
And this:
<div id="S04" class="Selectos"><select tabindex="5" name="Ano" required="">
<option...[Code goes on]
Those works fine, but i want to join them in one input, i have research all day long, i found some clues about what i have to do, but in especifics no one does help me.
This is the input for the joining:
<input id="Expires" name="Expires" type="hidden" />
And the way i call the form:
<div class="container"><form id="contact" class="RV_donateForm" action="https://eps.banorte.com/secure3d/Solucion3DSecure.htm" method="post">
And how it close:
<fieldset><button id="contact-submit" name="submit" type="submit" data-submit=" ">Donar</button></fieldset>
</form></div>
Then i look for some way to joining and this one looks the better way to do it at the submit event:
<script type="text/javascript">
button.onclick = function (){
document.getElementById('Expires').value = document.getElementById('S03').value + '/' + document.getElementById('S04').value; cn = document.getElementById('Expires').value ;
alert(cn);
};
</script>
Well, at the bank 'post' they throw me all the vars ok, except for Expires that never joins and shows null, and i notice also because it never show me the alert. I'm new at html and JavaScript, and i'm not sure what could be wrong. All the code on the file are on this order for exception that the call of the form is at the beginning of everything, ¿maybe is the position on line that i have to put the javascript?
I appreciate any help. Thanks a lot stackfellas!
You may want to check this https://developer.mozilla.org/es/docs/Web/API/EventTarget/addEventListener
I guess you first need to get the button, then add the listener
<script type="text/javascript">
var button = document.getElementById('contact-submit')
button.addEventListener('click', function () {
document.getElementById('Expires').value = document.getElementById('S03').value + '/' + document.getElementById('S04').value;
cn = document.getElementById('Expires').value ;
alert(cn);
});
</script>
Finally! It does work like Omar says, but loading the addEventListener at onload body function, it will run the function that the event refers when you click on submit button.
<script type="text/javascript">
function putExpires(){
var cm = document.getElementById('S03').value;
var ca = document.getElementById('S04').value;
document.getElementById("Expires").value = cm + '/' + ca;
var cn = document.getElementById("Expires").value;
}
function load() {
var button = document.getElementById("contact-submit");
button.addEventListener("click", function(){putExpires()}, false);
}
</script>
<body onload="load();">
Thanks Omar!

Javascript output as value of hidden input

How can I set the ouput of this javascript function as the value for a hidden input on a html form?
document.write(states[i][1]);
works fine but I cannot get it to fill in the value with the code as shown below.
if (to == 'abbr'){
input = input.replace(/\w\S*/g, function(txt){return
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
for(i = 0; i < states.length; i++){
if(states[i][0] == input){
document.getElementById("sid").value = (states[i][1]);
}
}
}
}
</script>
<form action="we2.php" method="post">
<input type="text" id="sid" name="s1"/>
<input type="submit" value="Verify">
</form>
What is wrong with this code / what is the right way to do this?
Thanks!
This should do it.
HTML:
<input type="hidden" id="HiddenInput" />
JavaScript:
document.getElementById("HiddenInput").value = someFunction();
Have you checked if states[i][0] == input evaluates to true?
Write JavaScript code after html code end in your page or at the end of page.
I found a easier solution by just turning the entire function into a variable then the variable into the DOM:
var response = abbrState('<?php echo $_GET['state']; ?>', 'abbr');
document.getElementById("sid").value = response;
The following should work.
HTML:
<div style="display:none" id="example"></div>
Javascript:
function addTextNode(text) {
var newtext = document.createTextNode(text),
element = document.getElementById('example');
element.appendChild(newtext);
}
function yourFunctionDataHere(){
return 'test1234';
}
addTextNode(yourFunctionDataHere());
Just make sure, that the return type of your function is of type string. If you want to see the output simply remove the style="display:none" from the div in the above example.
Try it online on jsfiddle.

Javascript getElementByID from form input

I am providing a form where the user shall enter an arithmetic calculation. Further down the result shall appear, once the user hits enter. It might just be a problem of syntax, but I couldn't find the mistake. Here is what I did so far:
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post"><span>Type here:</span><input type="text" id="calc"></input>
</form>
<script>
num_field = document.getElementById("calc");
num_field.onsubmit=function ()
{
document.getElementById("display_result").innerHTML = num_field;
}
</script>
<p id="display_result"></p>
</body>
</html>
So, the user shall enter for instance "1+2". The result shall appear below.
Any idea where is my mistake?
Best regards
Here is how you can achieve that.
eval is the best way for doing that but eval is risky to use so make sure to sanitize the value of input before using eval.
I am using this regex /(^[-+/*0-9]+)/g to extract only numbers and few operators (-+/*) and doing eval on that value.
remove the <form> that is not required use keypress event listener and check for enter key. keycode of enter key is 13
num_field = document.getElementById("calc");
num_field.onkeypress = function(e) {
if(e.which==13)
{
var value = num_field.value.match(/(^[-+/*0-9]+)/g);
if(!value) return;
else value = value[0];
var res = eval(value);
document.getElementById("display_result").innerText = res;
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calc" />
<p id="display_result"></p>
You were nearly there, your code just needed a bit of tweaking - see below (comments in code as what I have done and why)
The following seems to be an alternate and safer way to do this without using eval (function taken from the second answer in this post):
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post" id="form">
<span>Type here:</span>
<input type="text" id="calc"> <!-- inputs are self closing no need for closing tag -->
<input type="submit" value="submit"> <!-- added a submit button -->
</form>
<script>
form = document.getElementById("form");
num_field = document.getElementById("calc");
form.onsubmit = function() { // attach this event to the form
document.getElementById("display_result").innerHTML = evalAlternate(num_field.value); // add .value here to get the value of the textbox
return false; // return false so form is not actually submitted and you stay on same page (otherwise your display result will not be updated as the page is reloaded
}
function evalAlternate(fn) { // function safer alternate to eval taken from here: https://stackoverflow.com/questions/6479236/calculate-string-value-in-javascript-not-using-eval
fn = fn.replace(/ /g, "");
fn = fn.replace(/(\d+)\^(\d+)/g, "Math.pow($1, $2)");
return new Function('return ' + fn)();
}
</script>
<p id="display_result"></p>
</body>
</html>
see the below fiddle
https://jsfiddle.net/ponmudi/13y9edve/
num_field = document.getElementById("calc");
num_field.onkeydown = (event) => {
if (event.keyCode === 13) {
document.getElementById("display_result").innerHTML = eval(num_field.value);
return false;
}
}
This should work:
calc = document.getElementById("calc");
formula = document.getElementById("formula");
calc.addEventListener('click', function() {
document.getElementById("display_result").innerHTML = eval(formula.value);
});
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="formula" />
<button id="calc" type="submit">calc</button>
<p id="display_result"></p>
eval() JavaScript Method
Try this:
var calculation_input = document.getElementById('calculation_input');
calculation_input.onkeydown = function(event) {
if (event.keyCode == 13) { // Enter key.
// Sanitize before using eval()
var calculation = calculation_input.value.replace(/[^-()\d/*+.]/g, '');
document.getElementById("display_result").innerHTML = eval(calculation);
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calculation_input" />
<p id="display_result"></p>
You don't need to submit the calculation in a form, you can just use native javascript to calculate the result. And don't forget to always sanitize before using eval :)

Categories