when pressed wil ++ or -- a value, numeric keypad - javascript

Using numeric keypad I have added a .switch handler which when clicked will bring the value back to '0' (test purpose only)
If the value is +32 and the button is pressed I would like it to change to -32, vice versa.
so far I have only gotten it to return to 0, i was thinking then deleting or adding the val again, even tried -- $('#myInput').val());
$('.switch').click(function () {
if (!isNaN($('#myInput').val()) && $('#myInput').val().length > 0) {
$('#myInput').val(parseInt($('#myInput').val()) - $('#myInput').val());
}
if (!isNaN($('#myInput').val()) && $('#myInput').val().length < 0) {
$('#myInput').val(parseInt($('#myInput').val()) + $('#myInput').val());
}
});

If all you're trying to do is switch back and forth between a positive/negative number you can make your code much simpler and lose all the if conditions:
$('.switch').click(function () {
var $input = $('#myInput');
$input.val() != "" && !isNaN($input.val()) && $input.val(-$input.val());
});
This is the equivalent of multiplying the number by -1, which will have the same effect.
Example fiddle

$('#myInput').val().length < 0
when will a length of a string be less than zero?
parseInt($('#myInput').val()) + $('#myInput').val()
this doesn't actually do numeric addition, if th value is the string 1 then it will be like doing 1+"1" which will return 11
I think what you're looking for is :
$('.switch').click(function () {
var val = parseInt($('#myInput').val());
$('#myInput').val(-val);
});
see here

Related

Set max length to the digit display for a jQuery calculator

I am trying to make a jQuery ajax calculator and I have created a html for the interface.
My problem is that I want to set a max length for the display. That would be 8 digits only. After 8 digits it would display "Err" but I should be able to clear the "Err" after I click a number.
This is my code
Here's the modified code (with explanation):
$(function(){
var $display = $('#display');
$display.val(0);
var key = null;
$(document).on('click', 'button.number', function() {
if ($display.val().length >= 8) { //If there are 8 or more characters
$display.val("Err"); //Write Err
} else if ($display.val() == "Err") { //If it says Err
$display.val("0"); //Set it to zero
} else { //If everything's fine
$display.val(($display.val() == "0" ? "" : $display.val()) + $(this).val());
//Add the pressed number to the display
//The ternary statement means "if it's zero, replace, else append"
}
});
});

Don't allow the user to enter numbers greater than 12

