set focus textboxes onkeypressed - javascript

im writing payment page and there is 4 textbox for credit card number entry and after for digits set focus on another control i did for first textbox my javascript code works well but other textboxes doesnt work... here is my code...:
<script type="text/javascript">
function Length_txtCardNumber1_Validator() {
if (document.getElementById('<%= txtCardNumber1.ClientID %>').value.length = 4) {
document.getElementById('<%= txtCardNumber2.ClientID %>').focus();
return (false);
}
return (true);
}
function Length_txtCardNumber2_Validator() {
if (document.getElementById('<%= txtCardNumber2.ClientID %>').value.length = 4) {
document.getElementById('<%= txtCardNumber3.ClientID %>').focus();
return (false);
}
return (true);
}
function Length_txtCardNumber3_Validator() {
if (document.getElementById('<%= txtCardNumber3.ClientID %>').value.length = 4) {
document.getElementById('<%= txtCardNumber4.ClientID %>').focus();
return (false);
}
return (true);
}
</script>
code behind onpage_load :
txtCardNumber1.Attributes.Add("onkeypress", "return Length_txtCardNumber1_Validator()");
txtCardNumber2.Attributes.Add("onkeypress", "return Length_txtCardNumber2_Validator()");
txtCardNumber3.Attributes.Add("onkeypress", "return Length_txtCardNumber3_Validator()");
thank you...

Use == for comparison.
function Length_txtCardNumber3_Validator() {
if (document.getElementById('<%= txtCardNumber3.ClientID %>').value.length == 4) {
document.getElementById('<%= txtCardNumber4.ClientID %>').focus();
return (false);
}
return (true);
}

You can have "generic" code without depending on ID or name of the textboxes, plus allowing only digits as a bonus.
First, wrap all textboxes with single container and give them maxlength like this:
<div id="CreditCardPanel">
<asp:Textbox id="txtCardNumber1" runat="server" Columns="3" MaxLength="4" /> -
<asp:Textbox id="txtCardNumber2" runat="server" Columns="3" MaxLength="4" /> -
<asp:Textbox id="txtCardNumber3" runat="server" Columns="3" MaxLength="4" /> -
<asp:Textbox id="txtCardNumber4" runat="server" Columns="3" MaxLength="4" />
</div>
Now all you have to do is having such JS code and it's all done:
<script type="text/javascript">
var arrCreditCardInputs = [];
window.onload = function WindowLoad() {
var arrInputs = document.getElementById("CreditCardPanel").getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oCurInput = arrInputs[i];
if (oCurInput.type == "text") {
oCurInput.onkeypress = function(event) {
//allow digits only:
var keyCode = event.keyCode || event.which;
if (keyCode >= 48 && keyCode <= 57) {
if (this.value.length + 1 >= this.maxLength) {
var index = parseInt(this.getAttribute("arr_index"), 10);
var nextIndex = ((index + 1) % arrCreditCardInputs.length);
window.setTimeout(function() {
arrCreditCardInputs[nextIndex].focus();
}, 200);
}
return true;
}
else {
return false;
}
}
oCurInput.setAttribute("arr_index", i + "");
arrCreditCardInputs.push(oCurInput);
}
}
}
</script>
Basically, the code is taking all the textbox elements in the container, and assign their onkeypress event so that only digits can be pressed and when reaching the maximum length focus the next textbox as defined in the global array containing them.
Timer is used to allow the browser a chance to change the value of the textbox, otherwise setting focus immediately will "cancel" the key press and the value won't change.
Live test case is available here, try messing around with the code and understand how it works. :)

I bound the keyup event to the textboxes
$('#ccNumber1').bind('keyup',function () {
if ($(this).val().length == 4)
$('#ccNumber2').focus();
});

Related

Allow only First two and last two are alphabets and rest in between are numeric(e.g EE123456789IN) in text box

