I have a function which collects the value of an input that is in string format, being in this format I need to delete the words and only leave the numbers using the replace option, previously I used the first indexOf tag (it works correctly) to know if in the value of the input it contains the character "-" and to know if the numeric that is inside the string is negative positive, once the character is detected and all the words have been eliminated, what I do in the case that in the first IndexOf is equal to 0 is to convert the replaced value to negative, after that another function calls the first function and collects the variable that contains the replaced result and passed to negative, in this second function it contains another indexOF (it does NOT work correctly) that reads if the character "-" in the variable that we have passed since the first function. I have the problem in this second IndexOf which gives me the following error: impuesto1.indexOf is not a function.
First function (working correctly)
function value_impuestos(){
if(un_articulo == true)
{
impuestos1=$("#impuestos1-1").val();
negativo_positivo=impuestos1.indexOf("-");
impuesto = impuestos1.replace(/[^0-9\.]+/g, "");
if(negativo_positivo==0)
{
x = impuesto;
impuesto = x * -1;
impuesto=parseFloat(impuesto);
}
}
}
Second function (NO working correctly)
$("select[id=impuestos1-1]").change(function(){
value_impuestos();
impuesto1=impuesto;
alert(impuesto1); //result correct, example : -7
positivo_negativo=impuesto1.indexOf("-") > -1; //ERROR
if(positivo_negativo==false)
{
}
});
It might be simple, but:
Here is a working example. The change event is fired when you click out of the text box.
let impuesto = 0;
let un_articulo = true;
function value_impuestos(impuestos1){
if(un_articulo)
{
negativo_positivo = impuestos1.indexOf("-");
impuesto = impuestos1.replace(/[^0-9\.]+/g, "");
try {
impuesto=parseFloat(impuesto);
}
catch(err) {
console.error(err)
}
console.log('value_impuestos:', impuesto)
console.log('impuesto type:', typeof impuesto)
if(negativo_positivo == 0)
{
impuesto = impuesto * -1;
}
return impuesto
}
}
$(function() {
$("input[id=impuestos1-1]").change(function(e){
let impuesto1 = value_impuestos($(this).val());
console.log('change:', impuesto1)
if(impuesto1 > -1)
{
console.log('positive or 0')
}else{
console.log('negative')
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form>
<input type="text" id="impuestos1-1" />
</form>
</body>
Related
how do I change that the user is able to key in the value from 0- infinite?
Because it only allows the user to key in from 0-9 at this moment.
function validate() {
var values = document.getElementById("digit").value;
if (/^[0-9]$/.test(values) == false) {
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero";
return false;
}
return true;
}
Use typeof and the urnary operator + to check if its an number and greater equal then 0
function validate() {
var value = document.getElementById("digit").value;
if (!(!isNaN(+value) && value >= 0)) {
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero";
return false;
}
document.getElementById("numbers").innerHTML = "";
return true;
}
<input onkeyup="validate()" value="" id="digit" />
<p id="numbers"></p>
Your Regular expression is looking for one and only one digit between the start and end of the string.
Try /^[0-9]$+/.
The + means 'At least one, up to an infinity of' whatever it's stuck too.
Use the native method Number.isInteger() to check if the last character is a number. If not, slice it.
function validate(el) {
var lastChar = Number(el.value.slice(-1));
if (!Number.isInteger(lastChar)) {
el.value = el.value.substring(0, el.value.length - 1);
};
}
<input type="text" oninput="validate(this)">
I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)
My code isn't working, can someone please tell me what the problem is?
I'm guessing it's the for loop, but I cannot find the problem.
<html>
<body>
<script>
username = prompt("Please enter a your username:");
for (var i = 0; i < username; i++) {
if(isFinite(username.charAt(i))) {
result = true;
document.write("The username consists of one or more numbers." + BR);
}
else {
result = false;
document.write("The username must consist of one or more numbers." + BR);
}
}
</script>
</body>
</html>
You have two problems in your code:
In the for loop, use the length of the variable to establish the stop condition
for (var i = 0; i < username.length; i++)
BR is not defined
Working code: http://jsfiddle.net/f643fr4w/
From the output I can probably assume you just want to check if username consists of at least one number, actually: a digit.
// iterate over the input
for (var i = 0; i < username.length; i++) {
// check if it is a number (not a digit but that's the same here)
if (isFinite(username.charAt(i))) {
result = true;
// The requirement "one or more numbers" is fulfilled,
// we can break out of the loop
break;
}
else {
result = false;
}
// print something according to "result"
if(result === true){
document.write('The username consists of one or more numbers.');
} else {
document.write('The username must consist of one or more numbers.');
}
}
You have to go over the full length of the string to find out if there's no number but not if you want to find out if there is any number in it.
Now, if you want to test if it consists of only digits you have to reword the requirements, they are a bit too ambiguous now.
Additional hints:
you need to check the input, you always have to check user input!
you need to be aware that JavaScript strings are UTF16. Rarely a problem but gets easily one if you iterate over JavaScript strings.
String.charAt() returns a character, not a number. Don't rely on the automatic conversions in JavaScript, you way too easily shoot yourself in the foot if you rely on it but also if you don't, so be careful.
please don't use document.write, use either the console if available or change the text-node of an HTML element.
With these points in mind you may get something like this:
// make a list of digits
var digits = ['0','1','2','3','4','5','6','7','8','9'];
// ask the user for a username
var username = prompt("Please enter a your username:");
// check input
if (username.length === 0) {
console.log('no username given');
} else {
for (var i = 0; i < username.length; i++) {
// indexOf searches for the same type, that's why the digits above
// are strings with quotes around them
if (digits.indexOf(username.charAt(i)) >= 0) {
result = true;
// The requirement "one or more numbers" is fullfilled,
// we can break out of the loop
break;
}
else {
result = false;
}
}
// print something according to "result"
if (result === true) {
console.log('The username consists of one or more numbers.');
} else {
console.log('The username must consist of one or more numbers.');
}
}
The above is one variation of many and could easily give rise to a heated discussion on some forums (not here! Of course not! ;-) ) but I hope it helps.
Use a regex for such shenanigans:
var username = prompt("username plz kk thx");
var result = /[0-9]/.test(username);
document.write("The username " + (result ? "consists" : "must consist") + " of one or more numbers");
I'd like to validate a phone number input using JavaScript to allow only number input. I prefer not to use regex, so I wrote a function like this:
function numberTest(){
for(var i=0;i<phone_number.length;i++){
if(phone_number.charCodeAt(i) >= 48 && phone_number.charCodeAt(i) <=57){
return true;
}else{
return false;
}
}
}
However it does not work. Any ideas why?
This doesn't work because it returns true after the first valid character. Neither branch will get past the first character, so you need to only return if you find an invalid character. Otherwise, if you reach the end without finding an invalid characters, you can finally return true.
Something like:
function numberTest(phone_number) {
for (var i = 0; i < phone_number.length; i++) {
if (phone_number.charCodeAt(i) < 48 && phone_number.charCodeAt(i) > 57) {
return false;
}
}
return true;
}
// Test various values
var testData = ["1234", "12ab", "123451234512345", "a1234123", "123123123a"];
var output = document.getElementById("results");
testData.forEach(function(test) {
var next = document.createElement("li");
next.textContent = numberTest(test);
});
<ul id="results"></ul>
The isNaN() (means is not a number) method will give you the reverted result in a simpler way...
var phone_number = "5511112223";
alert(isNaN(phone_number)); //returns false meaning it is a valid number
phone_number = "55aa1g11d12223";
alert(isNaN(phone_number)); //returns true meaning it is not a number
I have a few functions that aim to convert a user input as a string to a binary number. This is part of a basic 'assembler' program I am working on. Here is my code:
function generateBinaryNumber(inputValue) //only works for hash!
{
var number;
if(containsHash(inputValue) != -1)
{
number = getNumberFromString(inputValue);
}
return decimalToBinary(number);
}
function containsHash(number) //Working!
{
var n = number.indexOf('#');
return n;
}
function getNumberFromString(mixedInput) //Working!
{
return (mixedInput.replace('#',''));
}
function decimalToBinary(decimal) //Working!
{
decimal = parseInt(decimal);
return decimal.toString(2);
}
If a user enters a value of '5' for example, the function returns NaN - however if they specify #5 it works - 101 is returned. I am new to programming and Javascript, if anyone can point me in the right direction that would be great. Thanks!
You're not passing the input if there's no #
function generateBinaryNumber(inputValue) //only works for hash!
{
var number; //number is not set
if(containsHash(inputValue) != -1)
{
//number is set here, but only if the if statement is true
number = getNumberFromString(inputValue);
}
//if containsHash was false, number is undefined
return decimalToBinary(number);
}
You just want to say var number=inputValue; when you declare it
As a side note, you should also add a radix argument to your parseInt (so something like parseInt(decimal,10)) otherwise it will treat input like "010" as hex digits and will parse it incorrectly.