I have an HTML textbox as:
<input style="width: 13%; height: 25%" name="txthour" id="txthour" onkeypress="return isNumberKey(event)">
I want user to stop if they enter a number greater than 12.
When the user has entered 1, I don't want to them to enter the number 3, this will prevent the number becoming 13 (which is greater than 12).
I am dong this in Javascript as:
function isNumberKey(e) {
if (isNaN($("#txthour").val()))
{
alert("Enter only numbers");
}
if ($("#txthour").val() > 12) {
e.cancel;
}
}
But it's not cancelling the text if it enters 13.
Your first problem with your code is that you are binding it on keypress. That means $("#txthour").val() will not be updated before your event.
You need to know which character the user has pressed. There is a function for that: String.fromCharCode();.
To get the current character, you can use this:
var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
then you need to check if it is a number:
if(!isNaN(currentChar))
Then you need to concatenate that character to your input:
var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
Parse the new value and check if it's less than or equal to 12. If all of these condition matches, return true.
Final code :
function isNumberKey(e) {
var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
if(!isNaN(currentChar)){
var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
if(parseInt(nextValue, 10) <= 12) return true;
}
return false;
}
http://jsfiddle.net/6X9Yq/
Edit
To allow the press of the enter key, you need to check if the keycode is 13 :
function isNumberKey(e) {
if(e.keyCode === 13) return true;
var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
if(!isNaN(currentChar)){
var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition
if(parseInt(nextValue, 10) <= 12) return true;
}
return false;
}
Try this instead:
function isNumberKey(e)
{
var exString = $('#txthour').val();
var newString = exString + String.fromCharCode(e.keyCode);
if (isNaN(newString))
{
alert("Enter only numbers");
}
if (newString > 12)
{
e.preventDefault();
}
}
The reason your original code doesn't work is because when the keydown event is called, the value of the text box hasn't been set yet. The code above figures out what the value will be based on your keystroke, and then checks to see if the future value will be > 12. If so, then the preventDefault() call cancels your input.
jQuery solution that:
1) Checks to make sure the user only inputs numbers.
2) Makes sure the number entered is 12 or lower.
3) Alerts the user based on the criteria they're not meeting, and clears the input field.
4) Also accounts for a user pasting something into the field.
$('#txthour').on('paste input', function () {
var number = $(this).val()
if (isNaN(number)) {
alert("Enter only numbers.");
$(this).val('');
}
if (number > 12) {
alert("Value entered must be 12 or lower.");
$(this).val('');
}
});
FIDDLE
$( "#txthour" ).keyup(function() {
if($( "#txthour" ).val() > 12)
{
$( "#txthour" ).val("12");
}
});
http://jsfiddle.net/5tjdL/
The problem:
When the user types a value and you are listening to the onkeypress event, you want to be able to see what the resulting value would be so that you can compare that new value to some other value and then determine if you want to block that input via event.preventDefault() method.
Heres my solution:
1) calculate the "true" new value(now unlike most answers that were previously written that make a huge erroneous assumption "My user will only type a value at the very end of the input field"), I will take into consideration the fact that a user can actually select existing input and overwrite it...ie [before key press] inputField = "12345", user selects "12345" and presses the key for "5", so that would mean that the new value is "5", or if the user selected "234" and pressed the key for "5", the resulting value would be "155".
2) once you have the final "true" value, you can now use the isNaN() method to test if the final value is a valid number or you could just pass the final value to your own method to make whatever comparison you need and decide stop the event by calling event.preventDefault() method. here's a sample code for achieving that.
$(document).keypress(function(event)
{
//this is just a container object for readability purposes
let eventData = {
element: null,
userinput: "",
fieldname: "",
fieldValue: null,
selectionStart: -1,
selectionEnd: -1
}
eventData.fieldName = event.target.id;
eventData.element = document.getElementById(eventData.fieldName);
eventData.fieldValue = element.value; //holds the value before modification
eventData.input = String.fromCharCode(event.keyCode); //what ever the user typed!
eventData.selectionStart = event.target.selectionStart;//this records
eventData.selectionEnd = event.target.selectionEnd;//the user selection if any
let finalValue = getFinalValue(eventData);
if(!isNaN(finalValue)){
//the final value is a number and can be compared to another number!
alert("we have a number! you may proceed");
}else {
//stop right there mister!
alert("You shall not pass!");
event.preventDefault();//user input was blocked!
}
}); // this here marks the end of the onkeypress method,
// and now getFinalValue(eventData) method below...
function getFinalValue(eventData){
let finalValue = eventData.fieldValue.substring(0,eventData.selectionStart) +
eventData.input + eventData.fieldValue.substring(eventData.selectionEnd);
return finalValue;
}//end of the getFinalValue() method

using Javascript to force number precision on event Onkeypressed in textbox

what i need is to force user while they are typing in a textbox
-
the maximum number they can put is 16
if they press . they can put additional 2 digits after the dots
so what i have done so far is
<asp:TextBox ID="textbox" runat="server" Width="200" onkeypress="validateCurrencyX(this,7, 2);" >0.00</asp:TextBox>
the javascript code is
function validateCurrencyX(sender,prefix, suffix){
var something = document.getElementById('textbox').value;
var valueArr = something.split('.');
if (valueArr[1]!= null && valueArr[1].length > suffix-1)
event.returnValue = false;
if (valueArr[0].length > prefix-1)
event.returnValue = false;
}
anyway my code has problems that
- when i select the whole text, or some part of the text, and press something, it doesn't change anything
is there any ordinary way they do this ? i'm quite new to both javascript and asp.net
thank you for attention
Since you are new to both javascript and .net, it would be best that you not try to reinvent the wheel.
If you are open to using jQuery, take a look at NumberFormatter
$(".amt").blur(function(){
$(this).format({format:"#,###,###,###,###,###.00", locale:"us"});
});
This does what you want it to:
<asp:TextBox ID="textbox" runat="server" Width="200" oninput="validateCurrencyX(this,7, 2);" onkeydown="validateCurrencyX(this,7, 2);" >0.00</asp:TextBox>
JavaScript:
var validateCurrencyX = (function() {
// Closure for local oldVal variable
var oldVal = 0;
return function validateCurrencyX(sender, prefix, suffix) {
setTimeout(function() {
// Convert to number
var val = sender.value * 1,
// Get decimals
dec = sender.value.split('.')[1];
if(
val != val // NaN
|| val > 16
|| val < 0
|| dec && dec.length > suffix // check number of decimals
) {
// If the new input doesn't fit the criteria, revert to the old input.
sender.value = oldVal;
} else {
if(Math.floor(val) != 0 && sender.value.charAt(0) == '0') {
// If it's a number >= 1, remove leading '0's.
sender.value = sender.value.replace(/^0+/, '');
}
// Value is good. Save it in case we need to revert later.
oldVal = sender.value;
}
}, 0);
};
})();
Here's a working example: http://jsfiddle.net/6HUUT/4/
The key to getting a user-friendly real-time text validator is to (1) use onkeydown / oninput not onkeypress because onkeypress doesn't fire for things like paste and delete, and (2) use a setTimeout with interval 0 to check what the user actually inputs and change it after it is updated in the textbox, rather than trying to prevent them from inputting it at the outset. Again, this helps with things like paste and delete, and also inserting characters in places other than the beginning, and generally makes your life easier. The idea is just to let the user make changes, and then check them to make sure they're ok.
Note, the use of onkeydown along with oninput is used for legacy browsers. input is sufficient for modern browsers, but older browsers (circa IE8) don't support it.
This is without using javascript since you have said- is there any ordinary way they do this ? So just have a look at this:
1) the maximum number they can put is 16: for this you have the maxlength property of textbox. Set it to 16
2) This piece of code will restrict your user in entering only 2 digits after the decimal in your textbox.
//In key press event of your TextBox:
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar))
{
TextBox tt = (TextBox)sender;
if (tt.Text.IndexOf('.') > -1 && tt.Text.Substring(tt.Text.IndexOf('.')).Length >= 3)
{
e.Handled = true;
}
}

