jquery mobile function on.change works only sometimes - javascript

I have this code in jsfiddle, this code is supposed to check for invalid numerical values like -12-12. So the bug arises if I type an invalid numerical value (eg. -12-11) it removes the input (which is the expected behavior) and the weird part is that the second time it doesn't call the document.on change function.
The steps to reproduce the problem are as follows:
Type 12 for example.
Click somewhere else like the other textbox and that number will be
converted to decimal (12.00)
Type and incorrect number like -12-12 and click somewhere else and
the textbox will get cleared out (which is the expected behaviour).
The second time you type that number in the textbox it doesn't change
the value or clear the textbox.
This is something that I don't understand, by trying to debug the code the second time you insert a wrong number that function doesn't get called so I was wondering why.
Any help is appreciated.
My javascript code:
$(document).on('change', 'input[type="number"]', function(event) {
var target = $(event.target);
var max = target.attr('max') - 0;
var min = target.attr('min') - 0;
var step = target.attr('step');
var val = parseFloat(target.val());
if(typeof max !== 'undefined' && val > max) {
target.val(max);
}
else if(typeof min !== 'undefined' && val < min) {
target.val(min);
}
else if(typeof step !== 'undefined') {
if(step < 1) {
target.val(parseFloat(target.val()).toFixed(step.split('.')[1].length));
}
else {
debugger;
}
}
else if(val + '' != target.val()) {
target.val(val);
}
});

