Jquery increment and decrement for dynamic generated field - javascript

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

Related

Decrementing and incrementing value in Jquery

I am trying to calculate discount on the fly using the following jquery code.
$(document).on("change keyup blur", "#chDiscount", function(){
var amd=$('#cBalance').val();
var disc = $('#chDiscount').val();
if(isNaN(disc)){
disc = 0;
}
$('#cBalance').val(amd-disc);
});
To escape non-numeric key:
var specialKeys = new Array();
specialKeys.push(8,46); //Backspace
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode;
console.log( keyCode );
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
return ret;
}
The problem is When I type in chDiscount input, the new value of cBalance is fine but When I erase the chDiscount value, I could no longer get the old(default) value of the cBalance input. I want the old value if I delete the Discount value. How can I do that? Please help. Thanks.
are you using jquery? I'm fan with jquery so I'll have my suggestion base on jquery. You can get ideas with this I hope.
What about store the initial value first using in the element jquery has that example.
$('#cBalance').data({origValue: 999});
Try this simple fiddle https://jsfiddle.net/jeorlie/b71epf02/
try using 10 as input in balance and deduct it with 3(assuming 3 was the total discount). You would get 7 in the balance. If you remove the discount (make it 0) you will have the original value.
This code in fiddle is buggy but you can get ideas with it, just analyze it. By the way. You can you store original value of Balance into a variable which is globally accessible. Hope you get ideas with it.

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

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

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

How to check value of a textbox that contain _age at the end?

This might be some odd question but it is the problem I am facing. I have textBox with Id like:
"pax_9495237e-5c9e-489f-8700-2f82e211fd51__Age"
"pax_9495237e-9h7e-489f-8700-2f82e211fd51__Age"
"pax_9495237e-9k2e-489f-8700-2f82e211fd51__Age"
Now I want to check if all Textboxes consist of __Age at the end, has numeric value or not. If not numeric(INT) i.e. characters(no .) not allowed then make an alert.
Please help me I don't know how to do it. I know I have a class option but I want to do by Id.
To select you input, you can use this :
$('[id$="__Age"]')
Then to know if is a number
$('[id$="__Age"]').each(function(){
if(isNaN(parseInt($(this).val()))){
alert(this,id + ' is not a number');
}
})
Fiddle : http://jsfiddle.net/3B9Vp/
In order to get all input ending with "__Age" you can use the jquery selector
jQuery( "[attribute$='value']" )
You can find more details here
So, in your occasion you can call:
$('input[id$="__Age"]');
where all text boxes with an id ending in "__Age" will be returned.
In order to validate if the input is numeric you can check the value of each textbox and use isNaN function provided in Javascript
Here is an example where there are 3 text boxes and you call a function to check if their current value is numeric or not.
Try like this
$(document).ready(function(){
$("input[type='text'][id$='__Age']").each(function(){
if(isNaN(parseInt($(this).val())))
alert('Not an Integer');
else
alert('It is an Integer');
});
});
It will check all the textbox values that are ids ended with '__Age'
Something like:
$("textarea").filter(function(i) { return $(this).prop("id").indexOf("__Age") !== -1; })
http://api.jquery.com/filter/
http://api.jquery.com/jQuery.inArray/
How to check whether a string contains a substring in JavaScript?
Working Example
// an array of e.which|e.key codes that is every key code for every number and control (like shift, backspace, etc..)
var numsNcontrols = [48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,8,9,13,16,17,18,19,20,32,33,34,35,36,45,46,44,145,37,38,39,40];
// first grab all inputs ending with "__Age", then asign "keydown" check for improper characters
$("input[type=text]").filter(function(i) { return $(this).prop("id").indexOf("__Age") !== -1; }).on("keydown", function(e) {
if ($.inArray(e.which, numsNcontrols) == -1) return false;
}) // now, using jQuery Chaining, we continue and asign keyup event to alert users they cannot enter anything but numbers
.on("keyup", function(e) {
if ($.inArray(e.which, numsNcontrols) == -1) alert('Numbers only please!');
})
// simple check value update to show how many textboxes end in "__Age"
$("#bil").val(
$("input[type=text]").filter(function(i) { return $(this).prop("id").indexOf("__Age") !== -1; }).length
+ " textboxes have __Age at end of ID."
);
// Shows in a textbox how many textboxes end in "__Age" && have a numeric value
$("#bad").val(
$("input[type=text]").filter(function(i) { return $(this).prop("id").indexOf("__Age") !== -1 && !isNaN(parseInt($(this).val())); }).length
+ " textboxes have __Age at end of ID && numeric value."
);
¡ALSO! Find a pretty full listing in one big object (full of smaller objects and arrays) of Key Codes here
If you only need to show one alert when any of the inputs with __Age at the end has nonNumeric values then you can try something like this:
if($("input[type='text'][id$='__Age']").filter(function(){
return !isNaN($(this).val()); //leave only those inputs with nonNumeric value
}).length) //count their lenght - if it's > 0 then show alert
alert('There are inputs with "nonNumeric" values!');

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;
}
}

Categories

Resources