Jquery increment and decrement for dynamic generated field

I have simple
code to increment and decrement field. everything was fine but i don't know how many field I get ( it's generate by mvc) My question is how to smart bind two buttons for each field on page?
I tried to use $(this.id+"x").val(currentVal - 1) but it's wrong way , I think.
Thanks for any suggestions
Additional:
I can't use Jquery Mobile range input.
Text box "Text Pin #4" must be allways focused.
All buttons must be possible to click on Mobile device.
You can select elements relative to the one that has the event triggered on it:
$(".bplus").click(function() {
//find the input relative to this element
$(this).closest('td').prev().children('input').val(function (i, oldValue) {
//make sure the old value is being interpreted as an integer
oldValue = parseInt(oldValue, 10);
//if the old value is a valid integer below 999 then add one,
//otherwise return 999
return (oldValue != NaN && oldValue < 999) ? (oldValue + 1) : 999;
});
});
$(".bminus").click(function() {
//find the input relative to this element
$(this).closest('td').next().children('input').val(function (i, oldValue) {
//make sure the old value is being interpreted as an integer
oldValue = parseInt(oldValue, 10);
//if the old value is a valid integer above 0 then subtract one,
//otherwise return 0
return (oldValue != NaN && oldValue > 0) ? (oldValue - 1) : 0;
});
});
Here is a demo: http://jsfiddle.net/uSzr7/16/
Here is some documentation for ya:
.closest(): http://api.jquery.com/closest
.prev(): http://api.jquery.com/prev
.children(): http://api.jquery.com/children
.val(): http://api.jquery.com/val (see the section on passing .val() a function)
Another way to handle the validation is to always add or subtract one but then add a change event handler to the input elements that checks to make sure the value is valid. This helps work with native form controls since you are using the type="number" input tag.
$(".bplus").click(function(){
var txtField = $(this).parents('tr').find('input[type="number"]')
var currentVal = parseInt(txt.val());
if (currentVal < 999)
txtField.val((currentVal || 0) + 1);
});
I put (currentVal || 0), that means if currentVal==NaN, it will be replaced by 0

How can I tell between a blank textbox and a textbox with zero in it in JavaScript?

I have the following:
var NewCount = document.getElementById('MainContent_gv_NewCount_' + rowIndex).value;
if (NewCount != "") {
document.getElementById('MainContent_gv_lblTotal_' + rowIndex).innerHTML = "£" + ((originalCount - NewCount) * unitCost).toFixed(2);
} else {
document.getElementById('MainContent_gv_lblTotal_' + rowIndex).innerHTML = "";
}
The calculations I am doing are based on the value in the textbox. (NewCount).
I want the label to update if the value is any number (including 0), but to be wiped if the user clears the textbox. However, at the moment it is treating a blank textbox and a textbox with 0 in it the same.
How can I differentiate between the two?
Use !== in your if statement.
I can't reproduce the behavior you are describing. In my tests a textbox with "0" in it will be considered not blank by Javascript using your comparison logic (!= "").
Here is my attempt:
http://jsfiddle.net/pJgyu/5404/
Any of the following could work
NewCount.length > 0
NewCount !== ''
if ( NewCount.length == 0 ) {
// text-box is empty
} else if ( !isNaN(NewCount) ) {
// the value is a number
}

Categories

Resources