I see your issue, and able to solve it. I suggest you to use blur event instead of change event of textbox. This will work like a charm.
Here is the code :
$(document).on('blur', 'input[type="number"]', function(event) {
var target = $(event.target);
var max = target.attr('max') - 0;
var min = target.attr('min') - 0;
var step = target.attr('step');
var val = parseFloat(target.val());
if(typeof max !== 'undefined' && val > max) {
target.val(max);
}
else if(typeof min !== 'undefined' && val < min) {
target.val(min);
}
else if(typeof step !== 'undefined') {
if(step < 1) {
target.val(parseFloat(target.val()).toFixed(step.split('.')[1].length));
}
else {
debugger;
}
}
else if(val + '' != target.val()) {
target.val(val);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="transaction_amount">Amount</label>
<input type="number" data-mini="true" step="0.01" name="amount" min="0.01" max="1000000" id="transaction_amount" value="">
<label for="transaction_external_identifier" id="payment-description-label">Check #</label>
<input type="text" name="external_identifier" id="transaction_external_identifier" value="" data-mini="true">

When an invalid number is entered into the number type input, the browser regards that as blank (because it's invalid and it won't bother holding that value, so returns false when asked about validity. According to the Mozilla Developer Network). So if you type -12-12 again, the change event doesn't fire and hence it doesn't clear out because the underlying value is still blank. You'll see this if you first start with entering -12-12 into the blank input - it also won't work.
Your best bet is to change the onchange to onblur as it will be far more consistent since it doesn't look at the value.

Related

How to edit the correct phone number in my script?

I have this sample:
link
CODE HTML:
<label for="primary_phone">Primary Phone Number<span class="star">*</span></label>
<br>
<input type="text" name="primary_phone" id="primary_phone" class="_phone required-input" value="" maxlength="10">
CODE CSS:
.invalid{
border:1px solid red !important;
}
.valid{
border:1px solid green !important;
}
CODE JS:
function phoneFormat(){
$( "._phone" ).on('blur change', function() {
text = $(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
var testt=$(this).val().match(text);
if($(this).val()=='' || $(this).val().match(text) || $(this).val().length == 0)
{
$(this).removeClass('valid').addClass('invalid');
}
else{
$(this).removeClass('invalid').addClass('valid');
}
$(this).val(text);
});
}
$( "#primary_phone" ).blur(function() {
phoneFormat();
});
I put a script that arranges text format
for example, we can add this number :
1234567890
After calling script appears next form (what is right)
(123) 456-7890
The problem is when you want to edit my phone number ... if you want to delete the last two numbers because I put the following code maxlength="10"
I want the user can not write more than 10 characters.
How do I fulfill both requirements.
If something is not explained well I'll do an edit to this post
Thanks in advance!
Just remove all special characters when you focus in on the input box:
$("#primary_phone").on("click", function() {
var thisVal = $(this).val();
var value = thisVal.replace(/[^\/\d]/g,'');
$(this).val(value);
});
Now when you click out of the input box, your original function to format the number comes in to play :)
Working fiddle : https://jsfiddle.net/reko91/gto0qeyx/2/
I would set a higher maxlength (say 15) and bind the input to keypress.
Inside the event you can check the keyCode against a set of allowed ones and suppress the event (entry of the character) otherwise.
I would also suppress the entry of numbers if we already have 10 (with one exception: if the user selected (marked) a portion of the input and that selection contains numbers.
var alwaysAllowed = [32, 40, 41, 45]; // [" ","(",")","-"]
function keyCode(keyCode) {
if (alwaysAllowed.indexOf(keyCode) !== -1) {
return "allowed";
} else if (keyCode >= 48 && keyCode <= 57) {
// 0 - 9
return "number";
} else {
// any other character
return false;
}
}
function countNumbers(text) {
// return the number of characters [0-9] in the string "text"
var counter = 0;
for (var i = 0; i < text.length; i++) {
if (parseInt(text[i]) >= 0 && parseInt(text[i]) < 10) {
counter++;
}
}
return counter;
}
$primaryPhone.on("keypress", function () {
var keyCodeEvaluation = keyCode(event.keyCode);
if (keyCodeEvaluation === false) {
event.preventDefault();
} else if (keyCodeEvaluation === "number") {
var value = this.value,
counter = countNumbers(value.substring(this.selectionStart, this.selectionEnd));
//
if (counter === 0 && countNumbers(value) > 9) {
event.preventDefault();
}
}
});
This would allow the user to edit (or write) the phonenumber with your format applied.
MORE IMPORTANTLY
You should rewrite your phoneFormat() function.
Each execution adds another event listener. The first time you change the input value it executes one time. Then two times, three times and so forth.
You should also store objects you use repeatedly in a variable, e.g. $( this ) (creating the same jQuery object each time is a performance killer).
Here is a working example that should cover most of your use cases.

Prevent user from typing in input at max value

I'd like the user to be blocked from typing more if the value is over 100. So far I have the following from reading different posts:
$('.equipCatValidation').keyup(function(e){
if ($(this).val() > 100) {
e.preventDefault();
}
});
To confirm I want the value not the string length, and it can't be above 100.
However this is not preventing further input in the field. What am I missing.
Checking keyup is too late, the event of adding the character has already happened. You need to use keydown. But you also want to make sure the value isn't > 100 so you do need to also use keyup to allow js to check the value then too.
You also have to allow people to delete the value, otherwise, once it's > 100 nothing can be changed.
<input class="equipCatValidation" type="number" />
When using input type="number", change also needs to be on the event list.
$('.equipCatValidation').on('keydown keyup change', function(e){
if ($(this).val() > 100
&& e.keyCode !== 46 // keycode for delete
&& e.keyCode !== 8 // keycode for backspace
) {
e.preventDefault();
$(this).val(100);
}
});
http://jsfiddle.net/c8Lsvzdk/
Basically keypress events are fired before accepting the current value. So when you press on any key, keypress event is subscribed but you don't get the updated value/result for the recently pressed key. So, to get the last pressed key we can use the fromCharCode method and concat it with the value we got from the textbox. That's it,
HTML :
<input id="inputBox" type="text" />
jQuery :
$("#inputBox").on("keypress", function(e){
var currentValue = String.fromCharCode(e.which);
var finalValue = $(this).val() + currentValue;
if(finalValue > 100){
e.preventDefault();
}
});
jsFiddle
Maybe keydown instead of keyup?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function() {
$('.equipCatValidation').keydown(function(e){
if ($(this).val() > 100) {
e.preventDefault();
}
});
})
</script>
</head>
<body>
<input type="text" class="equipCatValidation">
</body>
</html>
EDIT: There is a valid comment here - Prevent user from typing in input at max value - to circumvent that you should probably store the previous value and restore it when necessary.
It is bad UI to disable the input if a user inputs a bad value. I'm assuming you simply want to put a max value that the user cannot go over. If so, you can either clamp the value, or use the max attribute in your markup:
<form>
<input type='number' max='100'>
</form>
If you input an invalid value, the input will turn red, and you cannot submit the form.
<input class="equipCatValidation" />
var maxValue = 100;
jquery
$('.equipCatValidation').on('keypress', function(e){
/* preventing set value when it doesn't pass conditions*/
e.preventDefault();
var input = $(this);
var value = Number(input.val());
var key = Number(e.key);
if (Number.isInteger(key)) {
value = Number("" + value + key);
if (value > maxValue) {
return false;
}
/* if value < maxValue => set new input value
in this way we don't allow input multi 0 */
$element.val(value);
}
});
vanilla js
document.querySelector(".equipCatValidation")
.addEventListener("keypress", function(e) {
e.preventDefault();
var input = e.target;
var value = Number(input.value);
var key = Number(e.key);
if (Number.isInteger(key)) {
value = Number("" + value + key);
if (value > maxValue) {
return false;
}
input.value = value;
}
});
example
addition to the this answer
$('.equipCatValidation').on('keypress', function(e){
var $element = $(this);
var value = Number($element.val());
var key = Number(e.key);
if (Number.isInteger(key)) {
value = Number("" + value + key);
}
if (value > 100) {
return false;
}
});
Here's a solution for those using modern vanilla Javascript:
Just snap the value back down to the max when the user focuses away from the input.
You would set the input to a number type and the max value
<input type="number" max="100">
and then add a function to the onblur method of the element
document.querySelector('input[max]').onblur = function (event) {
// If the value is less than the max then stop
if (Number(event.target.value) < event.target.max) return
// Snap the value to the max
event.target.value = event.target.max
}
You can also use oninput instead of onblur but that may cause the user to have to fight the input in certain situations.
Example

Element's Value is Null - I am not representing this correctly, I think

Here's my code - I am getting an error in my firebug console that document.getElementById('deletebutton').value is null.
EDIT: To explain what I want - I want code to execute if one of two submit buttons is pressed - this is code to determine whether it was the delete button that was pressed (if not, it should have a null value) and it will execute certain code. Whenever I try to use this though, I keep getting the error message "'deletebutton' is null.
Here's the HTML:
<button type="submit" name="del" id="deletebutton" value="'.$org.'">Delete</button>
How do I account in my program for this? I set it to '', but I believe null would be a better option. Would I do:
if (document.getElementById('deletebutton').value != null
?
Here's the actual code:
<script type="text/javascript">
//<![CDATA[
function formValidation() {
var ids = ["orgname", "cultpicklist", "catpicklist", "servpicklist"]
formValue = 1;
if (document.getElementById('deletebutton').value != '' && document.getElementById('orgname').value === "") {
formValue = 0;
}
else {
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i]).value === "") {
formValue = 0;
break;
}
}
}
if (formValue == 1) {
return true;
} else if (formValue == 0) {
alert('Please fill out all required fields');
return false;
}
}
//]]>
</script>
I can't quite understand your code very well, because the HTML part is missing.
it'd be great if you could provide a jsfiddle or something similar in order to have a more accurate portrait of your situation.
Anyhow, I believe that if you just want to test the existence of the item with id "deletebutton" probably you could try something like
if( document.getElementById('deletebutton') != null )

