i need compare two values using Less Than or Greater Than, but it's not working fine. Here below my code.
//JAVASCRIPT
<script type="text/javascript">
function validform()
{
var balanvar = document.myform.balance.value,
currntvar = document.myform.currnt.value;
if( currntvar == "" ) { document.myform.currnt.focus(); document.getElementById("curntid").style.borderColor = "red"; return false; } // Must be filled error
if(currntvar > balanvar) { document.myform.currnt.focus(); document.getElementById("curntid").style.borderColor = "red"; return false; } else { document.getElementById("curntid").style.borderColor = "green"; } // Maximum value error
}
</script>
//HTML
<form name="myform" method="post" action="">
<input type="text" name="balance" id="balanceid" value="12000"/>
<input type="text" name="currnt" id="curntid"/>
<input type="submit" name="submit" value="Proceed" onclick="return validform();"/>
</form>
What i want is, i have to enter less than "balance" value in "currnt" text box, if i entered maximum value compare to "balance" text box mean, have to throw error message.
Problem Is, when clicking proceed without filling "currnt" it's showing error. and when entering value 15000 in "currnt" means its showing error. But when entering value 100000 in "currnt" means its not giving error. i don't know what error is this. please help me.
The .value property returns a string. hence you comparisons are done using string comparisons, which most of the time do yield other results than number comparisons.
To solve that, convert to numbers first using parseFloat() or parseInt():
function validform()
{
var balanvar = parseFloat( document.myform.balance.value ),
currntvar = parseFloat( document.myform.currnt.value );
if( isNaN( currntvar ) ) { document.myform.currnt.focus(); document.getElementById("curntid").style.borderColor = "red"; return false; } // Must be filled error
if(currntvar > balanvar) { document.myform.currnt.focus(); document.getElementById("curntid").style.borderColor = "red"; return false; } else { document.getElementById("curntid").style.borderColor = "green"; } // Maximum value error
}
Related
How can I make "You got it!" message to pop up when my input is not only 5, but lower or equal to 5?
document.getElementById("my-button").onclick = function() {
if (document.getElementById("my-input").value == "5") {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
}
What is my favorite numbers?
<input type="text" id="my-input">
<button id="my-button">Submit</button>
You have to convert your value to a number using Number, and then compare it using <=.
document.getElementById("my-button").onclick = function() {
if (Number(document.getElementById("my-input").value) <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
}
What is my favorite numbers?
<input type="text" id="my-input">
<button id="my-button">Submit</button>
You need to convert the input value which is a string to number before comparing it.
In this case you can use parseInt
document.getElementById("my-button").onclick = function() {
if (parseInt(document.getElementById("my-input").value, 10) <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
}
What is my favorite numbers?
<input type="text" id="my-input">
<button id="my-button">Submit</button>
The value that u get from input type is string so u need to convert it to number with [ ParseInt, Number ] methods after that u can compare and everytings will work fine so i think it's better of u
let button = document.getElementById("my-button");
let value = document.getElementById("my-input");
button.on('click', function () {
if (Number(value) <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
});
have a nice game
A slight issue with your question is that the type of the input is text rather than number. You can change the type of the input by doing <input type=number id="my-input">.
If you want to keep the type you will have to check if the input is a number.
In either case you will have to convert the value of the input from string to number since numeric operations using strings are wrong most of the time (there are rare specific cases where the outcome is the same). The only difference between using text and number is having to check if the value of the input is valid, which you can do using isNaN after the conversion. I usually prefer forcing JavaScript to convert the text by using - 0 over parseInt or parseFloat, since it's scricter and will not convert "123test" to 123.
Here is a solution working with number
document.getElementById("my-button").addEventListener("click", function() {
if (document.getElementById("my-input").value - 0 <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
});
<input type="number" id="my-input">
<button id="my-button">Submit</button>
Here is a solution working with text
document.getElementById("my-button").addEventListener("click", function() {
var value = document.getElementById("my-input").value - 0;
if (isNaN(value)) {
alert("Not a number");
} else if (value <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
});
<input type="text" id="my-input">
<button id="my-button">Submit</button>
Actually when you access the value of <input> its a string. You can't use >,<,>=,<= between strings you use need to convert it into a number using parseInt()
document.getElementById("my-button").onclick = function() {
let value = parseInt(document.getElementById("my-input").value)
if (value <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
}
What is my favorite numbers?
<input type="text" id="my-input">
<button id="my-button">Submit</button>
I have a single input field where the user can only enter a number between 2 AND 50. Anything above or below is invalid. It also MUST be a numeric value.
What I have so far is this:
$('#searchTimes').click(function() {
if($('#replyNumber').val()<=0) {
alert("Please select a value greater than 0 for number of guests");
$('#replyNumber').focus();
return;
}
if($('#replyNumber').val()>=51) {
alert("Please select a value less than or equal to 50 for number of guests");
$('#replyNumber').focus();
return;
}
if(isNaN($('#replyNumber').val())) {
alert("Please enter a numeric value only");
$('#replyNumber').focus();
return;
}
});
Is there a better more efficient way of writing that ^.
Also ... IF all of those IF statements are not true then I need to perform another function. How can I add that in?
_isValidNumber(number) {
var message;
var isValid;
switch(number){
case number >= 51:
message = "Please select a value less than or equal to 50 for number of guests";
isValid = false;
case number <= 0:
message = "Please select a value greater than 0 for number of guests";
isValid = false;
case isNumeric(number):
var message = "Please enter a numeric value only";
isValid = false;
default:
return true;
}
alert(message);
$('#replyNumber').focus()
return isValid;
}
function isNumeric(num){
return !isNaN(num)
}
var number = $('#replyNumber').val();
var numberIsValid = _isValidNumber(number);
I would try to abstract out duplicate code, like this:
<input id="replyNumber" >
<button id="searchTimes">click</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('#searchTimes').click(function() {
var val = $('#replyNumber').val()
if(val<=0) showErr("Please select a value greater than 0 for number of guests");
else if(val>=51) showErr("Please select a value less than or equal to 50 for number of guests");
else if(isNaN(val))showErr("Please enter a numeric value only");
});
function showErr(msg){
alert(msg);
$('#replyNumber').focus();
}
</script>
This is what you need :D
$('#searchTimes').on('click',function() {
var do_function = 1;
if (!$.isNumeric($('#replyNumber').val())) {
alert("Please enter a numeric value only");
$('#replyNumber').focus().select();
} else if (+$('#replyNumber').val() < 2) {
alert("Please select a value at least 2 for number of guests");
$('#replyNumber').focus().select();
} else if (+$('#replyNumber').val() > 50) {
alert("Please select a value no more than 50 for number of guests");
$('#replyNumber').focus().select();
} else {
do_function = 0;
}
if (do_function) {
call_some_function();
}
});
Good luck!
Use HTML5 min and max attributes and an input of type number (which covers the numeric part you mentioned). Use rangeOverflow and rangeUnderflow Validity Properties to check your input and present the proper error (or custom error) messages.
Try the below snippet using the following values (null (empty input),1,55) and check the custom error messages created.
function validateInput() {
var txt = "";
if (document.getElementById("inp1").validity.rangeOverflow) {
txt = "Value larger than acceptable!";
}
if (document.getElementById("inp1").validity.rangeUnderflow) {
txt = "Value smaller than acceptable";
}
if (document.getElementById("inp1").validity.valueMissing) {
txt = "Please type a number!";
}
document.getElementById("output").innerHTML = txt;
}
document.getElementById("btn").addEventListener("click", function(){
validateInput();
});
<form>
<input type="number" id="inp1" name="numberInput" min="2" max="50" required>
<button id="btn">go</button>
</form>
<div id="output"></div>
I was adding some JavaScript validation to my page and found that I couldn't find any helpful sources to tell me on how to stop numerical values and allow them on different input boxes. I am very new to JavaScript and aren't quite up to grips with it yet. I know VB has a command similar to what I am asking for: isNumeric()
Here is the code what I want to stop numerical values in:
if (document.ExamEntry.name.value=="") {
alert("You must enter your name \n");
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
alert("You must enter the subject \n");
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
Here is the code that I want to ONLY allow numerical values in:
if (document.ExamEntry.CadNumber.value.length!== 4) {
alert("Make sure you only have 4 numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}
---EDIT---
Here is what I have got so far now, it works sort of however it contstantly appears now... I was wondering if you knew anymore?
Stop Numerical values:
if (document.ExamEntry.subject.value) {
isNaN(parseInt(1));
alert("Please make sure you only have letters! \n");
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
ONLY allow numerical values:
if (document.ExamEntry.CadNumber.value) {
isNaN(parseInt(""));
alert("Please make sure you only have numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}
Look up isNaN and parseInt - they should get you started. From the JS console,
isNaN(parseInt("foo"))
true
isNaN(parseInt(12))
false
isNaN is like the opposite of your VBA isNumeric so you need to use it with parseInt on the document.ExamEntry.CadNumber.value
Use it like this:
if (isNaN(parseInt(document.ExamEntry.CadNumber.value))) {
alert("Please make sure you only have numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}
To give a small example of how it could work, you could check this small snippet.
In a sense, at the moment you submit your form, it will go to the validate function, that will then check your form for the requirements.
The numbers only / text only is implied by the type (and your browser can also help), and the error message is supplied in a title.
When one field fails, the validation stops and throws the error.
Note, if you have any other elements you want to check (like selects) you would have to do some extra work still ;)
And if you want to learn more about the element types you could set, you could check it here as well
function validate(form) {
var succeeded = true,
i, len, item, itemArray, firstErrorField;
if (!form) {
succeeded = false;
} else {
itemArray = form.getElementsByTagName('input');
for (i = 0, len = itemArray.length; i < len && succeeded; i++) {
item = itemArray[i];
switch (item.type) {
case 'text':
if ((!item.value && item.required) || !isNaN(parseInt(item.value))) {
succeeded = false;
}
break;
case 'number':
if ((!item.value && item.required) || isNaN(parseInt(item.value))) {
succeeded = false;
}
break;
}
if (!succeeded) {
firstErrorField = item.title || item.id || item.name;
}
}
}
if (!succeeded) {
alert('please check your input!\r\n' + firstErrorField);
}
return succeeded;
}
<form onsubmit="return validate(this);">
<fieldset>
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" id="name" title="name is required" required />
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input type="number" id="age" required="required" min="0" title="age is required" />
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit">Submit</button>
</td>
</tr>
</table>
</fieldset>
</form>
Hello everyone I would like to ask how to check value's length from textbox ?
Here is my code :
#*<script>
function validateForm() {
var x = document.forms["frm"]["txtCardNumber"].value;
if (x == null || x == "" ) {
alert("First name must be filled out");
return false;
}
}
</script>*#
When I run my script yeap I got alert message but I'm trying to add property which control the texbox' input length.
You could use x.length to get the length of the string:
if (x.length < 5) {
alert('please enter at least 5 characters');
return false;
}
Also I would recommend you using the document.getElementById method instead of document.forms["frm"]["txtCardNumber"].
So if you have an input field:
<input type="text" id="txtCardNumber" name="txtCardNumber" />
you could retrieve its value from the id:
var x = document.getElementById['txtCardNumber'].value;
Still more better script would be:
<input type="text" name="txtCardNumber" id="txtCardNumber" />
And in the script:
if (document.getElementById(txtCardNumber).value.length < 5) {
alert('please enter at least 5 characters');
return false;
}
i have used the following code for javascript validation, that return true or false depending on the condition
javascript block
function fnval()
{
if(document.field.value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
Here is my HTML:
<Input type=submit name="sub" onClick="return fnval()">
Thus the js block checks if the field value is entered or not. If not it throws an alert message and return false, and hence the form does not get submitted.
But in case the value is not empty it returns a true, and still the form does not get submitted.
I have seen some queries asked by people where return false results in submission of the form. But this is exactly opposite.. and am not able to find a solution as of now.
Can anyone please help me on this?
Try getElementsByName:
function fnval()
{
if(document.getElementsByName('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
getElementsByName doesn't have IE support though. Perhaps:
function fnval()
{
if(findInput('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
function findInput(name) {
var elements = document.getElementsByTagName('input'),
length = elements.length,
i = 0,
results = [];
for(i; i<length; i++) {
if (elements[i].name === name) {
results.push(elements[i]);
}
}
return results;
}
You need to add the form name and the form value. Something like:
if ( document.formName.fieldName.value == "" )
For instance, with this kind of HTML:
<form method="post" onsubmit="">
Password: <input name="password" type="text" /><br />
</form>
The js:
if (document.form.password.value == "") {
//empty
}
i suggest using onsubmit in the form, <form ... onsubmit="return fnval()">,
try adding that and placing return false at the base of your function.
no matter what you do in js. but if you have filled action tag of form element element , the form will submit.
Syntax error:
type="submit"
not
type=submit