I have issues with my JavaScript - javascript

I don't what happen with my script can i please point out where is my mistake. 1 to 9 all condition working fine but when you put 10-12 is not work
<form method="post" enctype="multipart/form-data" action="#">
<input type="hidden" value="2" id="itemstock" name="itemstock">
<input value="1" name="quantity" id="quantity" class="text">
<button type="submit" onClick="return checkoption();" >Click </button>
</form>
Javascript
function checkoption()
{
var itemqty = document.getElementById('quantity');
var iss = document.getElementById('itemstock');
if(itemqty.value > iss.value)
{
alert('We have Currently '+iss.value+' In Stock');
}
else
{
alert('add to cart');
}
}
Thank you in advance
Screen short see qty i put 13 but its not showing error

Using the < or > operators with strings will compare the values alphabetically, which is probably not what you want.
You need to compare these as numbers, not as strings. JavaScript allows you to easily cast a string to a number using +, like so:
var qty = +itemqty.value;
var isv = +iss.value;
if(qty > isv)
{
// ...
}
However, you can also use parseInt (which will return NaN if the value is invalid) if you want to add more error checking in your code.

The .value attribute on a text field such as input is a string, not a number. Therefore, you compare strings lexicographically. Change them into numbers, either via parseInt(str, 10) or via +str.

Related

The input from client side should entered only digits, if is alphabets should give an error msg

