Adding date/time using JavaScript to my asp.net user control - javascript

I have a user control where I was getting the server time and doing using a AJAX timer to update it every second. This was very slow and I've been told it is better to do it on the client side.
So I came up with this...but it isn't working. Any suggestions?
<%# Control Language="VB" AutoEventWireup="false" CodeFile="DateTime.ascx.vb" Inherits="UserControls_WebUserControl" %>
<script type="text/javascript">
window.onload = function () {
getDate();
};
function getDate() {
var dt = new Date();
var element = document.getElementById("client_time");
element.text = dt.toDateString();
}
</script>
<form name="headerForm">
<asp:Table Width="100%" ID="formatTable" runat="server">
<asp:TableRow>
<asp:TableCell ColumnSpan="2">
<asp:Image ImageUrl="~/Logo.jpg" ID="Image1" runat="server" />
</asp:TableCell>
<asp:TableCell>
<input type="text" size="10" maxlength="10" value="" name="client_time" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</form>

You have filled out the name field of the element, but it lacks the id needed to find it via getElementById. Also, .text won't do anything, you need to set its value attribute.
Since your input has a limit of 10 characters you might try removing that to show the full date string or you could instead simply write to the table cell with innerHTML or some such method.
To get time in a human readable format you can take a look at: http://www.quackit.com/javascript/tutorial/javascript_date_and_time.cfm

Related

html textbox funtion onkey_Up is not working on ascx control

i tried onkey_up to copy one textbos data to another textbox on an user control ascx file but when i run its not wroking.is it because of i wrote onkey_up function on .ascx , i should write on master page?
function sync() {
var TextBoxA1 = document.getElementById('TestAmountTextBox');
var TextBoxA2 = document.getElementById('TestAmountTextBox_2');
TextBoxA2.value = TextBoxA1.value;
}
html inpoutbox :
<input type="text" runat="server" id="TestAmountTextBox" class="form-control currency-input" placeholder="From " aria-label="From Transaction Amount" data-allownegative="true" style="width: 100px;" maxlength="14" tabindex="7" onkeyup="sync()"/>
<input type="text" runat="server" id="TestAmountTextBox_2" class="form-control currency-input" placeholder="To " aria-label="To Transaction Amount" data-allownegative="true" style="width: 100px;" maxlength="14" tabindex="13" />
By default, adding a textbox to a usercontrol will force ASP.NET to render a unique ID. Something like "usercontrolId_textboxId". You can find the actual ID, by viewing HTML source.
There are a few options to get around ASP.NET generated IDs:
Option 1:
You can turn off ASP.NET autogenerated IDs, by setting ClientIDMode="Static" E.g:
<input type="text"
runat="server"
id="TestAmountTextBox"
ClientIDMode="Static"
... [the rest of the attributes]
There are alternative properties in ClientIDMode that can be used. Also it can be turned off completely in web.config.
If ClientIDMode is set to Static, then ASP.NET will throw an error if the same ID is reused. For example using the usercontrol on more than once on the same page.
Option 2:
Bind the ASP.NET ID to the JavaScript code, using ClientID, For example:
function sync() {
var TextBoxA1 = document.getElementById('<%= TestAmountTextBox.ClientID %>');
var TextBoxA2 = document.getElementById('<%= TestAmountTextBox_2.ClientID %>');
TextBoxA2.value = TextBoxA1.value;
}
This will only work if the JavaScript is placed on the usercontrol.
Option 3:
A third option is to replace getElementById with getElementsByClassName and add another class to the textboxes.

Get selected value of radio button in Asp.net through javascript

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

How do I can get asp:Panel to work properly with asp:RadioButtonList without AutoPostBack?

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...

How to disable image button onlclick in asp.net?

I have a GridView in this GridView there is a column which I use to select date with the use of asp:CalendarExtender. I have multiple rows in GridView which are dynamically generated.
When I click the image button calender pops up and I choose my date.
In some rows I want the User to select date when he clicks image button of that row. sometime I don't want to allow him to select date.
When he tries to change the date or click on the image button, he should get alert message saying that you are not allowed to change the date.
I want to handle it from client side. So please suggest me how to do this.
this is the aspx code.
<asp:TextBox runat="server" ID="StartDateTime" CssClass="search_area_text_vm_small" onclick = "javascript:DateClick(this.id);"></asp:TextBox>
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/image3.jpg" />
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="StartDateTime" PopupButtonID="Image1" Format="yyyy-MM-dd" ></asp:CalendarExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="StartDateTime"
ErrorMessage="*" SetFocusOnError="True"></asp:RequiredFieldValidator>
You can make use of the OnClientDateSelectionChanged event of the CalendarExtender.
Use below code:
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="StartDateTime" PopupButtonID="Image1" Format="yyyy-MM-dd" OnClientDateSelectionChanged="checkIfDateSelected()" >
</asp:CalendarExtender>
<javascript>
function checkIfDateSelected(){
var dateTextBox=document.getElementByid('StartDateTime');
if(dateTextBox!='')
{
alert ('Date once selected cannot be changed');
return false;
}
</javascript>
This will show the info pop up and prevent the form submission if the date has been selected already.

javascript not accessing asp .net based html page element

I'm just trying to access the value of a textbox control (which has the runat="server" attribute). Been stuck for hours looking for an answer. Every time I try to get the value, it is null.
The javascript file:
function validateRegistration() {
var username = document.getElementById("<%=username.ClientId%>").value;
document.write(username);
}
The aspx file:
<asp:Content ID="Content3" ContentPlaceHolderID="mainContentPlaceHolder" runat="server">
<p>
Fill in the following form to register:</p>
<p>
Username:
<asp:TextBox ID="username" name="username" runat="server"></asp:TextBox></p>
<input id="register" type="submit" value="Register" onclick="validateRegistration()"/>
</asp:Content>
Did you try using
var username = document.getElementById('<%= username.ClientID%>').value;?
i have similar code in my page and works fine.
It should be (note the capital D):
var username = document.getElementById("<%=username.ClientID%>").value;
document.write(username);

Categories