Im working on a script which takes a form input and calculates a total including VAT.
I am attempting to validate the user input making sure he&she only uses whole numbers.
My problem is that when I type in the first number ie. 1 it throws my alert. And when continuing to add numbers it works fine. When typing in letters it works as supposed and return the alert.
I have a faint idea that this happens because I am using onkeydown event for activating the evaluation function. Since consoleLog show me that the value 100 is parsed as 10, 1000 as 100.
If I change them around so I now use onkeyup the calculator function will show me that the value 100 is parsed as 10, 1000 as 100. But if the field is empty the form is rendered unuseless because of the alert box keeps popping up. Evaluation works though if you get a chance to type anything in.
I will now post my code HTML first and JS after
<input type="text" id="price" name="price" onkeyup="checkIfWholeNo();" onkeydown="calculate();" />
function checkIfWholeNo() {
var price = document.getElementById('price').value;
if(/^\d+$/.test(parseInt(price))){}
else {alert("not a number"); return false;}
}
}
Question A:
Is there something wrong with my evaluation function that makes this happen?
Question B:
If it has to do with the event handlers how do I fix it so I get the effect of onkeyup on both the functions?
refer following links..
http://www.roseindia.net/javascript/form-validation-regular-expressions.shtml
http://www.designchemical.com/blog/index.php/jquery/form-validation-using-jquery-and-regular-expressions/
http://www.codeproject.com/Articles/17923/Form-Validation-with-Regular-Expression-Short-Vers
http://www.9lessons.info/2009/03/perfect-javascript-form-validation.html
Related
Let's say there is a form field named txtphone and then with javascript I check it is at least 10 digits in length. User enters only 5 digits so validation fails. I want the cursor to go back to where the txtphone is input automatically so the user can not get any further without entering a 10 digit phone number. This is an example. I can not get it to go back to input field on fields like name, email, etc. On this example, on failure, this is how I am trying to accomplish this:
txtphone.focus()
txtphone.select()
return False
It shows the alert error message but the focus is placed on the next form field.
Please, respond only if you had this problem in the past and you solved it, and please, give me a few lines of actual working code. I have been fighting this for weeks and ready to give up. Answers like "have you tried..." do me no good. Thank you.
I created a JSFiddle showing how the focus method should work for what you're looking for. Let me know if it helps.
JSFiddle
HTML
<input id="txtphone" type="text">
<button id="btn">
Click me!
</button>
JavaScript
var txtphone = document.getElementById("txtphone");
var button = document.getElementById("btn");
button.addEventListener("click", function () {
if (txtphone.value.length < 10) {
txtphone.style.backgroundColor = "red";
txtphone.focus();
} else {
txtphone.style.backgroundColor = "white";
}
});
I am using visual studio 2008 for developing a webpage. The problem description is like this : I have 3 textboxes in the webpage one is "Price" second one is "quantity" and third one is "Amount". I want to get price*quantity=Amount.
I dont want to have any buttonclicks while doing so. First I am entering value into price then im entering value to quantity, as soon as I move the cursor out of quantity I want the answer printed in third text box automatically without button click. I want to do it in javascript.
I think what you mean is the blur event, which gets triggered when a textinput loses its focus (if you click outside of it).
Bind it to your textarea like this:
price.addEventListener("blur", function( event )
{
// do it
}, true);
Fiddle: http://jsfiddle.net/egLzz5gb/
You can use the change event on the input fields. This event is fired every time the value in the input is changed. I don't know what your form looks like, but this code should give you a general idea how to do it:
quantityInput.addEventListener('change', function(){
amountInput.value = parseInt(quantityInput.value) * parseInt(priceInput.value);
});
If you're working with decimal numbers, use parseFloat() instead of parseInt(), be careful though, and preferably use Math.round(), as calculations with floating point are not 100% precise.
Price: <input type="text" id="price">
Quantity: <input type="text" id="quantity" onkeyup="myFunction()">
Amount: <input type="text" id="amount"">
<script>
function myFunction() {
var p = document.getElementById("price");
var q = document.getElementById("quantity");
var a = document.getElementById("amount");
a.value = p.value * q.value ;
}
So basically what I'm trying to do as a measure of security (and a learning process) is to my own "Capthca" system. What happens is I have twenty "label's" (only one shown below for brevity), each with an ID between 1 and 20. My javascript randomly picks one of these ID's and makes that picture show up as the security code. Each label has its own value which corresponds to the text of the captcha image.
Also, I have the submit button initially disabled.
What I need help with is figuring out how to enable the submit button once someone types in the proper value that matches the value listed in the HTML label element.
I've posted the user input value and the ID's value and even when they match the javascript won't enable the submit button.
I feel like this is a really really simple addition/fix. Help would be much much appreciated!!!
HTML code
<div class="security">
<label class="captcha enabled" id="1" value="324n48nv"><img src="images/security/1.png"></label>
</div>
<div id="contact-div-captcha-input" class="contact-div" >
<input class="field" name="human" placeholder="Decrypt the image text here">
</div>
<input id="submit" type="submit" name="submit" value="Send the form" disabled>
Javascript code
//Picks random image
function pictureSelector() {
var number = (Math.round(Math.random() * 20));
//Prevents zero from being randomly selected which would return an error
if (number === 0) {
number = 1;
};
console.log(number);
//Set the ID variable to select which image gets enabled
pictureID = ("#" + number);
//If the siblings have a class of enabled, remove it
$(pictureID).siblings().removeClass("enabled");
//Add the disabled class to all of the sibling elements so that just the selected ID image is showing
$(pictureID).siblings().addClass("disabled");
//Remove the disabled class from the selected ID
$(pictureID).removeClass("disabled");
//Add the enabled class to the selected ID
$(pictureID).addClass("enabled");
};
//Calls the pictureSelector function
pictureSelector();
//Gets the value of the picture value
var pictureValue = $(pictureID).attr("value");
console.log(pictureValue);
//Gets the value of the security input box as the user presses the keys and stores it as the variable inputValue
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
});
console.log($("#contact-div-captcha-input input").val());
//Checks to see if the two values match
function equalCheck() {
//If they match, remove the disabled attribute from the submit button
if ($(pictureValue) == $("#contact-div-captcha-input input").val()) {
$("#submit").removeAttr("disabled");
}
};
equalCheck();
UPDATE
Fiddle here
UPDATE #2
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
if (pictureValue === inputValue) {
$("#inputsubmit").removeAttr("disabled");
}
});
So I got it working 99.9%, now the only problem is that if someone were to backspace or delete the correct value they have inputted, the submit button does not then change back to disabled. Any pointers?
Known issue.
Give your button a name OTHER THAN submit. That name interferes with the form's submit.
EDIT
A link was requested for this -- I don't have a link for pure JavaScript, but the jQuery docs do mention this issue:
http://api.jquery.com/submit/
Forms and their child elements should not use input names or ids that
conflict with properties of a form, such as submit, length, or method.
Name conflicts can cause confusing failures. For a complete list of
rules and to check your markup for these problems, see DOMLint.
EDIT 2
http://jsfiddle.net/m55asd0v/
You had the CSS and JavaScript sections reversed. That code never ran in JSFiddle.
You never re-called equalCheck. I added a call to your keyUp handler.
For some reason you wrapped pictureValue inside a jQuery object as $(pictureValue) which couldn't have possibly done what you wanted.
Basic debugging 101:
A console.log inside of your equalCheck would have shown you that function was only called once.
A console log checking the values you were comparing would have shown
that you had the wrong value.
Basic attention to the weird highlighting inside of JSFiddle would have shown you had the code sections in the wrong categories.
I'm experiencing a weird issue, or maybe it's something that i simply don't know
i am using an input type text to capture and update a value using ajax.
<input type="text" onchange="functionx(this);" style="width:80px; margin-top: 5px;" name="stock" id="stock" />
if i put any alphanumeric value on the field the javascript function get fired correctly, even if i put the plus sign and some numbers (+123456) but if i use the minus sign it doesn't work (-123456) what am i missing or doing wrong?
Thanks in advance.
UPDATE
function functionx(obj){
alert("function is being called");
}
I ran into a similar issue, while working on a project.
My answer does not exactly address the OP, but might help people running into the similar issue, due to a different reason.
I had an input field, which needed only Natural numbers as input. Therefore inside the onChange handler, I would run a validation, as shown in below code snippet.
<input
...
// AREA OF FOCUS
type="number"
// AREA OF FOCUS
onChange={(event) => {
const isValid = validateNumberValue(event.target.value, 'REGEX FOR NATURAL NUMBER');
if (isValid) {
handleFormInputChange();
}
}}
...
/>
It would work perfectly for the most part, however it would also accept input such as --, ++. Upon investigation, I figured it was due to the onChange handler not triggering when + or - was entered as input.
This was because, the type attribute of the input HTML tag was "number". It would only trigger when a numeric value was entered. I changed the type field to text, and everything started working as expected.
<input
...
// AREA OF FOCUS
type="text"
onChange={(event) => { ... }}
...
/>
Hope it helps. Thanks.
Validate in your JS that you are comparing with a NULL or undefined value and not with a value who is bigger than 0, i tested this on jsFiddle and its working fine.
Something in your validation could be causing this issue.
function functionx(obj){
var objval = obj.value;
if(objval != ""){
alert(objval);
}
}
Check this fiddle
Is there a possiblity to force an iOS-device to show the numeric keyboard while using a custom pattern as input type?
my input pattern:
<input id="price" class="numeric" pattern="\d+((\.|,)\d{1,2})?" name="price"
title="" data-mini="true" data-clear-btn="true" autocomplete="off" autofocus />
I want to type a currency value like '14.99' and show up a keyboard with access to numbers on the iOS device
<input type='number' />
<input pattern='[0-9]*' />
<input pattern='[\d]*' />
are all missing the decimal sign and/or are not validating as number when adding a decimal sign. An alternative way could be a javascript function which is creating the decimal sign on the right place, like pressing 1->2->9->9 in this order creates on keypress() 0.01->0.12->1.29->12.99,
but this requires the input field to be type='text' --> obvious problem here is that the text keyboard is showed when focussing the input field.
How can I solve this issue?
EDIT
Environment:
JQM 1.3.2
jquery 1.8.2
For now, JavaScript is the only solution. Here's the simplest way to do it (using jQuery):
HTML
<input type="text">
JavaScript
$('input[type="text"]').on('touchstart', function() {
$(this).attr('type', 'number');
});
$('input[type="text"]').on('keydown blur', function() {
$(this).attr('type', 'text');
});
The idea is simple. The input starts off and ends up with type="text", but it briefly becomes type="number" on the touchstart event. This causes the correct iOS keyboard to appear. As soon as the user begins to enter any input or leave the field, the input becomes type="text" once again, thus circumventing the validation.
There's one downside to this method. When the user returns to an input that has already been filled out, the input will be lost (if it doesn't validate). This means the user won't be able to go back and edit previous fields. In my case, this isn't all that bad because the user may want to use the calculator over and over again with different values, so automatically deleting the input will save them a few steps. However, this may not be ideal in all cases.
It looks like Mobile Safari supports the new HTML5 input type attributes of email, number, search, tel, and url. These will switch the keyboard that is displayed. See the type attribute.
So for example, you could do this:
<input type="number" />
And when the input box has focus, the number keyboard is shown (as if the user had the full keyboard and hit the "123" button.
If you really only want numbers, you could specify:
<input type="tel" />
And then the user would get the phone number dialing keypad.
I know this works with Mobile Safari -- I only assume it will work with UIWebView.
http://conecode.com/news/2011/12/mobile-safari-uiwebview-input-types/
I made this little snippet to achieve what you want and I've tested it on iPhone 5 v7.0.3
I used e.which to read CharCode entered and then push it into an array (before) which represents digits before decimal mark and another array (after) to move values from (before) array past the decimal mark.
It might look complicated, due to my humble programming skills.
1) Code demo - 2) Currency conversion demo
HTML:
<input type="tel" id="number" />
JS
Variables and functions:
// declare variables
var i = 0,
before = [],
after = [],
value = [],
number = '';
// reset all values
function resetVal() {
i = 0;
before = [];
after = [];
value = [];
number = '';
$("#number").val("");
$(".amount").html("");
}
// add thousand separater
function addComma(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Main code:
// listen to keyup event
$("#number").on("keyup", function (e, v) {
// accept numbers only (0-9)
if ((e.which >= 48) && (e.which <= 57)) {
// convert CharCode into a number
number = String.fromCharCode(e.which);
// hide value in input
$(this).val("");
// main array which holds all numbers
value.push(number);
// array of numbers before decimal mark
before.push(value[i]);
// move numbers past decimal mark
if (i > 1) {
after.push(value[i - 2]);
before.splice(0, 1);
}
// final value
var val_final = after.join("") + "." + before.join("");
// show value separated by comma(s)
$(this).val(addComma(val_final));
// update counter
i++;
// for demo
$(".amount").html(" " + $(this).val());
} else {
// reset values
resetVal();
}
});
Reset:
// clear arrays once clear btn is pressed
$(".ui-input-text .ui-input-clear").on("click", function () {
resetVal();
});
Result:
I think that you can use the same approach that I suggested to Ranjan.
Using a textfield like a buffer. First you need to detect when the keyboard appears and check if the first responder is the webview. Then you become a textview as the first responder.
When you are setting the text inside the input of the webview, you can add some logic to validate the number.
Here is a link of my example project with the solution, in your case you don't need change the inputView. But the approach is the same, use a Man in the middle.
Cant comment on https://stackoverflow.com/a/19998430/6437391 so posting as a separate answer...
This is the same idea as https://stackoverflow.com/a/19998430/6437391 but instead of switching the type, its the pattern that's switched.
This has the effect of not clearing the value on the textfield on focus when value does not match numeric format, for example, if the value has separators( 1,234.56 ).
$('input[type="text"]').on('touchstart', function() {
$(this).attr('pattern', '[0-9]*');
});
$('input[type="text"]').on('focus', function() {
$(this).attr('pattern', actualpattern);
});