var tbv = document.getElementById("inputFrom");
var tbb = document.getElementById("inputTo");
var submit_check = document.getElementById("checkValues");
function blr() {
var von = tbv.value;
var bis = tbb.value;
console.log(von);
console.log(bis);
if (von >= bis || bis <= von) {
checkValues.disabled = true;
} else {
checkValues.disabled = false;
}
}
tbv.addEventListener("blur", blr);
tbb.addEventListener("blur", blr);
From: <br>
<input type="text" class="form-control" pattern="(|-)?[0-9]{0,3}?" title="Min: -100" id="inputFrom" />
<br> To: <br>
<input type="number" class="form-control" pattern="(|-)?[0-9]{0,3}?" title="Max: 300" id="inputTo" />
<br>
<button type="submit" class="btn btn-primary" id="checkValues"> Check </button>
As I explained above, I want to check if the value of the input "From" is greater or equal to the input "To".
The thing is, this works only by checking digit for digit, so that if input "From" has the value 12 and input "To" has the value 1, it is correct.
Anyone an idea what I´m doing wrong?
Try this
function blr() {
var von = parseint(tbv.value);
var bis = parseint(tbb.value);
console.log(von);
console.log(bis);
if (von >= bis) {
checkValues.disabled = true;
} else {
checkValues.disabled = false;
}
}
tbv.addEventListener("blur", blr);
tbb.addEventListener("blur", blr);
I have jsut parse the input as Integer and then compare, and there is no need to compare in both direction like a>=b and b<=a .-silly
By default .value returns a string, so use parseInt() to parse the value into a number.
Note: von >= bis and bis <= von means the same. Use of any one is enough.
var tbv = document.getElementById("inputFrom");
var tbb = document.getElementById("inputTo");
var submit_check = document.getElementById("checkValues");
function blr() {
var von = parseInt(tbv.value);
var bis = parseInt(tbb.value);
console.log(von);
console.log(bis);
if (von >= bis) {
checkValues.disabled = true;
} else {
checkValues.disabled = false;
}
}
tbv.addEventListener("blur", blr);
tbb.addEventListener("blur", blr);
From: <br>
<input type="text" class="form-control" pattern="(|-)?[0-9]{0,3}?" title="Min: -100" id="inputFrom" />
<br> To: <br>
<input type="number" class="form-control" pattern="(|-)?[0-9]{0,3}?" title="Max: 300" id="inputTo" />
<br>
<button type="submit" class="btn btn-primary" id="checkValues"> Check </button>
Javascript is loosely typed. It's variables get their type when data is loaded the first time, but can change type during their lifetime.
When you create a variable and load it with data from an input, it's considered a string, and string comparison is made character by character, not as a whole.
If you convert your values to int or float, using parseInt() or parseFloat() you'll have your problem solved.
Well for a start you don't need the OR part of this - (von >= bis || bis <= von) - you can just use (von >= bis).
If the values are always going to be numeric, then you can simply cast them by putting a plus before them, like so:
if (+von >= +bis) {
checkValues.disabled = true;
} else {
checkValues.disabled = false;
}
Use parseInt(). Since you get the value of textbox as string, you need to convert the string to number
var tbv = document.getElementById("inputFrom");
var tbb = document.getElementById("inputTo");
var submit_check = document.getElementById("checkValues");
function blr() {
var von = parseInt(tbv.value);
var bis = parseInt(tbb.value);
console.log(von);
console.log(bis);
if (von >= bis) {
checkValues.disabled = true;
} else {
checkValues.disabled = false;
}
}
tbv.addEventListener("blur", blr);
tbb.addEventListener("blur", blr);
From: <br>
<input type="text" class="form-control" pattern="(|-)?[0-9]{0,3}?" title="Min: -100" id="inputFrom" />
<br> To: <br>
<input type="number" class="form-control" pattern="(|-)?[0-9]{0,3}?" title="Max: 300" id="inputTo" />
<br>
<button type="submit" class="btn btn-primary" id="checkValues"> Check </button>
Agree with David Thomas. You need to convert string to a number.
Since you already have regular expression on your input box try using Number object to convert your string literal to Number and then compare.
function blr() {
var von = Number(tbv.value);
var bis = Number(tbb.value);
console.log(von);
console.log(bis);
if (von >= bis) {
checkValues.disabled = true;
} else {
checkValues.disabled = false;
}
}
For more detail on Number object visit
this link
Related
I´m trying to do different javascript validations before sending a form, the problem is that I haven´t been able to prevent the form from submit, it checks the conditions and sends alerts when a conditions hasn´t been satisfied but it sends the form anyways. I want the button to either be disabled until everything is right or send a message telling user, to check the cuenta.
Thanks in advance. This is my code:
<form action="<?php echo base_url();?>index.php/Datos/agregar" method="post">
Enter CLABE account:
<input name="clabe" id="clabe" type = "text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente"/>
<input type="text" name="control" id="control" maxlength="1" size="2" required >
Again:
<input name="clabe2" id="clabe2" type = "text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente"/>
<input type="text" name="control2" id="control2" maxlength="1" size="2" required>
<hr>
Bank: <input type="text" name="Banco" id="Banco" readonly required onmousemove="comparaclabe();" >
<hr>
Observations: <input type="text" name="Observaciones" id="Observaciones" required>
<hr>
<input type="submit" id="myBtn" value="Guardar Cambios" onclick ="return compareclabe();" ><span id="msg"></span>
<hr>
<input type="hidden" id="cve_banco" name="cve_banco">
</form>
<hr>
<script>
function compareclabe(){
document.getElementById("myBtn").disabled = true;
var x1 = document.getElementById("clabe").value;
var x2 = document.getElementById("control").value;
var x3 = x1 + x2;
var z1 = document.getElementById("clabe2").value;
var z2 = document.getElementById("control2").value;
var z3 = z1 + z2;
if( x3 != z3){
alert("keys are not equal");
return false;
}else if (x3 == z3){
this.someFunc(); //I want to call function someFunc and then
if the result is true, execute the next code
if (true){
var cBanco = String(x3).charAt(0) + String(x3).charAt(1) + String(x3).charAt(2);
var x = cBanco;
switch (x) {
case "012":
text = "BBVA BANCOMER";
break;
case "014":
text = "SANTANDER";
break;
case "032":
text = "IXE";
break;
default:
text = "No value found";
}
document.getElementById("Banco").value = text;
document.getElementById("myBtn").disabled = false;
return true;
}
}else{
return false;
}
}
function someFunc() {
//myFunction2();
var x = document.getElementById("clabe2").value;
f2(x,'37137137137137137');
//return true;
}
function f2(a, b) {
var cad = Array.from(a, (v, i) => v * b[i] % 10).join('');
//se suman todos los digitos del array
var value = cad,
sum = value
.toString()
.split('')
.map(Number)
.reduce(function (a, b) {
return a + b;
}, 0);
//separate last digit from result
var number = sum;
// convert number to a string, then extract the first digit
var one = String(number).charAt(1);
// convert the first digit back to an integer
var one_as_number = Number(one);
var digito_control = (10 - one_as_number);
if (digito_control === 10 ) {
digito_control = 0;
var dg = digito_control;
}else{
dg = digito_control;
}
var z = document.getElementById("control2").value;
if (dg != z){
alert("checkig digit is not equal");
return false;
}
else if (dg == z){
alert("checkig digit is equal");
return true;
}
}
</script>
I changed form submit button type to "button" and if all the validations are passed, then submit form from javascript. See below code
function compareclabe() {
document.getElementById("myBtn").disabled = true;
var x1 = document.getElementById("clabe").value;
var x2 = document.getElementById("control").value;
var x3 = x1 + x2;
var z1 = document.getElementById("clabe2").value;
var z2 = document.getElementById("control2").value;
var z3 = z1 + z2;
if (x3 != z3) {
alert("keys are not equal");
return false;
} else if (x3 == z3) {
this.someFunc(); //I want to call function someFunc and then if the result is true, execute the next code
if (true) {
var cBanco = String(x3).charAt(0) + String(x3).charAt(1) + String(x3).charAt(2);
var x = cBanco;
switch (x) {
case "012":
text = "BBVA BANCOMER";
break;
case "014":
text = "SANTANDER";
break;
case "032":
text = "IXE";
break;
default:
text = "No value found";
}
document.getElementById("Banco").value = text;
document.getElementById("myBtn").disabled = false;
$('#form').submit(); //submit form if all validation succeeds
}
} else {
return false;
}
}
function someFunc() {
//myFunction2();
var x = document.getElementById("clabe2").value;
f2(x, '37137137137137137');
//return true;
}
function f2(a, b) {
var cad = Array.from(a, (v, i) => v * b[i] % 10).join('');
//se suman todos los digitos del array
var value = cad,
sum = value
.toString()
.split('')
.map(Number)
.reduce(function(a, b) {
return a + b;
}, 0);
//separate last digit from result
var number = sum;
// convert number to a string, then extract the first digit
var one = String(number).charAt(1);
// convert the first digit back to an integer
var one_as_number = Number(one);
var digito_control = (10 - one_as_number);
if (digito_control === 10) {
digito_control = 0;
var dg = digito_control;
} else {
dg = digito_control;
}
var z = document.getElementById("control2").value;
if (dg != z) {
alert("checkig digit is not equal");
return false;
} else if (dg == z) {
alert("checkig digit is equal");
return true;
}
}
<form action="<?php echo base_url();?>index.php/Datos/agregar" method="post" id="form"> <!-- I included an id to form -->
Enter CLABE account:
<input name="clabe" id="clabe" type="text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente" />
<input type="text" name="control" id="control" maxlength="1" size="2" required> Again:
<input name="clabe2" id="clabe2" type="text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente" />
<input type="text" name="control2" id="control2" maxlength="1" size="2" required>
<hr> Bank: <input type="text" name="Banco" id="Banco" readonly required onmousemove="comparaclabe();">
<hr> Observations: <input type="text" name="Observaciones" id="Observaciones" required>
<hr>
<input type="button" id="myBtn" value="Guardar Cambios" onclick="return compareclabe();"><span id="msg"></span>
<hr>
<input type="hidden" id="cve_banco" name="cve_banco">
</form>
<hr>
But there are many validation plugins where you can easily implement. No need to code from begining. Refer this for an example -> https://jqueryvalidation.org/
You can disable the button by default, and add event listeners to all the inputs in your form. But be weary of other ways to submit the form, like the enter key. I would add an onsubmit function just to prevent all ways the event can happen when you don't want it to.
const form = document.querySelector('form')
const inputs = [...form.querySelectorAll('input')] // convert node list to array
const isValid = () => {
let valid = false
disableButton()
// handle your conditions here
if (valid) enableButton()
return valid;
}
inputs.forEach( input => input.addEventListener('input', isValid))
form.onsubmit = event => if (!isValid()) event.preventDefault()
Or ES5 if you prefer:
var form = document.querySelector('form');
var inputNodes = form.querySelectorAll('input');
var inputs = Array.prototype.call.slice(inputNodes); // convert node list to array
var isValid = function() {
var valid = false;
disableButton();
// handle your conditions here
if (valid) enableButton();
return valid
}
inputs.forEach( function(input) {
input.addEventListener('input', isValid);
});
form.onsubmit = function(event) {
if (!isValid()) event.preventDefault();
};
It's also worth noting that HTML5 has a lot of built-in validation you can take advantage of.
I got input from input tags but whatever I write in inputs it recognize as string value so that I can't use my conditions.
and the second problem if I enter "ddd" for first input and "111" for second input and press button it shows NaN in console. I want to show alert instead of this. How can I correct these?
function addFunc() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
if (typeof x == 'string' || typeof y == 'string') {
var result = parseInt(x) + parseInt(y);
console.log(result);
} else {
alert("Wrong Entry!");
}
}
<input id="num1">
<input id="num2">
<button type="button" onclick="addFunc()">ADD</button>
<p id="result"></p>
The value of an input field will always be a string. Try using isNaN() to determine if the decimal parsed correctly:
function addFunc() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
if ( !isNaN(x) && !isNaN(y) )
{
var result = x + y;
console.log(result);
}
else {
alert("Wrong Entry!");
}
}
<form onsubmit="addFunc(); return false">
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" value="Add" />
</form>
Alternatively, if you want to eliminate all bad input (1e would be invalid), try using a + symbol before the string value to convert it to a number. If the string can't be converted, it will return NaN:
function addFunc() {
var x = +document.getElementById("num1").value;
var y = +document.getElementById("num2").value;
if ( !isNaN(x) && !isNaN(y) )
{
var result = x + y;
console.log(result);
}
else {
alert("Wrong Entry!");
}
}
<form onsubmit="addFunc(); return false">
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" value="Add" />
</form>
Can anyone point me in the right direction as to why my calculate button will not calculate. It doesn't even throw any of the error messages up to the screen, but my clear button does work. It's probably something small, but I cannot figure it out for the life of me -_-.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("totalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("cost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
var virusRemoval = parseFloat($("virusRemoval").value = "");
var websiteMaking = parseFloat($("websiteMaking").value = "");
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value = "");
var totalCost = parseFloat($("totalCost").value = "");
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotal" value="Calculate " onblur="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>
The reason why the loop is in there is because we were required to have a loop and I couldn't find a good reason to have one, so I used one that would always be true to get it out of the way lol. Probably will throw an infinate loop at me or something, but I'll figure that out later, I'm just trying to get the dang on thing to do something here haha. I've tried to rewrite this 2 other times and still get to the same spot, so I realize it's probably something small, and I am new to Javascript. Thank you.
The problem is that you have id="calculateTotal" in the input button. Element IDs are automatically turned into top-level variables, so this is replacing the function named calculateTotal. Simply give the function a different name from the button's ID.
You also have a typo. The ID of the Total Cost field is TotalCost, but the code uses $('totalCost') and $('cost').
It's also better to do the calculation in onclick, not onblur. Otherwise you have to click on the button and then click on something else to see the result.
In the clearValues function, there's no need to assign variables and call parseFloat. Just set each of the values to the empty string. You could also just use <input type="reset">, that resets all the inputs in the form to their initial values automatically.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("TotalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("TotalCost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
$("virusRemoval").value = "";
$("websiteMaking").value = "";
$("computerOptimizationAndSetUp").value = "";
$("TotalCost").value = "";
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotalButton" value="Calculate " onclick="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>
I am looking to make price calculator for editing papers. I have the first part complete (words per day jsfiddle ).
<label>Need in how many Days</label>
<input type="number" id="days" />
<br />
<label>Total Word Count</label>
<input type="number" id="words" />
<br />
<label>Price</label>
<input type="text" id="output" readonly />
I am looking to have the user enter the total word count and how many days they need the document, to display the price per project. I am not sure how to add the price table to the javascript and have it display the results. The table is:
250 words or less = $0.015 per word, 251-499 = $0.020 per word, 500-1499 = $0.025 per word, 1500-2499 = $0.030 per word, More than 2500 words per day = contact me
Thanks for the help. Hope that makes sense.
I have tried to do it as explicitly as possible in pure Javascript for easier understanding.
This is the HTML:
<label>Need in how many Days</label>
<input type="number" onkeyup="getValues()" id="days" />
<br />
<label>Total Word Count</label>
<input type="number" onkeyup="getValues()" id="words" />
<br />
<label>Price</label>
<input type="text" id="output" readonly />
<br />
And here is the JavaScript:
var days, words, output;
//think of the prices as t-shirt sizes
var extraSmall = 0.015,
small = 0.020,
medium = 0.025,
large = 0.030,
extraLarge = 0.035,
extraExtraLarge = 'contact me';
// now you go into the dom and get the values you need
window.getValues = function () {
var pricePerWord = 0;
days = document.getElementById('days').value;
words = document.getElementById('words').value;
if(words > 2500) {
if(days == 1) {
pricePerWord = extraExtraLarge;
} else {
pricePerWord = extraLarge;
}
} else if (words >= 1500) {
pricePerWord = large;
} else if (words >= 500) {
pricePerWord = medium;
} else if (words >= 251) {
pricePerWord = small;
} else {
pricePerWord = extraSmall;
}
// call the calculate function to do the math and update the dom
calculate(pricePerWord, words, days);
}
window.calculate = function (pricePerWord, words, days) {
var total;
if(pricePerWord === extraExtraLarge) {
total = extraExtraLarge;
} else {
total = Math.ceil(pricePerWord * words / days);
}
output = document.getElementById('output');
if(days !== '' && days != 0) {
output.value = total;
} else {
output.value = 0; // prevent 'Nan' and 'Infinity' from showing up
}
}
Note: The code uses 'window.calculate' as it makes it work in jsfidle but it should work without the 'window.' part in your code.
Hope it helps!
I have a condition in javascript like below
function check()
{
var amount = document.getElementById('pamount').value;
var quantity = document.getElementById('qty').value;
var pmin = document.getElementById('pmin').value;
var pmax = document.getElementById('pmax').value;
var stock = document.getElementById('stocks').value;
if (amount > pmax) {
alert('Price should not be more than maximum price');
return false;
}
if (amount < pmin) {
alert('Price should not be less than minimum price');
return false;
}
if (quantity > stock) {
alert('Please enter quantity no more than maximum');
return false;
}
if (quantity < 1) {
alert('Please enter valid quantity');
return false;
}
}
And here is the html fields
<input type="text" value="" data-toggle="tooltip" data-placement="top" class="form-control small qty_box" id="qty" name="qty">
<input style="width:90px; float:left" type="text" value="" class="form-control small" id="pmin" name="min">
<input style="width:90px; float:left" type="text" class="form-control small" id="pmax" name="max">
But it always return false. When I enter less value for amount it alerts the same. I tried alerting amount and pmax. It gets actual value. But something wrong with this compare
I gave amount as 75 and pmax as 100.
Use parseFloat() or parseInt() as per your need to compare numbers. Below code used parseFloat().
var amount = parseFloat(document.getElementById('pamount').value);
var quantity = parseFloat(document.getElementById('qty').value));
var pmin = parseFloat(parseFloat(document.getElementById('pmin').value);
var pmax = parseFloat(document.getElementById('pmax').value);
var stock = parseFloat(document.getElementById('stocks').value);
There is no issue with your code. Check whether your browser is disabled the javascript. That will be the issue.
Remove that return false from { }
if (amount > pmax) {
alert('Price should not be more than maximum price');
}
else
//rest of the code