I am trying to create a form which will store values in an empty array but the values must be between 0 to 5 and comma separated. the problem is it alerts if values is more than 5 but still stores the value in the array. I want it to alert and then restore the form value.
Here is my code:
<form name ="form1" onsubmit="return validateForm()">
<input type="number" name="text" id="inputText" name="inputText" />
<button onclick="pushData();">Insert</button>
<p id="pText"></p>
</form>
And javascript:
function validateForm () {
var form = document.forms["form1"]["inputText"].value;
if(form <0 && form >= 6) {
alert('value should must be between 0 to 5');
return false;
}
}
// create an empty array
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];
}
// display array data
document.getElementById('pText').innerHTML = "Grades: " + pval ;
}
Try
if (form <0 || form >= 6)
I think it may work better if you reorganize where the functions are being bound.
Event propagation order:
The button is clicked, and the value is pushed into the array.
The form's submit event triggers, and validates the values, but it's too late.
There are many ways to approach this one, but the simplest would be to call pushData at the end of your validateForm.
Adjusted the condition, because there's no way for a number to
be less than 0 AND greater than or equal to 6 at the same time.
Also added event.preventDefault to stop form submission.
JavaScript
function validateForm (event) {
event.preventDefault();
var form = document.forms["form1"]["inputText"].value;
if (form < 0 || form > 5) {
alert('value should must be between 0 to 5');
return false;
}
pushData();
}
HTML
<form name="form1" onsubmit="validateForm(event)">
<input type="number" id="inputText" />
<button type="submit">Insert</button>
<p id="pText"></p>
</form>
JSFiddle
Note that per the MDN:
A number input is considered valid when empty and when a single number
is entered, but is otherwise invalid.
With this particular form element you may add min and max attributes so that the user must enter a value within a specified range. Therefore, the current contents of the OP's validateForm() function are superfluous. Additionally, that function has a problematic line of code:
if(form <0 && form >= 6) {
You cannot have a value that is both less than zero and greater than or equal to six. Use instead a logical OR, i.e. "||" operator for the logic to work.
The following code allows for a user to select numeric values in the range that the OP specifies and then it displays them in a comma-separated format, as follows:
var d = document;
d.g = d.getElementById;
var pText = d.g('pText');
pText.innerHTML = "Grades: ";
var inputText = d.g("inputText");
var myArr = [];
function pushData() {
var notrailingcomma = "";
myArr.push(inputText.value);
if (myArr.length > 1) {
notrailingcomma = myArr.join(", ").trim().replace(/,$/g,"");
pText.innerHTML = "Grades: " + notrailingcomma;
}
else
{
pText.innerHTML += inputText.value;
}
}
d.forms["form1"].onsubmit = function(event) {
event.preventDefault();
pushData();
};
p {
padding: 1em;
margin:1em;
background:#eeeeff;
color: #009;
}
<form name="form1">
<input type="number" id="inputText" name="inputText" min=0 max=5 value=0>
<button type="submit">Insert</button>
</form>
<p id="pText"></p>
A couple of points with respect to the form:
The OP's HTML has an error in the input field: it has two names. I dropped the one with a name of "text".
I like what #thgaskell recommends with respect to changing "Insert" into a submit button, preventing the default action of submitting the form, and associating pushData with the form's onsubmit event. So, I've modified the code accordingly.
Related
I have the below JavaScript submit function for a form that works fine. But when the form is on the page twice it only works for the first form and not for the second. I presume I need to use something with this so it only works on the active form?
HTML:
<form action="resultsnew.php" method="get" style="margin-bottom: 0" class="store-search-form">
<input type="text" name="d" value="Enter Postcode..." onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Enter Postcode...':this.value;" class="find-form-input field store-search-postcode" />
<input type="submit" onclick="java" value="Search" class="button" />
</form>
JavaScript:
$('.store-search-form').submit(function() {
//get the input's value
var postcodeinput = $('.store-search-postcode').val();
//remove spaces
postcodeinput = postcodeinput.replace(/\s/g, '');
//if valid postcode length trim it down
if (postcodeinput.length >= 5 && postcodeinput.length <= 7) {
//set the input's value
$('.store-search-postcode').val(postcodeinput.substring(0,postcodeinput.length - 3));
}
});
Do your searching relative to $(this) via find, i.e., change this:
var postcodeinput = $('.store-search-postcode').val();
to this:
var $this = $(this);
// ...
var postcodeinput = $this.find('.store-search-postcode').val();
(And in the other places you use it.)
Remember, within an event handler, this refers to the element the handler was hooked up to. $(this) creates a jQuery instance for that element. And then find searches within that element's descendants.
You need to reference the input that is in each form using $(this).find('.store-search-postcode') and then use that reference:
$('.store-search-form').submit(function() {
//get the input
var postcodeinput = $(this).find('.store-search-postcode');
//get the input's value
var postcode = postcodeinput.val();
//remove spaces
postcode = postcode.replace(/\s/g, '');
//if valid postcode length trim it down
if (postcode.length >= 5 && postcode.length <= 7) {
//set the input's value
postcodeinput.val(postcode.substring(0, postcode.length - 3));
}
});
I have numeric values with many decimal places and the precision is required for other functions. I want to present the values in a form, so the user can change the values if necessary.
To increase the readability, I want to display the values rounded to 2 decimal places, but if the user clicks on an input field, the complete value should be presented. By doing this, the user can see the real value and adjust them better.
Example:
HTML
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onchange="myFunction()" >
</fieldset>
</form>
JavasSript
<script>
//Example values that should be presented
var x = 3.14159265359;
function fillForm(){
document.getElementbyId("myInput1").value = x;
}
function myFunction(){
x = document.getElementbyId("myInput1");
}
</script>
The form input value should be " 3.14 " and if the user clicks in the field, the displayed value should be 3.14159265359.
Now the user can change the value and the new value has to be saved.
Because this is for a local 1 page website with no guaranty of internet connection, it would be an asset but not a requirement, to do it without an external script (jquery …).
you can use focus and blur event to mask/unmask you float, then simply store the original value in a data param, so you can use the same function to all input in your form ;)
function fillForm(inputId, val)
{
var element = document.querySelector('#'+inputId);
element.value = val;
mask(element);
}
function mask(element) {
element.setAttribute('data-unmasked',element.value);
element.value = parseFloat(element.value).toFixed(2);
}
function unmask(element) {
element.value = element.getAttribute('data-unmasked') || '';
}
<button onclick="fillForm('myInput1',3.156788)">Fill!</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onblur="mask(this)" onfocus="unmask(this)" >
</fieldset>
</form>
Edit: added "fillForm()" :)
Just use .toFixed(). It accepts one argument, an integer, and will display that many decimal points. Since Javascript primitives are immutable, your x variable will remain the same value. (also when getting/setting the value of an input use the .value property
function fillForm(){
document.getElementbyId("myInput1").value = x.toFixed(2);
}
If you need to save it you can store it in a new value
var displayX = x.toFixed(2)
Here is my solution. I hope you have other suggestions.
HTML
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" >
</fieldset>
</form>
<button id="myBtn" onclick="fill_form()">fill form</button>
JavasSript
<script>
var apple_pi = 10.574148541;
var id_form = document.getElementById("myForm");
//Event listener for form
id _form.addEventListener("focus", copy_input_placeh_to_val, true);
id _form.addEventListener("blur", round_input_2decimal, true);
id _form.addEventListener("change", copy_input_val_to_placeh, true);
// Replace input value with input placeholder value
function copy_input_placeh_to_val(event) {
event.target.value = event.target.placeholder;
}
// Rounds calling elemet value to 2 decimal places
function round_input_2decimal(event) {
var val = event.target.value
event.target.value = Number(val).toFixed(2);
}
// Replace input placeholder value with input value
function copy_input_val_to_placeh(event) {
event.target.placeholder = event.target.value;
}
// Fills input elements with value and placeholder value.
// While call of function input_id_str has to be a string ->
//fill_input_val_placeh("id", value) ;
function fill_input_val_placeh (input_id_str, val) {
var element_id = document.getElementById(input_id_str);
element_id.placeholder = val;
element_id.value = val.toFixed(2);
}
// Writes a value to a form input
function fill_form(){
fill_input_val_placeh("myInput1", apple_pi);
}
</script>
Here is an running example
https://www.w3schools.com/code/tryit.asp?filename=FLDAGSRT113G
Here is solution, I used focus and blur listeners without using jQuery.
I added an attribute to input named realData
document.getElementById("myInput1").addEventListener("focus", function() {
var realData = document.getElementById("myInput1").getAttribute("realData");
document.getElementById("myInput1").value = realData;
});
document.getElementById("myInput1").addEventListener("blur", function() {
var realData = Number(document.getElementById("myInput1").getAttribute("realData"));
document.getElementById("myInput1").value = realData.toFixed(2);
});
function fillForm(value) {
document.getElementById("myInput1").value = value.toFixed(2);
document.getElementById("myInput1").setAttribute("realData", value);
}
var x = 3.14159265359;
fillForm(x);
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" realData="" onchange="myFunction()" >
</fieldset>
</form>
jsfiddle : https://jsfiddle.net/mns0gp6L/1/
Actually there are some problems that needs to be fixed in your code:
You are redeclaring the x variable inside your myFunction function with var x =..., you just need to refer the already declared x without the var keyword.
Instead of using document.getElementById() in myFunction, pass this as a param in onchange="myFunction(this)" and get its value in the function.
Use parseFloat() to parse the value of your input to a float, and use .toFixed(2) to display it as 3.14.
This is the working code:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function myFunction(input) {
x = parseFloat(input.value);
}
To display the original number when you click on the input you need to use the onfocus event, take a look at the Demo.
Demo:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function focusIt(input){
input.value = x;
}
function myFunction(input) {
x = parseFloat(input.value);
}
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm">
<fieldset>
<input type="text" id="myInput1" onchange="myFunction(this)" onfocus="focusIt(this)">
</fieldset>
</form>
I have 5 textboxes displayed, a user can add more textboxes dynamically. However, I am not able to get the the sum and average of the values inputted by users on those textboxes. Can you please help me. I will really appreciate it.
Hear is the HTML code:
<html>
<head>
<title> Grading System </title>
</head>
<script src="addInput.js" language="Javascript" type="text/javascript">
</script>
<body>
<center> GRADING SYSTEM <br><br>
<form method="POST">
<div id="dynamicInput">
Subject number 1<br><input type="text" name="myInputs[]"><br>
Subject number 2<br><input type="text" name="myInputs[]"><br>
Subject number 3<br><input type="text" name="myInputs[]"><br>
Subject number 4<br><input type="text" name="myInputs[]"><br>
Subject number 5<br><input type="text" name="myInputs[]">
</div>
<input type="button" value="Add a subject" onClick="addInput('dynamicInput');">
<input type="button" name="BtnCompute" onClick="avg('dynamicInput');" value="Compute Average">
</form>
</body>
</html>
Then here's the Javascript code:
var counter = 5;
var limit = 10;
var sum=0;
var average=0;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Subject number " + (counter + 1) + " <br><input type='text' name='myInputs[]' >";
document.getElementById(divName).appendChild(newdiv);
counter++
}
}
function avg(divName){
sum += document.getElementsByName("myInputs[]")[0].value;
average = sum / counter
alert("Average is " + average);
return false;
}
The problems with your original function:
function avg(divName) {
// you only look at one <input> element ever time, rather
// than iterating over the collection returned by
// 'document.getElementsByName("myInputs[]")'; plus you're using
// a global value which is (at least potentially) exposed to
// every other function, which makes it vulnerable to being
// over-written by other values; also: you're not ensuring that
// the entered-value is a Number (an <input> returns its value as
// a String, not a Number):
sum += document.getElementsByName("myInputs[]")[0].value;
// here you're working out the average of two global values,
// both of which could be corrupted by other functions, and
// neither of which - being global - are guaranteed to be
// Numbers, since you're not enforcing that anywhere. Also
// you've exposed yourself to potential browser interference
// by not ending the line with the (optional) semi-colon:
average = sum / counter
// this is personal, but for debugging I'd recommend use of
// console.log() (but, again, a purely personal reccomendation
// and not really a 'problem' as such):
alert("Average is " + average);
return false;
}
My correction of your original function would be:
function avg() {
// rather than passing in an argument explicitly, I've opted
// to use a custom data-* attribute to contain the id of the
// relevant <div> (see the HTML below, this simplifies
// changes somewhat in the future):
var div = document.getElementById(this.dataset.divname),
// using Node.querySelectorAll() to retrieve the relevant
// <input> elements (my inclination would be to further
// amend the selector to 'input,' but that depends on
// whether or not you'd have any irrelevant <input>
// elements contained within the same <div>):
inputs = div.querySelectorAll('input[type=text][name="myInputs[]"]'),
// using Function.prototype.call() to apply the
// Array.prototoype.map() function to the Array-like
// NodeList returned by document.querySelectorAll(),
// and returns an Array of (in this case) entered values:
sum = Array.prototype.map.call(inputs, function (inputNode) {
// here we convert the existing value of the <input>
// element-node to a Number (<input> elements return
// their values as a String) or, if the value can't
// be converted to a Number, or the <input> has no
// entered value, we return 0:
return parseFloat(inputNode.value) || 0;
// using Array.prototype.reduce() to sum the
// Array of values returned by Array.prototype.map():
}).reduce(function (a, b) {
// here we return the sum of the previous number
// and the current number:
return a + b;
// the 0 here is the initial starting value
// to which the numbers are added:
}, 0),
// ensuring that the counter variable (first
// argument) is parsed into an integer value
// (using parseInt(), in base-10 (the second
// argument):
average = sum / parseInt(counter, 10);
console.log("Average is " + average);
return false;
}
// here we use JavaScript to attach the event-handling function to
// the relevant <input> (I added the 'id' to enable this), and
// this binds the avg() function to handle the 'click' event:
document.getElementById('btnCompute').addEventListener('click', avg);
The HTML for the amended <input> element:
<input id="btnCompute" data-divname="dynamicInput" type="button" name="BtnCompute" value="Compute Average" />
var counter = 5;
var limit = 10;
function addInput() {
// note that I've amended this function also, to
// use the 'data-divname' attribute to hold the
// 'id' of the relevant <div>:
var div = document.getElementById(this.dataset.divname);
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Subject number " + (counter + 1) + " <br><input type='text' name='myInputs[]' >";
div.appendChild(newdiv);
counter++
}
}
function avg() {
var div = document.getElementById(this.dataset.divname),
inputs = div.querySelectorAll('input[type=text][name="myInputs[]"]'),
sum = Array.prototype.map.call(inputs, function(inputNode) {
return parseFloat(inputNode.value) || 0;
}).reduce(function(a, b) {
return a + b;
}, 0),
average = sum / parseInt(counter, 10);
snippet.log("Average is " + average);
return false;
}
document.getElementById('addNew').addEventListener('click', addInput);
document.getElementById('btnCompute').addEventListener('click', avg);
label,
input[type=text] {
display: block;
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<!--
Note that I've also amended your HTML, removing the
unnecessary <br /> elements, instead using CSS to
provide line-breaks; and also wrapping the <input>
elements in <labels>, both to enable the CSS line-
breaks and to enable clicks on the text to focus
the associated (nested) <input> element:
-->
<form method="POST" action="#">
<div id="dynamicInput">
<label>Subject number 1
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 2
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 3
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 4
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 5
<input type="text" name="myInputs[]" />
</label>
</div>
<input id="addNew" data-divname="dynamicInput" type="button" value="Add a subject" />
<input id="btnCompute" data-divname="dynamicInput" type="button" name="BtnCompute" value="Compute Average" />
External JS Fiddle demo, for experimentation/development.
Despite my correction of your function though, I'd probably take an alternative approach:
// because I retrieve the number of elements in a couple
// of places, I created a simple function to retrieve
// that number of elements:
function currentlyExisting(selector) {
return document.querySelectorAll(selector).length;
}
// rewritten in my own style (though this is irrelevant to the
// the question you asked):
function addNew() {
// still using the value of the custom 'data-divname'
// attribute:
var parent = document.getElementById(this.dataset.divname),
// rather than creating a HTML string, here I create nodes
// using document.createElement() and a textNode, using
// document.createTextNode():
label = document.createElement('label'),
input = document.createElement('input'),
// getting the number of currently-existing <input>
// elements using the above function, passing the
// selector as an argument:
current = currentlyExisting('input[name="myInputs[]"'),
limit = 10;
// if the current number of <input> elements is less than
// the limit:
if (current < limit) {
// we set the type of the created <input>:
input.type = 'text';
// and the name property:
input.name = 'myInputs[]';
// appending a textNode to the created <label> element:
label.appendChild(document.createTextNode('Subject number ' + (current + 1) + ':' ));
// appending the created <input> to the created <label>:
label.appendChild(input);
// attaching the created <label>, along with its own
// childNodes, to the parent div (retrieved and cached above):
parent.appendChild(label);
// setting the disabled property to true if the updated
// number of <input> elements is equal to, or greater than,
// the limit; or to false if the number of <input> elements
// remains less than the limit (preventing the addition of
// more <input> elements than that identified by the limit):
this.disabled = currentlyExisting('input[name="myInputs[]"') >= limit;
}
// all functions return a value, whether it's explicitly defined
// or undefined (as this one will), the return false of your
// original function can be added here instead if you prefer,
// but I - personally - feel it's unnecessary, so I left it out.
}
function average() {
// retrieving the relevant <div> element using the
// data-divname attribute once again:
var parent = document.getElementById(this.dataset.divname),
// retrieving the relevant <input> elements:
inputs = parent.querySelectorAll('input[name="myInputs[]"]'),
// creating an Array of the values of the relevant
// <input> elements, using Function.prototype.call()
// in order to use Array.prototype.map() on the
// Array-like NodeList returned by querySelectorAll():
values = Array.prototype.map.call(inputs, function (input) {
// returning the value of the current <input>
// element as a number to the array, using
// parseFloat() to convert that String to a
// Number; or returning 0 if the String cannot
// be parsed as a Number:
return parseFloat(input.value) || 0;
// using Array.prototype.reduce() to reduce the Array
// of numeric values (provided by map()) to a single
// number, the sum of the values:
}).reduce(function (a, b) {
// adding the previous and current values
// together:
return a + b;
// here the 0 is the initial value before the Array
// 'reduction' takes place:
}, 0),
average = sum / inputs.length;
// adding the values to the appropriate elements on screen
// for easier visualisation (and in a manner that persists):
document.getElementById('average').textContent = average;
document.getElementById('sum').textContent = sum;
document.getElementById('total').textContent = inputs.length;
}
// adding the click event handlers to the relevant button <input>
// elements using EventTarget.addEventListener():
document.getElementById('addNew').addEventListener('click', addNew);
document.getElementById('btnCompute').addEventListener('click', average);
function currentlyExisting(selector) {
return document.querySelectorAll(selector).length;
}
function addNew() {
var parent = document.getElementById(this.dataset.divname),
label = document.createElement('label'),
input = document.createElement('input'),
current = currentlyExisting('input[name="myInputs[]"'),
limit = 10;
if (current < limit) {
input.type = 'text';
input.name = 'myInputs[]';
label.appendChild(document.createTextNode('Subject number ' + (current + 1) + ':'));
label.appendChild(input);
parent.appendChild(label);
this.disabled = currentlyExisting('input[name="myInputs[]"') >= limit;
}
}
function average() {
var parent = document.getElementById('dynamicInput'),
inputs = parent.querySelectorAll('input[name="myInputs[]"]'),
sum = Array.prototype.map.call(inputs, function(input) {
return parseFloat(input.value) || 0;
}).reduce(function(a, b) {
return a + b;
}, 0),
average = sum / inputs.length;
document.getElementById('average').textContent = average;
document.getElementById('sum').textContent = sum;
document.getElementById('total').textContent = inputs.length;
}
document.getElementById('addNew').addEventListener('click', addNew);
document.getElementById('btnCompute').addEventListener('click', average);
label,
input[type=text] {
display: block;
}
#average::before {
content: 'Average: ';
}
#sum::before {
content: ', sum: ';
}
#total::before {
content: ', of: ';
}
#total::after {
content: ' entries.'
}
#total:empty::before,
#total:empty::after,
#sum:empty::before,
#average:empty::before {
content: '';
display: none;
}
<div id="results">
<span id="average"></span>
<span id="sum"></span>
<span id="total"></span>
</div>
<form method="POST" action="#">
<div id="dynamicInput">
<label>Subject number 1:
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 2:
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 3:
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 4:
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 5:
<input type="text" name="myInputs[]" />
</label>
</div>
<input id="addNew" data-divname="dynamicInput" type="button" value="Add a subject" />
<input id="btnCompute" data-divname="dynamicInput" type="button" name="BtnCompute" value="Compute Average" />
</form>
External JS Fiddle demo, for experimentation/development.
References
HTML:
Custom data-* attributes.
JavaScript:
Array.prototype.map().
Array.prototype.reduce().
document.getElementById().
document.getElementsByName().
document.querySelectorAll().
EventTarget.addEventListener().
Function.prototype.call().
HTMLElement.dataset.
parseFloat().
parseInt().
So I think you're missing a few things.
sum += document.getElementsByName("myInputs[]")[0].value;
this line gets only the first input field value, so you need a loop through all the input fields to get the actual sum
for (var i = 0; i < counter; i++)
sum += parseInt(document.getElementsByName("myInputs[]")[i].value);
Next, notice the addition of the parseInt(); method. This converts the input value (which javascript sees as a string by default) into an integer in which you can perform calculations on.
Hope that helps you, cheers
For example, if I have a form and I don't want the user to enter numbers in it and I validate it with a function containing a regular expression, how do I prevent the invalid character the user entered (in this example, a digit) from showing up in the text form if it fails the regular expression test?
This is the function I tried and the select list I tried it on (in other words, this isn't the whole program). I tried returning false to the onkeypress event handler but what the user enters into the textbox still goes through.
function noNumbers(answer) { //returns false and displays an alert if the answer contains numbers
if (/[\d]+/.test(answer)) { // if there are numbers
window.alert("You can not enter numbers in this field");
return false;
}
}
<form action="get" enctype="application/x-www-form-urlencoded">
<select id="questions" name="questions">
<option value="no_numbers">What is the name of the city where you were born?</option>
<option value="no_letters">What is your phone number?</option>
<option value="no_numbers">What is the name of your favorite pet?</option>
<option value="no_letters">What is your social security number?</option>
<option value="no_numbers">What is your mother's maiden name?</option>
</select>
<p><input type="text" name="answer" onkeypress="validateAnswer();" /></p>
</form>
This validation works great for stripping invalid characters on the fly as you enter them in the relevant field. Example:
<form id="form1" name="form1" method="post">
Email:
<input type="text" name="email" id="email" onkeyup='res(this, emailaddr);' ; </form>
<script>
var phone = "()-+ 0123456789";
var numb = "0123456789";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-'.,";
var alphanumb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-.'1234567890!?,:;£$%&*()";
var alphaname = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,-.1234567890";
var emailaddr = "0123456789#._abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function res(t, v) {
var w = "";
for (i = 0; i < t.value.length; i++) {
x = t.value.charAt(i);
if (v.indexOf(x, 0) != -1)
w += x;
}
t.value = w;
}
</script>
Then you would simply change the second value of the javascript call to the type of data you want entered in the field using the variables that are defined within the code.
This is the function you are looking for
function validateAnswer(src) {
var questions = document.getElementById("questions");
var rule = questions.options[questions.selectedIndex].value;
if(rule=="no_numbers") src.value = src.value.replace(/\d/g, '');
if(rule=="no_letters") src.value = src.value.replace(/\w/g, '');
}
just send the input field reference to the function and set it to onkeyup event instead:
<input type="text" name="answer" onkeyup="validateAnswer(this);" />
you should also hook the onchange event of the selectbox to reset the value of the input box. I suggest you also consider the HTML5 pattern attribute. See
the fiddle
patern attribute support
workaround for unsupported browsers
You get the key being pressed from the event object passed to the handler.
input type="text" name="answer" onkeypress="validateAnswer(this, event);" />
function validateAnswer(element, event) {
if (event.charCode) {
if (/\d/.test(String.fromCharCode(event.charCode))) {
window.alert("You can not enter numbers in this field");
return false;
}
}
}
Googling for "onkeypress event" finds many examples of this.
Make your life simpler by adding an extra parameter to your validateAnswer function like this:
<input type="text" id="answer" name="answer" onkeyup="validateAnswer(this);" />
Then you can define your validateAnswer like this:
function validateAnswer(elem){
elem.value = elem.value.replace(/[^\d]/g, '');
}
Here an example: http://jsbin.com/iwiduq/1/
I have this function which i am using to compare two input fields. If the user enters the same number in both the text field. On submit there will be an error. Now i would like to know if there is a way to allow same number but not higher than or lower the value of the previous text box by 1. For example if user enters 5 in previous text box, the user can only input either 4, 5 or 6 in the other input field.Please give me some suggestions.
<script type="text/javascript">
function Validate(objForm) {
var arrNames=new Array("text1", "text2");
var arrValues=new Array();
for (var i=0; i<arrNames.length; i++) {
var curValue = objForm.elements[arrNames[i]].value;
if (arrValues[curValue + 2]) {
alert("can't have duplicate!");
return false;
}
arrValues[curValue] = arrNames[i];
}
return true;
}
</script>
<form onsubmit="return Validate(this);">
<input type="text" name="text1" /><input type="text" name="text2" /><button type="submit">Submit</button>
</form>
A tidy way to do it which is easy to read:
var firstInput = document.getElementById("first").value;
var secondInput = document.getElementById("second").value;
if (firstInput === secondInput) {
// do something here if inputs are same
} else if (firstInput > secondInput) {
// do something if the first input is greater than the second
} else {
// do something if the first input is less than the second
}
This allows you to use the values again after comparison as variables (firstInput), (secondInput).
Here's a suggestion/hint
if (Math.abs(v1 - v2) <= 1) {
alert("can't have duplicate!");
return false;
}
And here's the jsfiddle link, if you want to see the answer
Give them both IDs.
Then use the
if(document.getElementById("first").value == document.getElementById("second").value){
//they are the same, do stuff for the same
}else if(document.getElementById("first").value >= document.getElementById("second").value
//first is more than second
}
and so on.