validate a text field with only 5 value - javascript

<label class="user-reg-label fl">Percentage:<span class="required">*</span></label>
<input class="user-reg-input fl" type="text" name="Percentage[]" id="Percentage1" value="" maxlength="5" />
this is my html code.
i need to validate this input field with javascript to enter only 5 values like 99.99

This is formatting, not validating, but it seems to be what the OP is really looking for ( I think ).
var input = document.getElementById("Percentage1"),
onlyNumbers = input.value.replace(/\D/g,""), // Remove all nondigits
cleanNumbers = onlyNumbers.substr( 0, 4 ); // Limit to four digits
// Add decimal if more than two digits in length
if( cleanNumbers.length > 2 )
{
cleanNumbers = cleanNumbers.substr( 0, 2 ) + "." + cleanNumbers.substr( 2 );
}
input.value = cleanNumbers;

Using Jquery something like the below works.
Textbox
<input class="user-reg-input fl" type="text" name="Percentage[]" id="Percentage1" value="" onpaste="return false"
onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;" maxlength="6" />
Jquery
$(document).ready(function ()
{
$('#Percentage1').keyup(function (event)
{
var currentValue = $(this).val();
var length = currentValue.length;
if (length == 2)
{
$(this).val(currentValue + ".");
}
else if (length == 5)
{
$(this).val(currentValue + "%");
}
});
});
This works for your basic requirements however there are a few things that need to be improved. If a user tries to delete multiple numbers it doesn't work or if they try to use the backspace key

You can use keyup or keypress function for this
<input onkeyup="myFunction()" class="user-reg-input fl" type="text" name="Percentage[]" id="Percentage1" value="" maxlength="6" />
function myFunction()
{
var input = document.getElementById("Percentage1");
if( input.value.length > 6 )
{
alert( "too many characters" );
return false;
}
}
UPDATED:
<input type="text" id='text_field' onkeyup="check()"/>
<script>
function check()
{
var len=document.getElementById('text_field').value.length;
if (len==2)
document.getElementById('text_field').value=document.getElementById('text_field').value+".";
if (len==5)
document.getElementById('text_field').value=document.getElementById('text_field').value+"%";
}
</script>

Okay then there is a text field where only if you put "99.99%" type pattern it will validate
<script type="text/javascript">
function fnc(){
pattern=/\d+[.]+\d+[%]/g;
text=document.getElementById("atext").value;
x=pattern.test(text);
alert(x);
}
</script>
<input type="text" maxlength="6" id="atext">
<input type="button" onClick="fnc()" value="click me">

Try this one,
With Script portion
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#test').blur(function() {
if ($(this).val().match('(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)')) {
alert("Percentage Matched");//Any thing which you want
}
else
alert("Not Valid Input");
});
});
</script>
And Code for Textbox
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="test" runat="server"></asp:TextBox>
</div>
</form>

Related

HTML check user input in form for letters