Create an html page with the following form:
<form method="post" name="example" action="">
<p> Enter your name <input type="text"> </p>
<input type="submit" value="Submit Information" />
</form>
<div id="a"></div>
Add a js validation function to the form that ensures that you can only add numbers in the textbox If you enter alphabets, you should generate an error message in the given div. -->
I run the requirement successfully and I'm giving the error message when it entered alphabets. However, it's giving me the same error message when I enter digits as well. Please kindly show how the function or the window.onload should be implemented. Thank you.
My answer is down below;
window.onload = function() {
let form = document.getElementById('form_ref')
form.onsubmit = function() {
let user = form.user.value;
if (parseInt(user) !== user) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
return true;
}
}
<form id="form_ref" method="post" name="example" action="">
<label for="username">User</label><input type="text" name="user" id="username" required>
<div id="a"></div>
<br>
<input type="submit" value="Submit Information" id="submit">
</form>
Your equality check parseInt(user) !== user will always return true because form.user.value is a string but parseInt(...) always returns an integer. If you want to check if the entry is an integer there are a couple ways.
You can change the input's type attribute to number to make sure only digits can be entered and then you just have to make sure it's an integer and not a decimal (type="number" still allows decimal numbers so not just digits). user will still be a string, but it's easier to check. I'd recommend using Number.isInteger(...) to do the checking:
if (!Number.isInteger(parseFloat(user))) {
If you really want to use type="text" you can iterate through user and make sure its characters are all digits:
for(let i = 0; i < user.length; i++) {
if("0123456789".indexOf(user[i]) == -1) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
}
return true;
One advantage of this method is that you can make more characters available if you want to just by adding them to the string that's searched in the iteration. A disadvantage is that it's slower than the other method (the indexOf method has to iterate through the string for every character of user), but for your use case that seems irrelevant-- this function doesn't need to be called many times per second as it's a simple login type of thing, and it's client-side so you don't need to handle many instances at once. If speed is an issue you could probably make a comparison to the integer equivalencies of the characters:
if(user.charCodeAt(i) < "0".charCodeAt(0) || user.charCodeAt(i) > "9".charCodeAt(0)) {

Limit the user's input in an input number to 4 digits

How can I prevent (usign maybe Angular) the user from entering more than 4 numbers in a an simple number like this one :
<input type="number">
I used ng-maxlength, and max attributes, but those attributes as specified by w3.org specs and the official website Angular, do not prevent the user from adding more numbers.
What I want is that the input stops in 4 digits, like adding in somehow a mask or something to it.
Here is a way to do it using JavaScript:
HTML
<input type="number" oninput="checkNumberFieldLength(this);">
JavaScript
function checkNumberFieldLength(elem){
if (elem.value.length > 4) {
elem.value = elem.value.slice(0,4);
}
}
I would also suggest to make use of the min and max HTML attributes for the input Number element, if it applies in your case.
JSFiddle
W3c: input Number
Well, as somebody stated above maxlength doesn't work with inputs of type number, so you can do it this way:
<input type="text" pattern="\d*" maxlength="4">
of course, this will do if it's not a requirement to have input type="number"
Using ng-pattern with a regex
\d : digits
{4} : 4 times
<input type="number" ng-pattern="/^\d{4}$/" />
I would create a function in your controller like this
angular.module("my-app", [])
.controller('my-controller', function($scope) {
$scope.checkInput = function() {
if (input.value.length > 4) {
input.value = input.value.slice(0,4);
}
});
});
Then in your view you can do something like this
<input type="number" max="9999" ng-input="checkInput()" />
Warning: The max attribute will only work for the spinner. The user will still be able to enter numbers higher than that. Here's an example
<input type="number" max="9999" />
You can do that using modernizr and jquery.
I've made an example here: https://jsfiddle.net/5Lv0upnj/
$(function() {
// Check if the browser supports input[type=number]
if (Modernizr.inputtypes.number) {
$('input[type=number]').keypress(function(e) {
var $this = $(this),
maxlength = $this.attr('maxlength'),
length = $this.val().length;
if (length >= maxlength)
e.preventDefault();
});
}
});

How can i validate form with JavaScript

I want to create a form and want to validate user input, if user fill both text box i want to show an alert box, also if user fill one and left empty another one i want to show an alert box to let them know that they are missing one box. How i can do it with JavaScript, please help.
I want two text box, if user fill both text box and click enter i want to show an alert box telling them "Correct", if user fill one and left another empty i want to show an alert box telling them that it is "Incorrect".
How i can do it, help.
<form action="" method="post">
<input type="text" name="text1" placeholder="Text 1">
</br>
<input type="text" name="text2" placeholder="Text 2">
</br>
<input type="submit" value="Enter">
</form>
What kind of validation are you interested in ?
You can do everything with javascript my friend:).
This is pure javascript. To make it simple, I kept the html and js in one file. I also added a name to a form as you see below, in case you would have multiple forms.
<html>
<body>
<form name="LovelyForm" action="" method="post">
<input type="text" name="text1" placeholder="Text 1"> </br>
<input type="text" name="text2" placeholder="Text 2"> </br>
<input type="submit" onclick="validateForm()" value="Enter">
</form>
<script type="text/javascript">
function validateForm() {
var x = document.forms["LovelyForm"]["text1"].value;
var y = document.forms["LovelyForm"]["text2"].value;
if (x == null || x == "" || y == null || y == "") {
alert("Fill me in");
return false;
}else{
alert("Good");
return true;
}
}
</script>
</body>
</html>
Validation with javascript is the most flexible way and works with all browsers, if you learn JQuery you will be able to improve the user experience limit less.
If you don't want to javascript then use the new improved input validation options with Html 5, they will work with most browsers and not break the ones without Html5 support.
Here: Best practice as I see it :)
Only validate the most necessary on client side.
Avoid compulsory input unless they realy are.
Don't refuse space, hyphens, commas, dots and so on if you absolutely don't have to. People like to cut and paste. You can always clean on server side.
Don't limit input length/size if you don't have to. Again people like to cut and paste and many times the input is to long just because it contains blank spaces.
Most important of all. You must always validate on server side, to make sure your data won't get corrupted. Client validation is only to improve the users experience and not a substitute.
Here's a JSFiddle that should work with IE < 9: http://jsfiddle.net/ayr7yov7/1/
form.elements['one'].value may cause issues if the inputs are not of type text.
The code:
<script>
function trim(str) {
if(!str) return '';
return str.replace(/\s{2,}/g, '');
}
function valid(form) {
var v1 = trim(form.elements['one'].value),
v2 = trim(form.elements['two'].value);
if (v1 === '') {
alert('one');
return false;
}
if (v2 === '') {
alert('two');
return false;
}
alert('full!')
return true;
}
</script>
<form action="/echo/json/" onsubmit="return valid(this)">
<input name="one" type="text" />
<input name="two" type="text" />
<input type="submit" />
</form>
First step is to give JavaScript an easy way to reference the element in the DOM. Generally, the easiest way is to give each element you need to reference a unique ID.
<input id="num1" />
<input id="num2" />
Then, JavaScript can access the inputs with the getElementById() method of the document object (the "D" from DOM).
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
Now, i1 and i2 contain a reference to their respective input objects (the "O" from DOM). Every form element object has a value attribute that contains the current value of it's input.
var val1 = i1.value;
var val2 = i2.value;
Now var1 and var2 contain the value of the input. All you have to do is check and see if they both have a value that isn't empty.
if(
// if the first value does not equal an empty string ""..
val1 != ""
// and the second value does not equal an empty string ""..
&& val1 != ""
)
// then alert 'correct'
alert("correct");
// or else, alert 'incorrect'
else alert('incorrect');
Now you can throw it in a function and make it run when the form is submitted by attaching it to an event handler. When you're just starting it's easiest to use an onsubmit attribute, which takes the name of a function and calls that function when the form is submitted.
<form action="#" onsubmit="validate()">
<input id="num1" />
<input id="num2" />
<input type="submit" />
</form>
<script>
function validate(){
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
var val1 = i1.value;
var val2 = i2.value;
if(val1 != "" && val2 != "") alert("correct");
else alert("incorrect");
}
</script>