how to set range in text field for numeric up and down?

how to set range in text field for numeric up and down?More over the value in the text box can be increase and decrease using up and down key also?
i am using textbox with two images(up and down) like (for increment) and (for decrement) here how can i set range 0 to 100 (i am working in struts)
Edit: as per Alex's answer, there is a field in HTML5, so my statement about there not been one is incorrect.
There is no numeric up down field in HTML, so I'm presuming you're using a javascript implementation ( something like this http://www.htmlforums.com/client-side-scripting/t-help-with-numericupdown-control-59399.html ).
Have the onclick event for the up and down buttons trigger a JavaScript function. In this function have it check the value that it is changing to using an if statement, and if it's too large, don't increase it, and vice versa.
You'd want something along the lines of below. I haven't used javascript for a little while so I can't vouch for the correct syntax.
if (document.getElementById("input1").value < 5)
{
document.getElementById("input1").value++
}
As for key presses, check out http://www.w3schools.com/jsref/event_onkeypress.asp . Use this to trigger the same functions that the up and down buttons on the web page trigger.
Look at the HTML5 input made for this.
<input type="number"
min="0"
max="10"
step="2"
value="6">
If you want to use JavaScript, try...
var input = document.getElementById('your-number-input'),
lowerBound = 0,
upperBound = 10;
input.onkeyup = function(event) {
event.preventDefault();
var value = parseInt(input.value, 10),
keyCode;
if (isNaN(value)) {
value = 0;
}
if (window.event) {
keyCode = event.keyCode
} else if (event.which) {
keyCode = event.which
}
if (keyCode == 38) {
value++;
} else if (keyCode == 40) {
value--;
}
if (value > upperBound) {
value = upperBound;
} else if (value < lowerBound) {
value = lowerBound;
}
input.value = value;
}
jsFiddle.

Limit Input text box with Jquery

So I need to have an input box in where people only is allowed to enter either the words "Yes" or "No". No other input is allowed. Does anybody out there knows a plugin or any other easy way to that with Jquery? I found a plugin named constraint (http://plugins.jquery.com/project/constrain), that can prevent the user from typing certain characters, but that is not enough, as the plugin can only prevent the user from typing numbers in an alphabetic field, for example. Drop down boxes or other components are not an option.
Thank you for your help.
Why not something like this (link to jsFiddle)? This will only let you type those characters that are contained in an array of allowed values? I suspect there's a better way to check for the existence of values or partial values in the array instead of looping. But this will be triggered by a user's key press, not when the control loses focus...so the UX may be better.
Hope this helps!!
HTML
Enter text: <input type="text" id="data" />
JavaScript Code
var allowedValues = ['yes','no'];
$(document).ready(function() {
$("#data").keyup(function(e) {
var typedValue = $(this).val(),
valLength = typedValue.length;
for(i=0;i<allowedValues.length;i++) {
if(typedValue.toLowerCase()===allowedValues[i].substr(0,valLength)) {
return;
}
}
$("#data").empty().val(typedValue.substr(0, valLength-1));
});
});
Based on clarification in comment, try this:
Try it out: http://jsfiddle.net/fsPgJ/2/
EDIT: Added a keypress event to deal with the user holding down a key.
$('input').blur(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no") {
this.value = '';
alert( "'Yes' or 'No' is required. \n Please try again.");
}
})
.keypress(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no")
this.value = '';
})
.keyup(function() {
var val = this.value.toLowerCase();
if("yes".indexOf(val) != 0 &&
"no".indexOf(val) != 0) {
this.value = this.value.substr(0,this.value.length - 1);
}
});
Original:
If there's some reason you're not using a <select> or :radio or something, then you could have jQuery check the value on a .blur() event.
Try it out: http://jsfiddle.net/fsPgJ/
$('input').blur(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no") {
this.value = '';
alert( "'Yes' or 'No' is required. \n Please try again.");
}
});
This just clears the input if the (case insensitive) value is not "yes" or "no". I also added an alert() to give the user a little feedback as to why the field was cleared. You may want a different feedback approach.

Categories

Resources