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 :)
Related
This is a form I have:
<h1>Word game!</h1>
<form id="joke-form">
<label>
Unscramble these letters to form a word:<Br>
<span class="scrambled">REYJUQ</span>
<br>
<input type="text" id = "userinput" size="10">
</label>
<button type="submit">Check</button>
</form>
And here is a jquery function I am running on it. My problem is that I don't know how to get the value that the user inputs in the textbox when they press submit. I am relatively new to jquery but have had no luck in researching this topic, including reading similar questions on this site.
<script>
$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('this input: first').val();
console.log(words);
});
if (words === "ANSWER") {
$('#result').text("You have the right answer");
}
else {
$('#result').text("Guess again!");
}
</script>
You have the code in the wrong place, and the selector you are using is incorrect for the input.
See this codepen on how this could work:
http://codepen.io/KempfCreative/pen/JGRzwm
$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('#joke-form #userinput').val();
console.log(words);
if (words === "ANSWER") {
$('#result').text("You have the right answer");
}
else {
$('#result').text("Guess again!");
}
});
Try:
var words = $('#userinput').val();
Your selector $('this input: first') is malformed. Since your input element has an id anyway, I would just select it by id instead. Also you will need to put your if else statement inside the submit function.
Here is a Live Demo of your code working in action:
$('#joke-form').on('submit', function(event) {
event.preventDefault();
var words = $('#userinput').val();
console.log(words);
if (words === "JQUERY") {
$('#result').text("You have the right answer");
} else {
$('#result').text("Guess again!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Word game!</h1>
<form id="joke-form">
<label>
Unscramble these letters to form a word:
<Br>
<span class="scrambled">REYJUQ</span>
<br>
<input type="text" id="userinput" size="10">
</label>
<button type="submit">Check</button>
</form>
<span id="result"></span>
JSFiddle Version: https://jsfiddle.net/6pd5z9kv/1/
I see many anwsers already but here is what you've done wrong
your code
var words = $('this input: first').val();
fixed
var words = $(this).find("input:first").val();
//use 'this' seprately, then you start input:first with " and finished with '
hopefully it will work for you, and about html I dont know if its copy/pase issue but remove blank space with id and =
your code
id = "userinput"
fixed
id="userinput"
Rest is just fine :)
Cheers
So to give a little bit of detail, I'm trying to make an interactive fiction game or text adventure. I have a form where all the "commands" for the game will be typed. I'm working on the first command which is the string "start" to call a prompt. Just to test the code, I have the prompt say "success!" when done correctly. What's happening though, is as soon as I open the web browser to test, the prompt triggers before I even type a command. Here's the code.
<html>
<head>
<script type="text/javascript" src="scripts/engine.js"></script>
</head>
<body>
<form id="testForm"> <input type="text" name="">
</form>
</body>
</html>
And then here's the javascript.
var input = document.getElementById("testForm");
if (input = "start") {
prompt("Success!");
}
Try this:
<html>
<head>
<script type="text/javascript" src="scripts/engine.js"></script>
</head>
<body>
<form id="testForm">
<input type="text" id="myInput">
</form>
<script>
var myForm = document.getElementById("testForm");// get the form element.
var myInput = document.getElementById("myInput");// get the input element
myForm.onsubmit = function() { // when the form is submitted, execute this function.
if (myInput.value == "start") { // if the value of the input equals 'start', show prompt.
prompt("Success!");
}
return false; //return false, so the form doesn't get submitted.
};
</script>
</body>
</html>
Edit:
Added submit event handler, that returns false, so the form does not get submitted.
You need to check the value of the input like so
var input = document.getElementById("inputID");
var value = input.value;
The code will always be ran straight away because it has no event handler. You could add a button which triggers it
document.getElementById('button').addEventListener('click', function () {
var input = document.getElementById("inputID");
if (input.value === 'start') {
// Do something
}
});
Or if you prefer on the forms submit event:
document.getElementById('testForm').addEventListener('submit', function () {
var input = document.getElementById("inputID");
if (input.value === 'start') {
// Do something
}
});
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.
<html>
<head>
</head>
<body>
<form class="form-horizontal cmxform" id="validateForm" method="get" action="../../course_controller" autocomplete="off">
<input type="text" id="course_name" name="course_name" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:validate_course_name();">
<label id="course_name_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<button type="submit" name="user_action" value="add" class="btn btn-primary" onClick="javaScript:validate();" >Save</button>
<button type="reset" class="btn btn-secondary">Cancel</button>
</form>
<script type="text/javascript">
/**** Specific JS for this page ****/
//Validation things
function validate_course_name(){
var TCode = document.getElementById('course_name').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
course_name_info.innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
course_name_info.innerHTML=" ";
return true;
}
}
function validate(){
validate_course_name();
}
</script>
</body>
</html>
So this the code ...I am applying alpha numeric validation on one field but even if i give invalid input like some other characters the form is getting submitted where am i doing it wrong?
i am very new to this web so any help will be appreciated:)
There are several issues here. First, you are never returning the result, so even if the function results in false, it is not returned to the form so the form goes on its merry way. To fix, you can add an onsubmit to the form tag, or even better attach an onsubmit event to the form.
onsubmit="return validate();"
Second, you only need the one function, calling a function from another function is not necessary here, and results in an additional level of difficulty since you will need to return the result to the wrapper function, which will then need to return that result to the form.
//Validation things
function validate() {
var TCode = document.getElementById('course_name').value;
if (/[^a-zA-Z1-9 _-]/.test(TCode)) {
course_name_info.innerHTML = "Please Enter Only Alphanumeric or _,-,' ' ";
return false;
} else {
course_name_info.innerHTML = " ";
return true;
}
}
Here is a working fiddle of your example: http://jsfiddle.net/duffmaster33/nCKhH/
Your validate() function should return the result of the validation. Currently the result of validate_course_name is discarded. In other words, it should look something like this
function validate(){
return validate_course_name();
}
Also you might want to move the validation to
<form onsubmit="return validate()" ...
You need to wrap course_name_info with a getElementById
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
and then change the style of the label so the font isn't white on white background.
Hope that fixes it.
I have a textarea, which will handle output, and a textfield which will handle user input.
Focus will be entirely on the input field.
I can't make it so that the user input field will add text when the form is submitted (enter key is pressed). It will only work if there is a button and this is clicked. How do I solve this issue?
Below is the code i'm trying for the enter key submit.
<html>
<head>
<script type="text/javascript">
function addtxt(input) {
var obj=document.getElementById(input)
var txt=document.createTextNode("blah blah")
obj.appendChild(txt)
}
</script>
</head>
<body>
<textarea id="textarea1"></textarea>
<br><input type="text" onSubmit="addtxt('textarea1');">
</body>
</html>
This will do the job. Also, you should deal with the value property of the textarea rather than appending text nodes to it: if the user changes the textarea's value at all, changing its child nodes afterwards will have no effect. If you want the textarea to be read-only, add a readonly attribute: <textarea id="textarea1" readonly></textarea>.
<script type="text/javascript">
function inputKeyDown(evt, input) {
if (evt.keyCode == 13) {
var textarea = document.getElementById("textarea1");
textarea.value += "\n" + input.value;
input.value = ""; // I'm guessing you may want this
return false;
}
}
</script>
<input type="text" onkeydown="return inputKeyDown(event, this);">
Instead of submit, try using the keypress event. Detect when the enter key is pressed, copy the data, and cancel the event (to prevent form submission). If you allow the form to submit, it will simply replace the existing page with the result of the form post.
Modifying your current code:
<html>
<head>
<script type="text/javascript">
function addtxt(e,ctl,input) {
var key;
if (window.event) {
key = event.keyCode;
} else {
key = e.which;
}
if (key == 13) {
var obj=document.getElementById(input);
var txt=document.createTextNode("blah blah");
obj.appendChild(txt);
ctl.value = '';
return false;
}
return true;
}
</script>
</head>
<body>
<textarea id="textarea1"></textarea>
<br><input type="text" onkeypress="return addtxt(event,this,'textarea1');">
</body>
</html>
Note that there may be much better ways to achieve your ultimate goal, but since you don't state what that is, this is really the best I can do. Also, I'd would definitely look at using a framework like jQuery/Dojo/Prototype and add the handlers unobtrusively.
Use the form element
<form onsubmit="addtxt('textarea1')">
<textarea id="textarea1"></textarea>
<br><input type="text" />
</form>
You can use JQuery
$('textarea#textarea1').keypress(function(e) {
if (e.keyCode == 13) { // enter
//do some stuff
}
});