Changing input fields - javascript

I got a situation in which, I am validating input type using jquery.
I have html drop down list which contains different parameters("select:first-child").
I am trying validating input box based on these parameters for this I have written following code in jquery.
For example-
If I select "Quantity" then input box should take only numbers.
If I select "TradeDate" then input box should take date.
Now problem is ,when I select parameter which has type date , datepicker appears to select date.
But when I select any other parameter having type numbers ,input still showing datepicker.
So, Where I am wrong ,I want each time this validation
Here var type[1] contains type of parameter eg. float,date,char etc.
$("#cond_div").children("select:first-child").change(function(event){
var temp = $(this).val();
var type = temp.split("_");
$("#cond_div").children("input").on("keypress keyup", function () {
if (type[1].localeCompare("date") == 0) {
$(this).datepicker();
}
else if (type[1].localeCompare("float") == 0) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}
else if (type[1].localeCompare("int") == 0) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}
});
});

Once you've transformed an input with the .datepicker() creator, it stays that way until you destroy it by calling .datepicker("destroy") function.

SOLVED...
Instead of going with tricky logic ,found a simple way
$(document).ready(function () {
$("#cond_div").children("select:first-child").change(function (event) {
var temp = $(this).val();
var type = temp.split("_");
console.log("->" + temp);
console.log("->" + type);
$("#cond_div").children("input").val("");
$("#cond_div").children("input").datepicker("destroy");
if (type[1].localeCompare("date") === 0) {
console.log(type[1]);
$("#cond_div").children("input").datepicker();
} else if (type[1].localeCompare("char") === 0) {
console.log(type[1]);
$("#cond_div").children("input").attr("type", "text");
} else if (type[1].localeCompare("float") === 0) {
console.log(type[1]);
$("#cond_div").children("input").attr("type", "number");
} else if (type[1].localeCompare("int") === 0) {
console.log(type[1]);
$("#cond_div").children("input").attr("type", "number");
}
});
});

Related

HTML input field number 0-100 validation with javascript / jquery

I have a question about an input field which should only accept numbers with two digits after the dot. For this scenario I created a fully functional Fiddle example - where you can see where I am stuck right now.
My issue: I can't change the value when it's completely selected/marked.
Fiddle Example of my issue
The scripts check for:
only positive numbers
only numbers between 0 - 100
only two digits after .
only one . (dot) possible
copy&paste check implementation
// Check if keypressed and only number & .
$('#inpPercent').keypress(function(event) {
var inpVal = $(this).val();
if ((inpVal.indexOf('.') != -1) && (inpVal.substring(inpVal.indexOf('.')).length > 2)) {
event.preventDefault();
return false;
}
if (isNumberRegChecked(event, this) == false) {
event.preventDefault();
return false;
}
return isNumber(event, this)
});
// CHANGE VALID FEEDBACK OF INPUT FIELD
$('#inpPercent').on('input', function(e) {
var inpVal = $(this).val();
if (inpVal > 100 || inpVal < 0 || !inpVal) {
$("#inpPercent").removeClass("is-valid");
$("#inpPercent").addClass("is-invalid");
return false;
} else {
$("#inpPercent").removeClass("is-invalid");
$("#inpPercent").addClass("is-valid");
return true;
}
});
// PREVENT COPY PASTE
$('#inpPercent').bind("paste", function(e) {
var text = e.originalEvent.clipboardData.getData('Text');
if ($.isNumeric(text)) {
if (text > 100 || text < 0) {
$("#inpPercent").addClass("is-invalid");
} else {
$("#inpPercent").addClass("is-valid");
}
if ((text.substring(text.indexOf('.')).length > 3) && (text.indexOf('.') > -1)) {
e.preventDefault();
$(this).val(text.substring(0, text.indexOf('.') + 3));
}
} else {
e.preventDefault();
}
});
function isNumberRegChecked(evt, element) {
var inpVal = $(element).val();
var checkValue = /^(\d{0,2}(\.\d{0,2})?)$/.test(inpVal);
if (checkValue == false) return false;
return true;
};
// THE SCRIPT THAT CHECKS IF THE KEY PRESSED IS A NUMERIC OR DECIMAL VALUE.
function isNumber(evt, element) {
var charCode = evt.which ? evt.which : event.keyCode;
if (
(charCode != 46 ||
$(element)
.val()
.indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57)
)
return false;
return true;
};

