I'm trying to make sure the input in a particular field is just an 11 digit number, however my if condition does not seem to be working:
Javascript:
<script>
function check() {
var x = document.forms["myform"]["mobile"].value;
if (!/^\d{11}$/.test(x)) {
myform.action="gender.html";
else {
myform.action="mobilerror.html"
}
}
</script>
And the HTML is:
<form id="myform" onsubmit="check();" >
<input class="input" type="text" name="mobile" required="required"
oninvalid="this.setCustomValidity('Number is empty')" oninput="setCustomValidity('')" />
</form>
Please help!
You can try maxlength and type attribute of input field:
<input class="input" type="text" name="mobile" maxlength="11" type="number" required="required"/>
If it satisfy your case then you don't need to call javascript function.
Your regular expression is working just fine. I think the error lies in the "if" condition. Try changing
if (!/^\d{11}$/.test(x)) {
myform.action="gender.html";
else {
myform.action="mobilerror.html"
}
to this
if (/^\d{11}$/.test(x)) {
myform.action="gender.html";
else {
myform.action="mobilerror.html"
}
As you can see I just took off the negation in the expression.
Note: Assuming that the "mobilerror.html" is shown when the user didn't type the 11 digit as expected.
Try this
function check() {
var x = document.forms["myform"]["mobile"].value;
var pattern = new RegExp("^1?([1-9])(\\d{10})");
if (pattern.test(x)) {
myform.action="gender.html";
} else {
myform.action="mobilerror.html"
}
}
^1?([1-9]) checks if the first number is not zero, so that the input value is numerically a 11-digit number. If you don't want it you can remove it.
This help you :
use type 'number':
<input type="number" id="number" class="input">
and test number digits is 11 or not with :
var patt = /.{11}/;
Example :
<html>
<head>
<style>
</style>
</head>
<body>
<form id="myform" onsubmit="check()" >
<input id="number" class="input" type="number">
<button type="submit">Submit</button>
</form>
<script>
var patt = /.{11}/;
function check(){
var num = document.getElementById("number").value;
var frm = document.getElementById("myform");
if(patt.test(num))
frm.action ="mobilerror.html"
else
frm.action = "gender.html";
}
</script>
</body>
</html>
Related
The goal is to replace some characters directly when written in the form input, not after submitting the form. Also, I would like to change the contrast of the replacing character to be kind of grey/less visible.
I came up with something like that (but not working infortunately):
<form action="" method="post">
<input type="text" name="test_input" id="test_input" onkeypress="myFunction()" required>
<input type="submit" value="Subscribe!">
</form>
<script>
function myFunction() {
let str = document.getElementById("test_input").innerHTML;
let res = str.replace(/a/g, "b");
document.getElementById("test_input").innerHTML = res;
}
</script>
You have some mistakes in your code. Check out corrected code.
You need to correct your pattern.
<form action="" method="post">
<input type="text" name="test_input" id="test_input" onkeyup="myFunction()" required>
<input type="submit" value="Subscribe!">
</form>
<script>
function myFunction() {
let str = document.getElementById("test_input").value;
let res = str.replace(/a/g, "b");
console.log(res)
document.getElementById("test_input").value = res;
}
</script>
Try a cleaner solution that uses regular expressions:
<input type="text" onkeyup="this.value=this.value.replace(/[Search Expression]/flag,'New String');"/>
This solution prevents the user from typing a value outside the pattern established by the regex.
Example:
To remove all the numbers from "name" field:
<input type="text" onkeyup="this.value=this.value.replace(/[\d]/g, '');">
I want to limit number of words that user input to a text box . I tried one code it was successfull for only single text box when i ammend it to multiple text box this code did not work, An advice will be really appreciated.
<html>
<head>
<script type="text/javascript">
function validate(){
x=document.myForm
input=x.myInput.value
if (input.length>5){
alert("The field cannot contain more than 5 characters!")
return false
}else {
return true
}
}
</script>
</head>
<body>
<form name="myForm" action="http://www.java2s.com" onsubmit="return validate()">
Enter some text (less than 5 characters):
<input type="text" name="myInput" size="20">
<input type="submit" value="Submit">
</form>
</body>
</html>
There are two methods to go about it:
Method 1:
Using the maxlength="5" attribute
<input type="text" maxlength="5" name="somename"/>
Method 2:
Using Javascript:
<script language="javascript" type="text/javascript">
function limitInput(field, max) {
if (field.value.length > max) {
field.value = field.value.substring(0, max);
}
}
</script>
<input type="text" name="somename" onKeyDown="limitInput(this,5);" onKeyUp="limitInput(this,5);"" />
UPDATE
With a message:
<script language="javascript" type="text/javascript">
var errHolder = document.getElementById('err');
function limitInput(field, max) {
if (field.value.length > max) {
err.style.display = 'inline-block';
}
else
{
err.style.display = 'none';
}
}
</script>
<span>
<input type="text" name="somename" onKeyDown="limitInput(this,5);" onKeyUp="limitInput(this,5);" />
</span>
<span id="err" style="display:none;background-color:red;">Please enter less than 5 characters</span>
You can either set the maxlength attribute or trim the string everytime the user enters into it. Using maxlength is a better way of doing it
var input = document.getElementById("limit5");
var LIMIT = 5;
input.onkeyup=function(){
if(input.value.length > LIMIT){
input.value = input.value.substr(0,LIMIT);
//alert("Please limit your input to 5 characters")
}
}
<input id="autolimit5" maxlength="5" type="text"/>
<input id="limit5" type="text"/>
There are many ways to to prevent user from entering data in form elements. What you are trying is to validate all data in one go when user clicks on the Submit button. It would be better to validate at the time when the user is typing. Basically there are 4 related events whenever the user presses anything on the keyboard.
onKeyPress
onKeyDown
onKeyUp
onInput
You can use a combination of these events to achieve anything that you want. For the use case in the question we can just use keypress event.
<html>
<head>
<script type="text/javascript">
function validate(){
x=document.myForm
input=x.myInput.value
if (input.length>5){
alert("The field cannot contain more than 5 characters!")
return false
}else {
return true
}
}
// function which runs on every keypress of input element to which this
// function is attached
function validateTextField(e){
if(event.currentTarget.value.length >= 5){
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="http://nothing.com" onsubmit="return validate()">
Enter some text (less than 5 characters):
<input type="text" name="myInput" size="20" onkeypress="return validateTextField(event)">
<input type="text" name="anotherInput" size="20" onkeypress="return validateTextField(event)">
<input type="submit" value="Submit">
</form>
</body>
</html>enter code here
If you want, you can customize the size for the validation by changing some of the parameters
Update the html input definition with below
<input type="text" name="myInput" size="20" onkeypress="return validateTextField(event, 5)">
<input type="text" name="anotherInput" size="20" onkeypress="return validateTextField(event, 8)">
Update the function definition to use the second parameter
function validateTextField(e, size){
console.log(e);
if(event.currentTarget.value.length >= size){
return false;
}
}
my HTML code:
<form action="Generator.klx" method="post" onsubmit="genarate('hiddenField')">
<input type="hidden" id="hiddenField" name="hidden" value=""/>
<input type="submit" name="submit"/>
</form>
my JavaScript:
function genarate(hiddenField){
var field = document.getElementById(hiddenField);
field.value = "new Value";
}
But it just didnot work :(. Can anybody tell me where I was wrong?
Thank you
Your code as quoted should be working, and does in my tests with a variety of browsers. (I've tried it locally, with a POSTed form, but you can also try it here: http://jsbin.com/ehoro4/1 I've changed the method to GET so you can see the result in the URL.)
My guess is that you have something else on the page with the name or id "hiddenField", other than just the hidden field you've quoted. If you change the name of the field to "fluglehorn" or something else that's (um) unlikely to be elsewhere on your page, it may well work. That's because the namespace used by getElementById is (sadly) quite crowded.
Alternately, are you sure that genarate is appearing at global scope? (E.g., it's outside of all other functions.) Because your onsubmit attribute requires that genarate be global. So this works:
<form action="#" method="get" onsubmit="genarate('hiddenField')">
<input type="hidden" id="hiddenField" name="hidden" value=""/>
<input type="submit" name="submit"/>
</form>
<script>
function genarate(hiddenField){
var field = document.getElementById(hiddenField);
field.value = "new Value";
}
</script>
but for example this would not:
<form action="#" method="get" onsubmit="genarate('hiddenField')">
<input type="hidden" id="hiddenField" name="hidden" value=""/>
<input type="submit" name="submit"/>
</form>
<script>
(function() { // Begin scoping function to avoid global symbols (not uncommon)
function genarate(hiddenField){
var field = document.getElementById(hiddenField);
field.value = "new Value";
}
})();
</script>
Also recommend using a debugger (there's no excuse for not using client-side debuggers here in 2011) to set a breakpoint on the genarate function and walk through, to see what's going wrong.
crud.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="JavaScript.js"></script>
</head>
<body>
<input type="text" name="name" id="name" onfocus="opConfig.reloadPrice()">
<button type="button" onclick="myFun()">submit</button>
<button type="button" onclick="update()">update</button>
<br><br>
<p id="table"></p>
</body>
</html>
JavaScript.js
var arr = [];
var index;
function myFun()
{
var name = document.getElementById('name').value;
arr.push(name);
table();
}
function table(){
var text = "<table border=1><tr><th>username</th><th>action</th></tr>"
for (var i = 0; i < arr.length; i++) {
text+="<tr><td>"+arr[i]+"</td><td><button
onclick=myDELE("+i+");>delete</button><button
onclick=myEdit("+i+");>edit</button></td></tr>"
}
text+="</table>";
console.log(text);
document.getElementById('table').innerHTML = text;
tablehidden();
}
function myDELE(i)
{
var name = arr.splice(i,1);
// name.splice(i,1);
console.log(name);
table();
tablehidden();
}
function tablehidden(){
if (!arr.length) { document.getElementById('table').hidden=true; }
else{document.getElementById('table').hidden=false;}
}
function myEdit(i)
{
text = document.getElementById('name').value = arr[i];
index = i;
}
function update(){
arr[index]=document.getElementById('name').value ;
table();
tablehidden();
}
I have a form
<form>
<input id="input" type="number">
<input type="submit">
</form>
I want to be able to input a number into the number and click the submit button and javascript displays a number based on the number submitted.
(My Guess is that this question is very basic but I am pretty knew to javascript.)
Here is a very simple (jquery-less) example of what you might be after:
<script type="text/javascript">
function ShowANumber() {
var currentNumber = document.getElementById("input").value;
var newNumber = currentNumber * 10 // Do something with input
document.getElementById("result").innerHTML = newNumber;
return false; // Stop form submit
}
</script>
<form onsubmit="return ShowANumber();">
<input id="input" type="text"/>
<input type="submit"/>
</form>
<div>Result: <span id="result"></span></div>
The text box should accept onli decimal values in javascript. Not any other special characters. It should not accept "." more than once. For ex. it should not accept 6.....12
Can anybody help???
You can use regex:
function IsDecimal(str)
{
mystring = str;
if (mystring.match(/^\d+\.\d{2}$/ ) ) {
alert("match");
}
else
{
alert("not a match");
}
}
http://www.eggheadcafe.com/community/aspnet/3/81089/numaric-validation.aspx
You can use Regex.test method:
if (/\d+(\.\d{1,2})/.test(myTextboxValue)) //OK...
JQuery Mask plug in is the way to go!
http://www.meiocodigo.com/projects/meiomask/#mm_demos
If you mean you do not want anything but an integer or a decimal to be typed into the field, you'll need to look at the value
as each key is pressed. To catch pasted input, check it again onchange.
textbox.onkeyup=textbox.onchange=function(e){
e= window.event? event.srcElement: e.target;
var v= e.value;
while(v && parseFloat(v)!= v) v= v.slice(0, -1);
e.value= v;
}
probably you want to validate a form input before sending it to the server. Here is some example:
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
function validate(){
var field = document.getElementById("number");
if(field.value.match(/^\d+(\.\d*)?$/)){
return true;
} else {
alert("Not a number! : "+field.value);
return false;
}
}
</script>
</head>
<body>
<form action="#" method="post" onsubmit="return validate();">
<input type="text" id="number" width="15" /><br />
<input type="submit" value="send" />
</form>
</body>
</html>
I just whipped this up. Useful?
<html>
<head>
<script type="text/javascript">
function validNum(theField) {
val = theField.value;
var flt = parseFloat(val);
document.getElementById(theField.name+'Error').innerHTML=(val == "" || Number(val)==flt)?"":val + ' is not a valid (decimal) number';
}
window.onload=function(){
validNum(document.getElementById('num'));
}
</script>
</head>
<body>
<form>
<input type="text" name="num" id="num"
onkeyup="return validNum(this)" /> <span id="numError"></span>
</form>
</body>
</html>