Hi I am new to HTML and JavaScript. I want to check the users phone number input for any letters, and print out those letters within the error message.
I'm a bit lost at the moment, can I save input as a string (as shown by the pseudo code saving input as InsertLetter). As well as put any string characters that are letters into an error message?
<form onsubmit="return isnumb()">
<label for="ph"> Enter Phone: </label>
<input type="text" id="phnumb"> <span
id="message"></span>
//InsertLetter = phnumb output
</form>
<script>
function isnumb() {
if (document.getElementById("phnumb").match =([a-z]))
{document.getElementById("message").innerHTML =
"<em> Number includes letter" + InsertLetter + "</em>";
return false;}
else return true;
It is far better to use <input type="tel"> in this situation. On that occasion user input should follow the given pattern which you can check with. Use Form Validation for the rest of the work, for example:
const phone = document.getElementById("phone");
const button = document.getElementsByTagName('button')[0];
const errorMessage = document.querySelector('p.error');
button.addEventListener('click', (e) => {
if (!phone.validity.valid) {
showError();
e.preventDefault();
}
});
phone.addEventListener('keyup', (e) => {
if (phone.validity.valid) {
errorMessage.innerHTML = '';
} else {
showError();
}
});
function showError() {
if (phone.validity.valueMissing) {
errorMessage.textContent = "Phone is required";
}
if (phone.validity.patternMismatch) {
errorMessage.textContent = "You are not supposed to use characters like this one: " + phone.value;
}
if (phone.validity.valid) {
phone.setCustomValidity("");
}
}
.error {
color: red;
}
<form>
<label for="phone">Phone Number (Format: +99 999 999 9999)</label>
<input type="tel" id="phone" name="phone" pattern="[\+]\d{2}[\s]\d{3}[\s]\d{3}[\s]\d{4}" required>
<p class="error"></p>
<button>Submit</button>
</form>
First of all i want to give u an answer of user should insert only number :`
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submitForm() {
var phonenumber = document.forms["myForm"]["notanumber"].value;
if (isNaN(phonenumber)) {
alert("only number required");
} else {
alert("submit");
}
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" id="notanumber" />
<input type="submit" onclick="submitForm()" />
</form>
</body>
</html>
-> isNaN() is an inbuilt function in js, if variable is not a number, it return true, else return false.
the simple code :
restric the user from clicking any key, Only numbers allowed.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submit() {
alert("submited");
}
function noAlphabets(e) {
var phonenumber = document.forms["myForm"]["notanumber"].value;
var x = e.which || e.keycode;
if (x >= 48 && x <= 57) {
return submit();
} else {
alert("insert only numbers");
return false;
}
}
</script>
</head>
<body>
<form id="myForm">
<input
type="text"
id="notanumber"
onkeypress="return noAlphabets(event)"
/>
<button type="button" onclick="submit()">Submit</button>
</form>
</body>
</html>

Counter char script for many fields

Hi I want use this script to count char in form with many fields,
but not want duplicate code, I want use only one code for all fields,
how can pass to javascript name fields count and display this count...
As one counter for many fields input type...
thanks
Salvatore
<script>
function countChar(val) {
var len = val.value.length;
if (len >= 66) {
val.value = val.value.substring(0, 66);
} else {
$('#charNum').text(65 - len);
}
};
</script>
<div id="charNum"></div>
<input type="text" name="name_var1" value="" maxlength="66" onkeyup="countChar(this)" />
<div id="charNum"></div>
<input type="text" name="name_var2" value="" maxlength="66" onkeyup="countChar(this)" />
<div id="charNum"></div>
<input type="text" name="name_var3" value="" maxlength="66" onkeyup="countChar(this)" />
the problem is that you are using ids several times. Try to work with classes and generate the selectors from the class name of the element.
<script>
function countChar(val) {
var len = val.value.length;
if (len >= 66) {
val.value = val.value.substring(0, 66);
} else {
$('.' + val.className + '_charNum').text(65 - len);
}
};
</script>
<div class="name_var1_charNum"></div>
<input class="name_var1" type="text" name="name_var1" value="" maxlength="66" onkeyup="countChar(this)" />
<div class="name_var2_charNum"></div>
<input class="name_var2" type="text" name="name_var2" value="" maxlength="66" onkeyup="countChar(this)" />
<div class="name_var3_charNum"></div>
<input class="name_var3" type="text" name="name_var3" value="" maxlength="66" onkeyup="countChar(this)" />
As far as I understood you do need to display characters left value for each field (depending on max-length) and restrict user from adding extra characters (more than allowed limit). Probably that's what you need.
<div class="countable-item">
<div class="char-num"></div>
<input type="text" name="any" class="countable" max-length="66" />
</div>
<div class="countable-item">
<div class="char-num"></div>
<input type="text" name="any2" class="countable" max-length="66" />
</div>
<script>
(function($){
var restrictMaxLength = function () {
var maxLength = $(this).attr('max-length'),
currentValue = $(this).val(),
currentLength = currentValue.length;
if (currentLength >= maxLength) {
return false;
}
},
displayCountCharacters = function () {
var maxLength = $(this).attr('max-length'),
currentValue = $(this).val(),
currentLength = currentValue.length;
$(this).closest('.countable-item')
.find('.char-num')
.text(maxLength - currentLength);
};
$(document)
.on('keypress', '.countable', restrictMaxLength)
.on('keyup', '.countable', displayCountCharacters);
})(jQuery);
</script>

getting values to populate a text instead of the span

I have pieced together a script that adds the values in text boxes and displays the sums in a span. I have tried a ton of things, but I can not get it to display the sums in a input textbox. Here is a fiddle that I have been working in ..
http://jsfiddle.net/elevationprint/MaK2k/17/
Basically I want to change the spans to input text boxes. If anyone can take a look and let me know what I am missing, I would appreciate it!
The code is this
HTML
Red<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br>
Blue<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br><br>
Total = <span class="qty12lable"></span> x $.95<br>
Total = <span class="qty24lable"></span> x $1.40<br>
SCRIPT
$('.qty12').keyup(function(){
var qty12Sum=0;
$('.qty12').each(function(){
if (this.value != "")
qty12Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty12lable").text(qty12Sum);
//console.log(amountSum); });
$('.qty24').keyup(function(){
var qty24Sum=0;
$('.qty24').each(function(){
if (this.value != "")
qty24Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty24lable").text(qty24Sum);
//console.log(amountSum); });
You can target the input fields like so:
Total = <input class="qty12lable" value=""> x $.95<br>
Total = <input class="qty24lable" value=""> x $1.40<br>
$("input.qty12lable").val(qty12Sum);
$("input.qty24lable").val(qty24Sum);
To set the text (value) of a textbox you have to use .val() not .text(). Like this:
$('.qty12').keyup(function() {
var qty12Sum = 0;
$('.qty12').each(function() {
if (this.value != "")
qty12Sum += parseInt(this.value);
});
$(".qty12lable").val(qty12Sum);
});
$('.qty24').keyup(function() {
var qty24Sum = 0;
$('.qty24').each(function() {
if (this.value != "")
qty24Sum += parseInt(this.value);
});
$(".qty24lable").val(qty24Sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Red
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>Blue
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>
<br>Total = <input class="qty12lable"/> x $.95
<br>Total = <input class="qty24lable"/> x $1.40
<br>
This snippet has some logic about how you can attach event listeners on input fields and how you can get their values. It's not perfect and has quite a few bugs from production level perspective but this will give a hint about how you can listen and manipulate DOM using Jquery. Which is what Jquery is all about.
$( "input" )
.change(function () {
var prevVal = ($('#total').html() !== '') ? $('#total').html() : 0;
if(parseInt($(this).val()) === NaN) {
return;
}
$('#total').html(parseInt($(this).val()) + parseInt(prevVal));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="1"></input><br>
<input type="text" id="2"></input><br>
<hr>
Total = <span id="total" class="qty12lable"></span> <br>

Validate Numbers Javascript

I have written the code so far and came up with this. I have to
Make sure the user input numbers into the text boxes and I was given errors using the Xhtml format, one, the '&&' sign gave me errors and due to online help, I was told I needed to use //
As I student learning Javascript I have no idea what this is or means, but as I placed it there, I was given more errors and my code crashed up after the javascript was added.
Thanks for the help in advance
<head>
<script type = 'text/javascript'>
// <![CDATA[
$('#submit').click(function(){
validateRange();
validateRa();
})
function validateRange() {
var txtVal = document.getElementById("CustomerID").value;
var txtVal1=parseInt(txtVal);
if (txtVal1 >= 3000 && txtVal1 <= 3999) {
return true;
}
else {
alert('Please enter a number between 3000-3999');
return false;
}
}
function validateRa() {
var txtVal1 = document.getElementById("AcctNo").value;
var txtVal2=parseInt(txtVal1);
if (txtVal2 >= 90000 && txtVal2 <= 99999) {
return true;
}
else {
alert('Please enter a number between 90000-99999');
return false;
}
}
// ]]
</script>
<title>Account Lookup</title>
</head>
<body>
<h1> Please Provide Your Information</h1>
<p><input type="text" id="AcctNo" value="Account Number"/></p>
<p><input type="text" id="CustomerID" value="CustomerID" onchange="validateRange()"/></p>
<p><input type="text" name="Type" value="Account Type" onchange="validateRange()"/></p>
<p><input type="text" name="balance" value="Balance"/></p>
<p class="submit" />
<input type="submit" name="commit" value="Submit" id="submit" /><button type="reset" value="Clear">Clear</button></p>
</body>
</html>
EDITED
try using this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
validateRange();
validateRa();
});
});
function validateRange() {
var txtVal = document.getElementById("CustomerID").value;
var txtVal1=parseInt(txtVal);
if (txtVal1 >= 3000 && txtVal1 <= 3999) {
return true;
}
else {
alert('Please enter a number between 3000-3999');
return false;
}
}
function validateRa() {
var txtVal1 = document.getElementById("AcctNo").value;
var txtVal2=parseInt(txtVal1);
if (txtVal2 >= 90000 && txtVal2 <= 99999) {
return true;
}
else {
alert('Please enter a number between 90000-99999');
return false;
}
}
</script>
<html>
<title>Account Lookup</title>
<body>
<h1> Please Provide Your Information</h1>
<p><input type="text" id="AcctNo" value="Account Number"/></p>
<p><input type="text" id="CustomerID" value="CustomerID" onchange="validateRange()"/></p>
<p><input type="text" name="Type" value="Account Type" onchange="validateRange()"/></p>
<p><input type="text" name="balance" value="Balance" /></p>
<p class="submit" />
<input type="submit" name="commit" value="Submit" id="submit" /><button type="reset" value="Clear">Clear</button></p>
</body>
</html>
BTW the function validateRa missing the closing curly braces you need to add } before // ]]
function validateRa() {
var txtVal1 = document.getElementById("AcctNo").value;
var txtVal2=parseInt(txtVal1);
if (txtVal2 >= 90000 && txtVal2 <= 99999) {
return true;
}
else {
alert('Please enter a number between 90000-99999');
return false;
}
} //<= this is missing in your code
// ]]

Checking the value while typing in textbox

If say i am having a textbox input and a integer value A then how to check at time of typing the data itself that the value entered in textbox does not exceed A.
Textbox :
<input type="textbox" name="mynumber">
My script :
(According to answer by Felix)
<script type="text/javascript">
<%int n=(Integer)request.getAttribute("n");%>
var A=<%=n%>;
$('input[name^=txtDynamic_]').keyup(function () {
if (+this.value > A) {
$(this).next().html('Greater than Total shares');
flag=1;
}
else{
$(this).next().html('');
}
});
</script>
FORM :
<FORM METHOD=POST ACTION="stegnographyonshares" enctype="multipart/form-data">
<c:forEach var="i" begin="1" end="${myK}">
Enter The ${i} share number: <input type="text" name="txtDynamic_${i}" id="txtDynamic_${i}" /><span></span>
<br />
<br>
</br>
</c:forEach>
<br></br>
<INPUT TYPE="file" NAME="file" value="file">
<br></br>
<INPUT TYPE="submit" value="SAVE">
</form>
Whats problem in this ? the script code is not running and not printing the error message.Please help
You can use .keyup() event:
$('input[name=mynumber]').keyup(function() {
if(this.value.length > A) {
console.log('Toal characters exceed A')
}
});
Fiddle Demo
Based on your comment, you can do:
$('input[name=mynumber]').keyup(function() {
if(+this.value > A) {
console.log('Number exceed A');
}
});
Fiddle Demo
//length of text
var Count = 10;
//set id of your input mynumber
$("#mynumber").keyup(function(){
if($(this).val().length() > Count) {
$(this).val().subString(0,Count);
}
});
Do this:
var A = 10;
$('[name="mynumber"]').keyup(function () {
if (parseInt($(this).val(), 10) > A) {
alert("More than A");
} else {
alert("Less than A");
}
});
Demo
Can even be done using HTML5 output tag
<form oninput="x.value = parseInt(a.value) > 10 ? 'Greater than 10' : 'Less than 10' ">
<input type="range" id="a" value="">
<output name="x" for="a"></output>
</form>
Fiddle
Reference

Categories

Resources