Allow 2 digit number after the decimal

Hi i am trying to restrict user to input 2 digit number after the decimal.The below functionality is working but i am not able to modify the last two digit.suppose I have entered number 3456.78 and i want to modify 3456.68 it is not allowing.
$('.PMT_AMT').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Here's one possibility that uses a regular expression. Save the old input value on keypress, and if the new value on keyup does not validate, reset to that old value.
You need to validate on keypress as well, because otherwise, if the user types very fast, an invalid value can be saved:
const re = /^\d+(\.\d{0,2})?$/;
let oldVal;
$('.PMT_AMT').keypress(function(event) {
const { value } = this;
if (re.test(value)) oldVal = value;
});
$('.PMT_AMT').keyup(function(event) {
const newVal = this.value;
if (!re.test(newVal)) this.value = oldVal;
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
This solution creates a prediction and tests the regular expression against that instead.
$('.PMT_AMT').keypress(function(event) {
if(!/^\d*(\.\d{0,2})?$/.test(
this.value.slice(0, this.selectionStart)
+ String.fromCharCode(event.which)
+ this.value.slice(this.selectionEnd)
)) event.preventDefault();
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Why use jQuery and not just browser functionality?
<input type="number" step="0.01">
On submit the browser will check if the submitted value of the input field has maximum two decimals.

Auto complete is not working properly asp.net Jquery

I have write jquery code for Auto complete on text-box with onkeypress event it is working proper while text-box is empty but when i use ctrl+a or shift+tab and type to search some thing it is appending old data which resulting wrong search
e.g.
if i search "1" in text box it showing list of all records with 1
but suppose i had pressed ctrl+a or shift+tab and enter "2" it is showing list of "12" instead of "2"
<asp:TextBox ID="txtDrg" onkeypress="SearchText('DRG',this,event);" runat="server" ></asp:TextBox>
function SearchText(searchType, searchKey, event) {
if (searchType != '' && searchKey != '') {
var x = event.which || event.keyCode;
var searchKeyWord = '';
if (searchType == 'DRG') {
if (x == 8 || x == 46) {
if (searchKey.value.length > 0) {
searchKeyWord = searchKey.value.toString().slice(0, -1);
}
}
else {
if (x == 110 || x == 190)
searchKeyWord = '.';
else
searchKeyWord = String.fromCharCode(x);
if (searchKey.value != '' || searchKey.value != undefined)
searchKeyWord = searchKey.value + searchKeyWord;
}
if (valiadte)
GetAutoData(searchType, searchKeyWord);
}
}
}
function GetAutoData() {
//code
}

Form Validation Jquery object

I am trying to format the phone number field based on the country .The logic works fine when the user fill in the details but does not work when the country is changed and filled in again.
Ex:
Filled in the form for Germany and then without reloading the page if try change county to US and fill in phone "+" is being added even though format for it is different.
$(document).ready(function($){
$('#country').on('change', function() {
if ( this.value == 'US' || this.value == 'CA')
{
$('#C_BusPhone')
.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val);
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
}
else
{
$('#C_BusPhone')
.keydown(function (e) {
if ($(this).val().indexOf("+") === -1) {
$(this).val("+" + $this.val());
}
})
}
});
});
Not sure if this was the cause for your error, but this line needs to get corrected from
$(this).val("+" + $this.val());
to this
$(this).val("+" + $(this).val());
It was a fast catch, just use your browser javascript console for debugging.
See the updated fiddle here. You might want to add the starting parenthesis to your international prefix as well.

Restricting Input to numbers only(-100.00 to 100.00) in a HTML input field

I am trying to restrict html input field to accept numbers only
The JS code is working fine with English keyboard on an android device but when i change keyboard to Japaneses it starts accepting Japaneses characters.
(Update: Japanese input problem solved only - and decimal point is not being entered)
Here is the HTML
<input type='text' style='height: 100%;' name='lmt_c13' id='lmt_c13' isNumeric='true' onblur='updateJudgment(this);' onkeyup='removeSpaces(this);' onkeypress='return isNumberKey(event,this);' class='txtCtrl' >0</input>
and here is the JS code
function isNumberKey(evt, control) {
if ($(control).attr("isNumeric") == "true") {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) || charCode == 13)
return false;
return true;
}
};
the input I want in this input field in something like -12.24 and 23.78
See the
// Restricts input for each element in the set of matched elements to the given inputFilter.
(function($) {
$.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
};
}(jQuery));
// Install input filters.
$("#intTextBox").inputFilter(function(value) {
return /^-?\d*$/.test(value); });
$("#uintTextBox").inputFilter(function(value) {
return /^\d*$/.test(value); });
$("#intLimitTextBox").inputFilter(function(value) {
return /^\d*$/.test(value) && (value === "" || parseInt(value) <= 500); });
$("#floatTextBox").inputFilter(function(value) {
return /^-?\d*[.,]?\d*$/.test(value); });
$("#currencyTextBox").inputFilter(function(value) {
return /^-?\d*[.,]?\d{0,2}$/.test(value); });
$("#latinTextBox").inputFilter(function(value) {
return /^[a-z]*$/i.test(value); });
$("#hexTextBox").inputFilter(function(value) {
return /^[0-9a-f]*$/i.test(value); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>jQuery input filter showcase</h2>
<p>Supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, and all browsers since IE 9.</p>
<p>There is also a pure JavaScript version of this (without jQuery).</p>
<table>
<tr><td>Integer</td><td><input id="intTextBox"></td></tr>
<tr><td>Integer >= 0</td><td><input id="uintTextBox"></td></tr>
<tr><td>Integer >= 0 and <= 500</td><td><input id="intLimitTextBox"></td></tr>
<tr><td>Float (use . or , as decimal separator)</td><td><input id="floatTextBox"></td></tr>
<tr><td>Currency (at most two decimal places)</td><td><input id="currencyTextBox"></td></tr>
<tr><td>A-Z only</td><td><input id="latinTextBox"></td></tr>
<tr><td>Hexadecimal</td><td><input id="hexTextBox"></td></tr>
</table>
for more input filter examples. Also note that you still must do server side validation!
If you want to know more about regular expressions see this link: https://www.w3schools.com/jsref/jsref_obj_regexp.asp
For decimal point allow, You can add below condition :: || charCode == 46
if (charCode > 31 && (charCode < 48 || charCode > 57) || charCode == 13 || charCode == 46 )
Or if you want to test decimal validation then
function CheckDecimal(inputtxt)
{
var decimal= /^[-+]?[0-9]+\.[0-9]+$/;
if(inputtxt.value.match(decimal))
{
return true;
}
else
{
return false;
}
}
Hope it helps
i think me i'll do this: (using regular expressions)
function isNumberKey(control) {
if ($(control).attr("isNumeric") == "true") {
var regex = /^[0-9.-]$/;
var _event = event || window.event;
var key = _event.keyCode || _event.which;
key = String.fromCharCode(key);
if(!regex.test(key)) {
//alert(key);
_event.returnValue = false;
if (_event.preventDefault)
_event.preventDefault();
}
}
};
function isDecimal(control) {
if ($(control).attr("isNumeric") == "true") {
var regex = /^[-]?[0-9]+[.]?[0-9]*$/;
str = $(control)[0].value;
var _event = event || window.event;
if(!regex.test(str)) {
var m = str.match(/^[-]?[0-9]+[.]?[0-9]*/g);
$(control)[0].value = m[0];
_event.returnValue = false;
if (_event.preventDefault)
_event.preventDefault();
}
}
};
and my html:
<input type='text' style='height: 20px;' name='lmt_c13' id='lmt_c13' isNumeric='true' onblur='updateJudgment(this);' onkeyup='isDecimal(this);' onkeypress='isNumberKey(this);' class='txtCtrl' value='0' />
please try it and tell me if it works.

Categories

Resources