Hey I am trying to validate a textbox for getting first two and last two char are alphabets and rest of are numeric in between in the length of 13. eg EE123456789IN . How to validate this in textbox and also check this on submit button.`
function Validate_Post() {
var tb = document.getElementById("<%=txt_SpeedPost.ClientID%>").value;
var a = tb.charAt(0);
var b = tb.charAt(1);
var c = tb.charAt(11);
var d = tb.charAt(12);
if ((a != 'E' && b != 'E') || (c != 'I' && d != 'N') || d != 'N') {
alert("Invalid Speed Post Ref. No The Speed Post Ref No must be like this EE123456789IN") enter code here
}
for (var i = 3; i < 11; i++) {
if ((tb.charAt(i) >= 48 && tb.charAt(i) <= 57) || (tb.charAt(i) >= 96 && tb.charAt(i) <= 126)) {
alert("Enter Number after EE e.g EE123456789IN")
}
}
return true
}
<asp:Button ID="Btn_submit" runat="server" Text="SUBMIT" align="center" Width="168px " OnClick="Btn_submit_Click" OnClientClick="Validate_Post();" style="font-weight: 700"/>
I want result like this that textbox should validate e.g EE123456789IN and max length should be 13 and textbox only accepts this kind of input. if not then it will show error during submit. can you help me out of this.
I don't know ASP.NET, but you can do it with pure HTML without Javascript
<form action='/somewhere' method='post'>
<input type='text' pattern='[A-Z]{2}\d{9}[A-Z]{2}' required />
<input type='submit' />
</form>
Please use below code and let me know if you face any issue or you need any change in it.
SpeedPost:
<asp:TextBoxID="txt_SpeedPost" runat="server" maxlength=13 />
<asp:Button ID="Btn_submit" runat="server" Text="SUBMIT" align="center" Width="168"
OnClick="Btn_submit_Click" OnClientClick="return Validate_Post();" style="font-
weight: 700"/>
<script>
function Validate_Post() {
var tb = document.getElementById("<%=txt_SpeedPost.ClientID%>").value;
var length = tb.length;
var first2 = tb.substr(0, 2);
var last2 = tb.substr(length - 2, length);
//alert(first2 + '::' + last2);
var isAlphabet = allLetter(first2+last2);
//if(first2 != 'EE' || last2 != 'IN')
if(!isAlphabet)
{
alert("Invalid Speed Post Ref. No The Speed Post Ref
No must be like this EE123456789IN");
return false;
}
var centerLength = length - first2.length - last2.length;
var centerChars = tb.substr(2, centerLength);
//alert(centerChars);
if (isNaN(centerChars))
{
// not a number
alert('not a number');
return false;
}
return true;
}
function allLetter(inputtxt)
{
var letters = /^[A-Za-z]+$/;
if(inputtxt.match(letters))
{
return true;
}
else
{
return false;
}
}
</script>

Get Value From Dynamic textarea

In the given code i have create a dynamic textarea, now when i try to get insert value from that textarea. It gives me null value.
<form name="myForm">
<textarea name="fname" <%#!((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).Code.Equals("OTH", StringComparison.InvariantCultureIgnoreCase) ? "style='display: none;'" : string.Empty%> id="text<%#((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).ID%>" maxlength="50" placeholder="Enter other item details"></textarea>
</form>
Given is my function to get value from textarea box:
function ValidateData() {
if ($("textarea").is(":visible")) {
//var x = document.forms["myForm"]["fname"].value;
var x = document.getElementsByName("fname").value;
if (x == null || x == "") {
alert("Please Enter Other Item Details");
return false;
}
}
else return true
}
Your textarea was dynamic so you can used textarea change event. You can use given code on load, so whenever you input text it sets on OtherItemValue:
var OtherItemValue;
$("textarea").on('input change keyup', function () {
if (this.value.length) {
OtherItemValue = this.value;
} else {
OtherItemValue = "";
}
});
And then you can used below code:
function ValidateData() {
if ($("textarea").is(":visible")) {
if (OtherItemValue == null || OtherItemValue == "") {
alert("Please Enter Other Item Details");
return false;
}
}
else return true
}
Since you are using jQuery already, why don't you use it to achieve the desired result?
Your code would look like this:
function ValidateData() {
if ($("textarea").is(":visible")) {
var x = $("textarea").val();
if (x == null || x == "") {
alert("Please Enter Other Item Details");
return false;
}
}
return true
}
If you really need to use standard library, #Rachit Gupta's answer should solve the problem.
<form name="myForm">
<textarea name="fname" <%#!((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).Code.Equals("OTH", StringComparison.InvariantCultureIgnoreCase) ? "style='display: none;'" : string.Empty%> id="text<%#((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).ID%>" maxlength="50" placeholder="Enter other item details"></textarea>
</form>
Your function should now look like this
function ValidateData() {
if ($("textarea").is(":visible")) {
//var x = document.forms["myForm"]["fname"].value;
var x = document.getElementsByName("fname")[0].value;
if (x == null || x == "") {
alert("Please Enter Other Item Details");
return false;
}
}
else return true
}
The problem with your code is that getElementsByName will get a list of elements, which don't have a value property. You need to get only a particular element and get its value. This solution may solve your problem, but will work if you don't have any other element with name as fname above the textarea.
Use jquery .val() method to retrieve the value of the text area.
you need to initialise textarea to empty at document ready function.
$(document).ready(function(){
$("textarea[name='fname']").val("");
});
function ValidateData() {
if ($("textarea").is(":visible")) {
var x = $("textarea[name='fname']").val();
if (x == null || x == "") {
alert("In if " + x);
return false;
}
else {
alert("In else" + x);
}
}
else {
return true
}
}

Multi delete checkbox on button click does not work as required

I have a grdiview in which I have added the Multi-delete functionality. Please see the code for your reference:-
<script type="text/javascript">
function ValidateAll() {
var chkselectcount = 0;
var gridview = document.getElementById('<%= grdTeacherProfile.ClientID %>');
for (var i = 0; i < gridview.getElementsByTagName("input").length; i++) {
var node = gridview.getElementsByTagName("input")[i];
if (node != null && node.type == "checkbox" && node.checked) {
chkselectcount = chkselectcount + 1;
}
}
if (chkselectcount == 0) {
alert("Please select atleast One CheckBox");
return false;
}
else {
ConfirmationBox();
}
}
function ConfirmationBox() {
var result = confirm("Are you sure, you want to delete the Users ?");
if (result) {
return true;
}
else {
return false;
}
}
</script>
Also see the button html:-
<asp:Button ID="btnDelete" runat="server" CausesValidation="false" CssClass="btn btn-danger" Text="Delete" OnClick="btnDelete_Click" OnClientClick="javascript:return ValidateAll();" />
The issue is that,
when I check the checkboxes and Click on delete button, it asks for confirmation. When I click on Cancel it still deletes the row from the Gridview as well as sql table.
What should I do for the proper working of this. ? Please suggest
I think you need to use
return ConfirmationBox();
instead of
ConfirmationBox();
So your code becomes
function ValidateAll() {
var chkselectcount = 0;
var gridview = document.getElementById('<%= grdTeacherProfile.ClientID %>');
for (var i = 0; i < gridview.getElementsByTagName("input").length; i++) {
var node = gridview.getElementsByTagName("input")[i];
if (node != null && node.type == "checkbox" && node.checked) {
chkselectcount = chkselectcount + 1;
}
}
if (chkselectcount == 0) {
alert("Please select atleast One CheckBox");
return false;
}
else {
return ConfirmationBox();
}
}
You need to remove the javascript: from OnClientClick you can use OnClientClick="return ValidateAll();"

How to restrict type of input when user press Tab in asp.net?

I have a text box in which the SSN number is inserted by user the TexBox has a default value as 'XX-XX-' and then he enters four digit number after 'XX-XX-' only. I have javascript but when he press tab the text in TexBox i.e 'XX-XX-' is get selected and it Flush all the selected text. I want to restrict it to enter only after 'XX-XX-' eg: XX-XX-1234 how to do?
.aspx page:
<asp:TextBox ID="txtInsuredSSN" runat="server" Text="XX-XX-" MaxLength="10" onkeydown="return validateSSN(event);" />
Javascript:
function validateSSN(key) {
//getting key code of pressed key
var keycode = (key.which) ? key.which : key.keyCode;
var phn = document.getElementById('<%#txtInsuredSSN.ClientID %>');
if (phn.selectionStart < 6)
return false;
//comparing pressed keycodes
if ((keycode < 48 || keycode > 57)) {
if ((keycode > 95 && keycode < 106) && phn.value.length < 10)//if num lock is on
{
return true;
}
else if (keycode = 8 && phn.value.length > 6) { //check for backspace
return true;
}
else {
return false;
}
}
else {
//Condition to check textbox contains ten numbers or not
if (phn.value.length < 10) {
return true;
}
else {
return false;
}
}
}
Plz suggest any solution?
use a label for the hard coded prefix, something like :
<label>
<span class="frmlabelleftfloat">SSN: xx-xx-</span>
<asp:TextBox ID="Last4OfSSN" runat="server" ValidationGroup="ssnValidation" MaxLength="4"></asp:TextBox>
<span class="failureNotification">*</span>
<asp:RegularExpressionValidator ID="regexpssn" runat="server" ControlToValidate="Last4OfSSN"
ValidationGroup="ssnValidation" Display="Dynamic" ForeColor="Red" ErrorMessage="Should be 4 Digits"
ValidationExpression="\\d{4}?$"> </asp:RegularExpressionValidator>
</label>
you need to verify that regex though.

How to simulate TAB on ENTER keypress in javascript or jQuery

I want to change keycode in keydown ( key press ) in all input in a page.I want to replace Enter keycode with TAB key code. How I can do this?
thanks
EDIT 1)
Consider this code:
<div>
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
</asp:RadioButtonList>
<br />
<br />
<asp:TextBox ID="TextBox1" runat="server">3333</asp:TextBox>
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
</div>
I want when user press Enter on eny of above control focus go to next control.
thanks
I've had a similar problem, where I wanted to press + on the numpad to tab to the next field. Now I've released a library that I think will help you.
PlusAsTab: A jQuery plugin to use the numpad plus key as a tab key equivalent.
Since you want enter/↵ instead, you can set the options. Find out which key you want to use with the jQuery event.which demo.
JoelPurra.PlusAsTab.setOptions({
// Use enter instead of plus
// Number 13 found through demo at
// https://api.jquery.com/event.which/
key: 13
});
Then enable the feature by adding plus-as-tab="true" to the form fields you want to use enter-as-tab in, or some other element that contains these form fields. Radio buttons should not be a problem, as they are covered by my other library, EmulateTab - see autonavigation of radio buttons in that demo.
<div plus-as-tab="true">
<!-- all focusable elements inside the <div> will be enabled -->
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<!-- Radio buttons should not be a problem. -->
</asp:RadioButtonList>
</div>
You can try it out yourself in the PlusAsTab enter as tab demo.
This code is to replace enter with tab character:
$("#wmd-input").bind("keypress", function(e) {
if (e.keyCode == 13) {
var input = $(this);
var inputVal = input.val();
setTimeout(function() {
input.val(inputVal.substring(0,inputVal.length) + "\t");
}, 1);
}
});
Live Demo
UPDATE:
This code is to focus to on the next element:
$(document).ready(function () {
$("input,select").bind("keydown", function (e) {
if (e.keyCode == 13) {
var allInputs = $("input,select");
for (var i = 0; i < allInputs.length; i++) {
if (allInputs[i] == this) {
while ((allInputs[i]).name == (allInputs[i + 1]).name) {
i++;
}
if ((i + 1) < allInputs.length) $(allInputs[i + 1]).focus();
}
}
}
});
});
Hope this works
$('input,textarea').keydown(function(){
if(event.keyCode==13) {
event.keyCode = 9;
}
});
Edit
Try this http://jsfiddle.net/GUmUg/. Play around with selectors to make this work as i don't know asp
$('input,textarea').keypress(function(e){
if(e.keyCode==13) {
$(this).next().focus();
}
});
$('input').on('keydown',function(e){
var keyCode = e.keyCode || e.which;
if(e.keyCode === 13) {
e.preventDefault();
$('input')[$('input').index(this)+1].focus();
}
});
check fiddle here : http://jsfiddle.net/Pd5QC/
The way I do it is by using jquery to each over your selection and focusing on the element after the current on you are on.
$(document).on('keyup', '.my-input', function (ev) {
if (ev.keyCode == '13') {
var currentInput = this;
var isOnCurrent = false;
$('.my-input').each(function () {
if (isOnCurrent == true) {
$(this).focus();
return false;
}
if (this == currentInput) {
isOnCurrent = true;
}
});
}
});
I think this work:
$('input').live("keypress", function (e) {
/* ENTER PRESSED*/
var OffSet = 0;
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
if ($(this).is("input[type='radio']")) {
var tblID = $(this).closest('table').attr('id');
var radios = $('#' + tblID).find(":input");
//alert(radios.index(this));
OffSet = radios.length - radios.index(this) - 1;
}
//alert(OffSet);
var inputs = $(this).parents("form").eq(0).find(":input");
var idx = inputs.index(this);
inputs[idx + OffSet].blur();
try {
inputs[idx + OffSet].selectionStart = inputs[idx + OffSet].selectionEnd = -1;
} catch (e) {
}
if (idx == inputs.length - 1) {
inputs[0].select();
} else {
inputs[idx + 1 + OffSet].focus(); // handles submit buttons
try {
inputs[idx + 1 + OffSet].select();
} catch (e) {
}
}
return false;
}
});
I created a simple jQuery plugin which does solve this problem. It uses the ':tabbable' selector of jQuery UI to find the next 'tabbable' element and selects it.
Example usage:
// Simulate tab key when enter is pressed
$('.myElement').bind('keypress', function(event){
if(event.which === 13){
if(event.shiftKey){
$.tabPrev();
}
else{
$.tabNext();
}
return false;
}
});
$(document).ready(function() {
//Objetos con CssClass="EntTab" sustituye el Enter (keycode 13) por un Tabulador (keycode 9)!!
$(".EntTab").bind("keypress", function(e) {
if (e.keyCode == 13) {
var inps = $("input, select"); //add select too
for (var x = 0; x < inps.length; x++) {
if (inps[x] == this) {
while ((inps[x]).name == (inps[x + 1]).name) {
x++;
}
if ((x + 1) < inps.length) $(inps[x + 1]).focus();
}
} e.preventDefault();
}
});
});

Categories