As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I have created a simple Javascript Captcha but currently the values are randomly generated but I want to get values from the array only(want to randomized these two array), plz check my code I want to do this using simple Javascript with no dependency also plz fix the function validate().
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function myCaptcha() {
var leftnum =[5, 10, 15, 20];
var rightnum =[2, 4, 6, 8];
var leftnum = Math.floor(Math.random()*11);
var rightnum = Math.floor(Math.random()*11);
var tolnum = leftnum + rightnum ;
document.getElementById("sh").innerHTML = leftnum + " + " + rightnum;
}
function validate() {
var captchanow = document.getElementById("captcha");
if (captchanow != "") {
alert("Please enter a captcha");
return false;
}
else if(captchanow == tolnum) {
alert("wrong captcha entered");
return false;
}
else {
form.submit
}
return true;
}
</script>
</head>
<body onload="myCaptcha()">
<form action="" method="post" onsubmit="return false;">
<p>Captcha :
<input name="captcha" type="text" id="captcha" value="" />
<label id="sh" value=""></label></p>
<p>
<input type="submit" name="button" id="button" value="Submit" onclick="validate()"/>
</p>
</form>
</body>
</html>
I discourage you strongly from using a JavaScript captcha as it will entirely remove the point of a captcha, which is to not be machine-readable.
Instead, I would recommend you to switch to something like reCAPTCHA.
Using a JavaScript CAPTCHA will only upset your users and spambots may solve it with their eyes closed [figuratively].
First of all, a Javascript CAPTCHA is completely pointless, as the bots that you want to stop won't be running the Javascript in the page.
Anyhow, this is how you pick items from arrays:
var leftnums =[5, 10, 15, 20];
var rightnums =[2, 4, 6, 8];
var leftnum = leftnums[Math.floor(Math.random() * leftnums.length)];
var rightnum = rightnums[Math.floor(Math.random() * rightnums.length)];
To get the value of the input field, use the value property:
var captchanow = document.getElementById("captcha").value;
To check if two numbers differ, use the != operator, and parse the string to an integer value:
else if(parseInt(captchanow,10) != tolnum) {
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm a beginner in JavaScript & in this task I have I have to do the following;
allow the user to enter questions and answer pairs in an html page which will be stored in an array.
retrieve the answer when one of the questions from the array is asked (different boxes, labels)
Reset the boxes when I press a button
So far, I just know how to store the user input in one single array, append it when a button is pressed and display it.
How do I have two different objects (Question & answer) in the same array that will be an input by the user in pairs and retrieve only the answer when the Question is input again? It kind of works like a Manual Bot.
var myArr = [];
function pushData() {
// get value from the input text
var inputText = document.getElementById('inputText').value;
// append data to the array
myArr.push(inputText);
var pval = "";
for (i = 0; i < myArr.length; i++) {
pval = pval + myArr[i] + "<br/>";
}
// display array data
document.getElementById('pText').innerHTML = pval;
}
<!DOCTYPE html>
<html>
<head>
<title</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="text" name="text" id="inputText" />
<button onclick="pushData();">Show</button>
<p id="pText"></p>
</body>
</html>
Why not use an object? That way, you can store the Question/Answer pairs with the Question as the key and the answer as its value. Try this out:
var myObj = {};
function pushData() {
// get value from the input text
var question = document.getElementById('inputQuestion').value;
var answer = document.getElementById('inputAnswer').value;
// add data to the object
myObj[question] = answer;
}
function getAnswer() {
var question = document.getElementById('inputRetrieveQuestion').value;
if (myObj[question]) {
document.getElementById('pText').innerHTML = myObj[question];
}
}
<html>
<body>
<h3> Enter a Question/Answer </h3>
Question <input type="text" name="question" id="inputQuestion" /> Answer <input type="text" name="answer" id="inputAnswer" />
<button onclick="pushData()">Submit</button>
</br>
<h3> Retrieve an Answer </h3>
Question <input type="text" name="question" id="inputRetrieveQuestion" />
<button onclick="getAnswer()">Submit</button>
</br>
Answer:
<div id="pText"></div>
</body>
</html>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Please help me in this issue
I want to fill all the fields with random data
https://jsfiddle.net/omrmstg7/
<html>
<head>
<script>
//<![CDATA[
window.onload=function(){
var button = document.getElementById("my-button");
var input = document.getElementById("my-input");
var names = ["Henry", "Joseph", "Mark", "Michael"];
button.addEventListener("click", function() {
input.value = names[Math.floor(Math.random() * names.length)];
});
}//]]>
</script>
</head>
<body>
<button id="my-button">Generate Random Names</button>
<input type="text" id="my-input" />
<input type="text" id="my-input" />
<input type="text" id="my-input" />
</body>
</html>
I'm guessing your problem is that you want to fill all the inputs and it doesn't do that.
The problem is that id is reserved for unique elements.
So, if you change your HTML for id to be class instead, you would change your JavaScript to something like this:
var button = document.getElementById("my-button");
var inputs = document.getElementsByClassName("my-input");
var names = ["Henry", "Joseph", "Mark", "Michael"];
button.addEventListener("click", function() {
Array.prototype.forEach.call(inputs, function (input) {
input.value = names[Math.floor(Math.random() * names.length)];
});
});
Change the inputs to use a class instead of an id.
id values should be unique in HTML and getElementById only returns the first matching id.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am new to JavaScript... The following code displays correct even when I submit an incorrect value, I can't get the "else" section to work:
<!doctype html>
<html>
<head>
<script type="text/javascript">
/*<![CDATA [*/
function myFunction() {
var answer = document.getElementById('answer');
if (answer = 10)
document.getElementById("valid").innerHTML = "Correct!";
else
document.getElementById("valid").innerHTML = "Please, Try Again!";
}
/* ]]> */
</script>
</head>
<body>
<h2>What is 3+7=?</h2>
<form>
<input type="text" id="answer">
<input type="submit" onClick="myFunction(); return false;">
</form>
<div id="valid"></div>
</body>
</html>
Change your function to
function myFunction() {
var answer = parseInt(document.getElementById('answer').value,10);
if (answer === 10)
document.getElementById("valid").innerHTML = "Correct!";
else
document.getElementById("valid").innerHTML = "Please, Try Again!";
}
And it will work like a charm.
Explanation.
The element with id="answer" is an input. To retrieve value of an input, you need .value
Like var answer = document.getElementById('answer').value;
Now, this will return the value in your input type="text" as a string.
Ideally, you should parse it into the int using parseInt().
Like var answer = parseInt(document.getElementById('answer').value);
This will avoid type coersion.
Lastly, you want to compare the two values, so you need to use == operator.
Single =, an assignment operator would just assign the value and would always result into true since assignment gets successful.
And it's best practice to use strict comparison with datatypes. using === operator.
You need to use the equality operator == instead of the assignment operator =.
Also you need to get the value of the answer, not the just the element.
<!doctype html>
<html>
<head>
<script type="text/javascript">
/*<![CDATA [*/
function myFunction() {
var answer = document.getElementById('answer').value;
if (answer == 10)
document.getElementById("valid").innerHTML = "Correct!";
else
document.getElementById("valid").innerHTML = "Please, Try Again!";
}
/* ]]> */
</script>
</head>
<body>
<h2>What is 3+7=?</h2>
<form>
<input type="text" id="answer">
<input type="submit" onClick="myFunction(); return false;">
</form>
<div id="valid"></div>
</body>
</html>
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm not a javascript programmer, but I have to use it for a calculation I need to do on a wordpress page.
Here is what I need:
3 fields in html where I can enter a number (a form).
a text field where the multiplication is "printed"
if I change one element, a new result must apear, without me needing to push any button.
any idea on how to do this?
I know how to do the calculation as such, but not that it works automatically.
HEre is what I got so far:
<html>
<head>
<title>Simple Javascript Calculator - Basic Arithmetic Operations</title>
<script language="javascript" type="text/javascript">
function multiply(){
a=Number(document.calculator.number1.value);
b=Number(document.calculator.number2.value);
c=a*b;
document.calculator.total.value=c;
}
</script>
</head>
<body>
<!-- Opening a HTML Form. -->
<form name="calculator">
<!-- Here user will enter 1st number. -->
Number 1: <input type="text" name="number1">
<!-- Here user will enter 2nd number. -->
Number 2: <input type="text" name="number2">
<!-- Here result will be displayed. -->
Get Result: <input type="text" name="total">
<!-- Here respective button when clicked, calls only respective artimetic function. -->
<<input type="button" value="MUL" onclick="javascript:multiply();">
</form>
</body>
</html>
thanks
jsFiddle Demo
You are going to be forced to use an interval if you want to monitor two inputs and handle all changes (such as pasting in, either from a mouse, from ctrl+v, from using the edit+paste browser input, from typing, etc.).
If you do not need to handle all cases, then onkeyup will work as Bart suggests. Here is an interval approach:
var x = document.getElementById("x");
var y = document.getElementById("y");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
var ystored = y.getAttribute("data-in");
setInterval(function(){
if( x == document.activeElement ){
var temp = x.value;
if( xstored != temp ){
xstored = temp;
x.setAttribute("data-in",temp);
calculate();
}
}
if( y == document.activeElement ){
var temp = y.value;
if( ystored != temp ){
ystored = temp;
y.setAttribute("data-in",temp);
calculate();
}
}
},50);
function calculate(){
d.innerHTML = x.value * y.value;
}
x.onblur = calculate;
calculate();
This will not answer the problem for your specific question but a nice way to do your calculations is through the eval function.
http://jsfiddle.net/gL3YF/1/
The HTML:
<input type="text" id="expression" value="1 + 1" />
<hr />
<h3 id="result"></h3>
The Javascript:
var input = document.getElementById('expression');
input.onkeyup = function () {
var result = document.getElementById('result');
result.innerHTML = eval(this.value);
};
//evaluate initial value
input.onkeyup();
use the onchange event on each input element so that when a user changes input[value] an operation is triggered. You should also cache the previously performed operation so that it's applied to the operands when onchange event is triggered
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: formatting number with exactly two decimals
I need a JS (jQuery) script, that helps me limit the input of numbers to two decimal points.
I have tried this and it works perfect limiting my input only to floats or integers. But I can't understand how to make it limit to two decimal points.
I also looked at lots of other answers here, but none seem to stop the user from inputing more then two digits while typing.
Any suggestions? Thanx.
EDIT: My code, if it helps
The form:
<form method="post" id="split_form"
action="?name=ajax&case=split_action&sid=' . $id . '"
onSubmit="return checkform(this);" >
<table class="default" cellpadding="0" cellspacing="0">
<tr><td><input class="numeric1" type="text" name="summ_1" value="" />
<tr><td><input class="numeric2" type="text" name="summ_2" value="" />
</table>
<input type="submit" class="submit" value="ok" />
</form>
JS scripts:
<script type="text/javascript" src="/js/jquery.numeric.js"></script>
<script language="JavaScript" type="text/javascript">
$(".numeric1").numeric();
$(".numeric2").numeric();
function checkform ( form ) {
var sum1 = form.summ_1.value;
var sum2 = form.summ_2.value;
var new_summ = parseFloat(sum1) + parseFloat(sum2);
var summ = parseFloat(' . $row[1]['summ'] . ');
if ( ( sum1 > 0 && sum2 > 0 ) && ( new_summ == summ ) ) {
return true;
} else {
return false ;
}
}
</script>
In the numeric plugin, line 135, numeric entries are treated. Currently, they are always allowed. You could modify this plugin to allow numbers only if the decimal point is nonexistent, or no more than two steps away:
var decimalIx = $(this).val().indexOf(decimal);
allow = decimalIx == -1 || decimalIx >= $(this).val().length - 2;
I was going to make the -2 configurable, but as Alex Ball pointed out in comments, the work has already been done.