Strip data to number and decimal then jquery set input value to variable

I'm taking data from an encrypted php script which outputs variables as e.g. %%Price%%
Annoyingly those variables are not just a decimal and numeric value.
The encrypted script renders %%Price%% as:
<font color="green"><strong>Sale Price: $2,489.99</strong></font>
I want to strip the value of %%Price%% to price (number and decimal) and then place that result in a hidden form field as the value.
I have tried:
<form id="add-to-cart">
<input type="hidden" name="price" id="price" value=""/>
<button type="submit"> Review & Order</button>
</form>
<script>
var price = "%%Price%%";
var newPrice = price.replace(/[^0-9\.]/g, '');
jQuery("#price").val(newPrice);
</script>
...but this gives an empty result
I would use:
newPrice = parseFloat(price.substring(2, price.length - 3));
I checked your code with a jsfiddle and it seems ok. Check here: http://jsfiddle.net/CmHn6/1/. I actually replaced:
var price = "%%Price%%";
with:
var price = '<font color="green"><strong>Sale Price: $2,489.99</strong></font>';
as you said in your example. Notice that I used single quotes there. If your encrypted script does not take this into account, your line could end up like:
var price = "<font color="green"><strong>Sale Price: $2,489.99</strong></font>";
which would result in a syntax error and would not fill in your input element.
If your string never use single quotes, then you can use single quotes in your code, like in my example.
If not, you could put %%Price%% inside a hidden div, and read this value from there:
<div id="pricediv" display="style: none">%%Price%%</div>
<form id="add-to-cart">
<input type="hidden" name="price" id="price" value=""/>
<button type="submit"> Review & Order</button>
</form>
<script>
var price = $("#pricediv").html();
var newPrice = price.replace(/[^0-9\.]/g, '');
jQuery("#price").val(newPrice);
</script>

Don't process the <form> if the <input> DOESN'T contain an underscore

Form:
<form action="goto.php" method="post" name="myform" id="myform" onsubmit="return formSubmit(this);" class="form-wrapper cf">
<input name="statusid" autocomplete="off" id="statusid" placeholder="Enter ID Here" type="text">
<input name="submit_btn" class="submit" id="submit_btn" value="" placeholder="submit" >
</form>
Demo - http://jsfiddle.net/FEF7D/4/
Some users submit an ID that has only numbers in it (e.g. 981734844).
And some users submit an ID that has underscore "_" (without quotes) in it (e.g. 28371366_243322).
What I want to do is NOT allowing the users that submit an ID with ONLY numbers in it (e.g. 89172318) to process the form action.
In other words:
82174363278423: Don't allow to process the form action
21489724893249_2918423: Allow to process the form action
Is it possible to do that?
Thanks in advance.
Try this...
function formSubmit(form) {
// create a regex to test for the numbers + underscore + numbers pattern
var rx = /^\d+_\d+$/,
test = rx.test(form.statusid.value);
test || alert('You need to enter an ID with underscore in it.');
return test;
}
Demo - http://jsfiddle.net/FEF7D/7/
you need to use java script validation and in that you can use following code:
if ( String.indexOf('_') != -1 ) {
// your form processing code..
}
Yes you can do that. There are a number of solutions. For example, you can split your input string into an array using the underscore as the split divider and if your array has two entries, you know you've got a single underscore. e.g. Something like this (untested snippet to illustrate - you also need to add numeric checks for each part of the array so you probably want to assign the split to a variable if going with this approach):
$('form').submit(function(event)
{
if (myinputvar.split('_').length ! = 2)
{
event.preventDefault();
return false;
}
// do the rest of your submission here
});
You can do any form validation in onsubmit of form.
HTML
<form name="myform" id="myform" onsubmit="return formSubmit(this);" class="form-wrapper cf" action="goto.php" method="post">
<input name="statusid" autocomplete="off" id="statusid" placeholder="Enter ID Here" type="text">
<input type="submit" name="submit_btn" class="submit" id="submit_btn" value="" placeholder="submit" >
</form>
JavaScript
// Do validation of form
function formSubmit(formObj) {
// Only allowable character is numeric or underscore
if (!/^[_0-9]*$/.test(formObj.statusid.value)) {
return false;
}
return true;
}
The two answers above will work (just strip out Neil's jquery).
Another option is
function formSubmit(form){
var statusid=document.getElementById("statusid");
if(statusid.value.search("_")===-1){
alert('ID must have an underscore "_".');
}
};
unfortunately, for some reason I can't get that to work with jsfiddle, it's telling me formSubmit is not a function, but clearly it is. Either way, javascript has a 'search' method on strings.

Categories

Resources