For some reason none of my setfocus() events were working on the server side of my web app, so I created a Javascript function setfocus that is set to trigger on the onload event of the body tag.
<body onload="SetFocus()">
The user will click a radio button which enables the drop down. they select from the drop down which enables the textbox. When they scan a barcode into the textbox it will automatically tab out of the field, therefore triggering the onchange event to call some server side code which, if a successful SQL insert is completed, will insert a new row to the gridview, and it should set focus automatically back to the textbox via Javascript. Once that gridview object has more than a header and a row of data, I disable the drop down and radio button list, so if you look at the Javascript below, I can't use those as criteria in my if statement anymore.
Javascript:
var MatAllRB = document.getElementById("HF_RB_MatAll").value;
var MatAllCL = document.getElementById("DD_SelectCL_All").value;
var MatAll = document.getElementById("Txt_MatBC_All");
var MatAllPrompt = document.getElementById("HF_AllPrompt").value;
var count = $("#GV_Scan_All tr").children().length;
This works perfectly:
else if (ActiveTab == "cont-3" && MatAllRB != "" && MatAllCL != "")
{ alert("went into setfocus");
document.getElementById("Txt_MatBC_All").focus();
alert("made it through setfocus");
}
This only works if you actually click off the field, the tab doesn't work. It just does nothing.
else if (ActiveTab == "cont-3" && count == 9)
{ alert("went into setfocus");
document.getElementById("Txt_MatBC_All").focus();
alert("made it through setfocus");
}
This does the same thing as the above:
else if (ActiveTab == "cont-3" && (MatAllPrompt == "RP" || MatAllPrompt == "P03"))
{ alert("went into setfocus");
document.getElementById("Txt_MatBC_All").focus();
alert("made it through setfocus");
}
The weird thing is that all of these alerts that I have in here show up correctly, it just never sets focus. I am pretty new at this stuff still, so maybe I'm missing something, but I can't figure out why the focus() will work for click off rather than tabbing off. Any help would be appreciated.
Here's the HTML:
<asp:RadioButtonList runat="server" ID="RB_Mat_All" AutoPostBack="true" RepeatColumns="4" OnSelectedIndexChanged="RB_Mat_All_OnSelectedIndexChange">
<asp:ListItem Text="NC" value="NC"></asp:ListItem>
<asp:ListItem Text="DA" value="DA"></asp:ListItem>
<asp:ListItem Text="GW" value="GW"></asp:ListItem>
<asp:ListItem Text="PC" value="PC"></asp:ListItem>
</asp:RadioButtonList>
<asp:HiddenField runat="server" ID="HF_RB_MatAll"></asp:HiddenField >
<br />
<asp:DropDownList runat="server" ID="DD_SelectCL_All" AutoPostBack="true" OnSelectedIndexChanged="DD_SelectCL_All_OnSelectedIndexChange">
<asp:ListItem Value="" Text="Select..."></asp:ListItem>
<asp:ListItem value="53" text="05"></asp:ListItem>
<asp:ListItem value="54" text="06"></asp:ListItem>
<asp:ListItem value="55" text="07"></asp:ListItem>
<asp:ListItem value="57" text="08"></asp:ListItem>
<asp:ListItem value="58" text="09"></asp:ListItem>
</asp:DropDownList>
<asp:label runat="server" ID="Lbl_All_Prompt" CssClass="Form" Text=""></asp:label>
<asp:HiddenField runat="server" ID="HF_AllPrompt"></asp:HiddenField >
<asp:TextBox runat="server" ID="Txt_MatBC_All" Cssclass="Form" Text="" AutoPostBack="true" OnTextChanged="Txt_MatBC_All_TextChanged"></asp:TextBox>
<asp:GridView runat="server" ID="GV_Scan_All" CssClass="Form_Feedback"></asp:GridView>
When I view the source the textbox looks like this:
<input name="Txt_MatBC_All" type="text" onchange="javascript:setTimeout('__doPostBack(\'Txt_MatBC_All\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="Txt_MatBC_All" class="Form" />
It's odd that you can click off the field and it works, but tabbing off doesn't. Try adding tabIndexes to the inputs on your page.
The ids of your text box, change when the asp.net render the page. So try this to get the id dynamically and see if its works.
document.getElementById("<%=Txt_MatBC_All.ClientID%>").focus();
The same way you must use the ClientID on every getElementById you use.
by the way, on every line you focus the same text control (Txt_MatBC_All). If this is the case, why you make all that if, just use one line.
tip 1: you can see if your getElementById found the control by make teamporary an alert call like alert(document.getElementById("<%=Txt_MatBC_All.ClientID%>"));
tip 2: Right click on your browser and see the source code of your page to see what ids your control have take, to see if you actually is correct and the same with the javascript you use.
Try converting your JavaScript to square bracket notation. For example: document.forms[0].Txt_MatBC_All.focus();
Related
I've a page where on page load event I've set focus on a textbox using javascript. But after button press I've to set focus on different text box of different asp:Panel. Is this possible using javascript? Currently I am doing this via code behind page.
<script type="text/javascript">
$(function () {
document.getElementById('<%=txtPassengerId.ClientID%>').focus();
});
</script>
<asp:Panel ID = "firstPanel" >
<asp:TextBox ID="txtPassengerId" runat="server"/>
<asp:Button ID="btn_search" runat="server" Text="Search" OnClick="btn_search_Click" />
</asp:Panel>
<asp:Panel ID = "secondPanel" >
<asp:TextBox ID="txtDestination" runat="server"/>
</asp:Panel>
After the button pressed secondPanel is visible and I need to focus on txtDestination text box. Is this possible using javascript?
Yes, you have to use the selector you've used "document.getElementById" and use the .focus() function.
document.getElementById("secondpanel").style.visibility = "visible";
document.getElementById("txtDestination").focus();
should do it. if you need more just comment.
I know it has been asked several times and I found many solutions but no solution worked for me.
I am working on IE
<asp:RadioButtonList ID="rbtnView" runat="server" OnSelectedIndexChanged="rbtnView_SelectedIndexChanged"
AutoPostBack="True" TabIndex="7" RepeatDirection="Horizontal">
<asp:ListItem Selected="True" Value="0">Show Pending</asp:ListItem>
<asp:ListItem Value="1">Show Processed</asp:ListItem>
</asp:RadioButtonList>
here is the button code from where I am calling the function:
<asp:Button ID="btnPrint" runat="server" CssClass="myButton" OnClick="btnPrint_Click"
Text="Print" ValidationGroup="validationgroup2" TabIndex="9" OnClientClick="doPrint()" />
here is the javascrit function
function doPrint() {
debugger;
var rad = $('#<%=rbtnView.ClientID %> input[type=radio]:checked').val();
}
Any help would be appreciated.
var radioValue = $("input[name='YOURVALUEFORTHEGROUP']:checked").val();
replace YOURVALUEFORTHEGROUP
The javascript function works just fine. But you are doing a form post (PostBack) when pressing the btnPrint button.
You can use a regular button instead of an asp.net Control. Or if you need a PostBack to execute the btnPrint_Click method. But then you can get the value there. It all depends why you need the value client side.
<input type="button" value="Get value" onclick="doPrint()" />
Or add return false to the aspnet button.
OnClientClick="doPrint(); return false;"
I am trying to get a javascript function to work properly with my asp.net controls. I have two radio buttons and three textboxes.
When the first radio button is clicked I would like to disable the third textbox and when the second radio button is clicked I would like to disable the third text box. See the attachment for a screenshot.
I have tested that the function works by adding "OnClick" to the first radio button and setting AN ALERT WHICH IS WORKING.
However, I am not sure how to pass the controls in to the function to have access to them. Anyone know how to do this?
Screenshot
ASP.NET
<asp:RadioButton ID="RadioButton1" runat="server" Checked="True" GroupName="DateTimeQuery" OnClick="TimeRangeClickEvent()"/>
<asp:TextBox ID="startdatetext" Enabled="true" runat="server" MaxLength="10"></asp:TextBox>
<asp:TextBox ID="enddatetext" Enabled="true" runat="server" MaxLength="10"></asp:TextBox>
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="DateTimeQuery" OnClick="TimeRangeClickEvent() />
<asp:TextBox ID="withinthepast" Enabled="true" runat="server" Text="1"></asp:TextBox>
Javascript
<script>
function TimeRangeClickEvent(How do I pass asp.net controls here)
{
alert('Working');
}
</script>
You should use ClientID control properties to get IDs of HTML elements and then work with them from Javascript. More info.
In Javascript:
var radio1 = document.getElementById('<%=RadioButton1.ClientID%>');
When you have all your HTML elements you just need to handle necessary change/clicked/selected events in javascript to make it work.
I'm developping a form page in a WebForms application.
I have a RadioButtonList and a Panel, and I wanted the panel to open when a especific value of the RadioButtonList was selected, how do I do this?
I've tried with AutoPostBack but I didn't like how it worked (running the page again), are there any other solutions?
Some of the places I searched for an answer recommended using the AutoPostBack property, but I personally didn't like it and so I had to find another way for it to work and so I decided to use JavaScript/JQuery...
This is an HTML sample code of an example of a RadioButtonList and a panel that opens when a chosen option on it is clicked (the value "Required" causes it to open and "Not Required" to close in this case):
<div>
<p class="space">3.2. ACCOMMODATION (*)</p>
<asp:RadioButtonList ID="accomodation" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow" Width="500px">
<asp:ListItem Text="Not Required" Value="Not Required"></asp:ListItem>
<asp:ListItem Text="Required" Value="Required"></asp:ListItem>
</asp:RadioButtonList>
<asp:Panel ID="PanelAccommodation" runat="server">
<p>
Number of nights (*):
<asp:RequiredFieldValidator ID="RequiredFieldValidator12" runat="server" ControlToValidate="numberOfNights" ForeColor="red" ErrorMessage="<- Required"></asp:RequiredFieldValidator>
</p>
<asp:TextBox ID="numberOfNights" runat="server" Width="50px"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" TargetControlID="numberOfNights"
FilterType="Numbers" runat="server">
</ajaxToolkit:FilteredTextBoxExtender>
<p>Preferred Hotel:</p>
<asp:TextBox ID="preferredHotel" runat="server" Width="450px"></asp:TextBox>
<p>Preferred Hotel URL:</p>
<asp:TextBox ID="preferredHotelURL" runat="server" Width="450px"></asp:TextBox>
</asp:Panel>
</div>
The Script I used:
$(document).ready(function () {
$("#MainContent_PanelAccommodation").hide("fast");
$('#<%= accomodation.ClientID%>').find('input:radio').click(function () {
var selVal = $('#<%= accomodation.ClientID %>').find('input:checked').val();
if (selVal == "Required") {
$("#MainContent_PanelAccommodation").show("fast");
}
if (selVal == "Not Required") {
$("#MainContent_PanelAccommodation").hide("fast");
}
})
});
In this Script I use the first
$("#MainContent_PanelAccommodation").hide("fast");
to make sure that when the page runs the panel is hidden and will only open when/if "Required" is selected...
Another thing you may struggle with is what ID to put in the function since as you can see the panel ID is "PanelAccommodation", but the ID I use in the function is "MainContent_PanelAccommodation" since that's how it's recognized on your browser (to check this just select the panel's position and inspect element) you'll notice that the ID becomes "MainContent_PanelAccommodation" because it inherits from your asp:Content ContentHolderID...
Hope this helps ;) any questions just ask...
I have an ASP.NET 4.5 web form with inputs for a physical and mailing address. After entering a physical address, a user can tick a checkbox to fill in the mailing address if the information is the same.
This occurs via an OnClick function tied to the checkbox, which basically does this (I left out additional code):
document.getElementById("<%= txtMailAddressStreetNumber.ClientID%>").value = document.getElementById("<%= txtPermAddressStreetNumber.ClientID%>").value;
Each of the address textboxes has a RequiredFieldValidator. When I submit the form, it passes client-side validation and posts back to the server. There it fails (Page.IsValid is false). The textboxes that were populated by the OnClick function fail server-side validation unless I manually populate them.
I've tried calling Page_ClientValidate('FormGroup'); (FormGroup is the name of the validation group) after assigning values, and doing this doesn't trigger any validation error messages for the textboxes. However, when I submit the form (postback), the values inserted via Javascript are all cleared and I have to manually enter them.
Code in the .aspx page:
<asp:Label CssClass="mainlabel" ID="lblPermAddressZipCode" runat="server" Text="Zip Code" AssociatedControlID="txtPermAddressZipCode" />
<asp:RequiredFieldValidator ControlToValidate="txtPermAddressZipCode" ID="RequiredFieldValidator10" runat="server" ErrorMessage="*" Display="Dynamic" ValidationGroup="FormGroup" CssClass="formerror" />
<asp:TextBox ID="txtPermAddressZipCode" Width="100" onclick="openDialog(1)" ReadOnly="true" CssClass="readOnlyTextBox" runat="server" />
<asp:CheckBox ID="cbPermIsMailAddress" onclick="UsePermanentAsMailingAddress()" runat="server" /><small>(same as above)</small>
<asp:Label CssClass="mainlabel" ID="lblMailAddressZipCode" runat="server" Text="Zip code" AssociatedControlID="txtMailAddressZipCode" />
<asp:RequiredFieldValidator ControlToValidate="txtMailAddressZipCode" ID="RequiredFieldValidator15" runat="server" ErrorMessage="*" Display="Dynamic" ValidationGroup="FormGroup" CssClass="formerror" />
<asp:TextBox ID="txtMailAddressZipCode" ReadOnly="true" onclick="openDialog(2)" CssClass="readOnlyTextBox" Width="100" runat="server" />
Javascript:
function UsePermanentAsMailingAddress() {
//only copy if the address is complete
if (document.getElementById("<%= permCityStateZipId.ClientID %>").value != '') {
//exit if the box was unchecked
if (!$("#<%= cbPermIsMailAddress.ClientID%>").is(':checked')) {
return;
}
document.getElementById("<%= txtMailAddressZipCode.ClientID%>").value = document.getElementById("<%= txtPermAddressZipCode.ClientID%>").value;
//the ID value is the answer
document.getElementById("<%= mailCityStateZipId.ClientID%>").value = document.getElementById("<%= permCityStateZipId.ClientID %>").value;
//Page_ClientValidate('FormGroup');
}
else {
$("#<%= cbPermIsMailAddress.ClientID%>").removeAttr('checked');
alert("Please enter a complete permanent address first.");
}
}
Since the ReadOnly property is set in the .aspx, any changes made to it client-side will be ignored when it's posted back. If you absolutely need to have the textboxes read-only, then remove the property from your .aspx and set it with JavaScript on page load:
$(document).ready(function () {
$('#<%= txtMailAddressZipCode.ClientID%>').prop('readonly', true);
});
This way the user won't be able to directly change the textbox (I assume you have some other way of filling the textbox), but any changes will be posted back rather than the original (empty) values.