I'm having problems with integrating JavaScript to ASP.NET. I want to use jQuery or even Vanilla JavaScript to do some client side operations but I'm unable to access HTML and ASP.NET Server Controls. I have tried many solution, just like using <%= element.ClientID %> but none worked for me. I'm unable to identify my fault, please help me identifiying.
Alread Tried:
RegisterClientScriptBlock
Include JavaScript File Directly
$("#<% element.ClientID %>")
document.getElementById("<%= element.ClientID %>");
Using HTML control instead Server & vice versa.
new_quiz.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/teacher_quizes/teacher_quizes.master" AutoEventWireup="true" CodeBehind="new_quiz.aspx.cs" Inherits="onlineQuiz_bsef17m35.teacher_quizes.new_quiz" %>
<asp:Content ID="Content1" ContentPlaceHolderID="quizes" runat="server">
<div class="form p-2">
<div class="form-group p-1">
<asp:Label runat="server" Text="Quiz Title"></asp:Label><br />
<small class="text-danger">The title of your quiz</small>
<input runat="server" type="text" maxlength="64" id="title"
class="form-control"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="title"
ErrorMessage="Title is required"></asp:RequiredFieldValidator>
</div>
<div class="form-group p-1">
<asp:Label runat="server" Text="Quiz Description"></asp:Label><br />
<small class="text-danger">Please describe this quiz</small>
<textarea runat="server" id="description" class="form-control" rows="2"
maxlength="128">
</textarea>
<asp:RequiredFieldValidator runat="server" ControlToValidate="description"
ErrorMessage="Description is required" CssClass="text-warning text-muted">
</asp:RequiredFieldValidator>
</div>
<div class="form-group p-1">
<asp:Label runat="server" Text="Maximum Marks"></asp:Label><br />
<small class="text-danger">The maximum achiveable marks for this quiz, between 1 and 1000</small>
<input runat="server" type="number" min="1" max="100" id="maxMarks"
class="form-control"/>
<asp:RangeValidator MinimumValue="1" MaximumValue="1000"
runat="server" ControlToValidate="maxMarks" CssClass="text-warning"
ErrorMessage="Please choose a number between 1 and 100">
</asp:RangeValidator>
</div>
<div class="form-group p-1">
<asp:Label runat="server" Text="Passing Marks"></asp:Label><br />
<small class="text-danger">The passing marks for this quiz, between 1 and 1000 and lesser than or equal to total marks</small>
<input runat="server" type="number" min="1" max="100" id="passingMarks"
class="form-control"/>
<asp:RangeValidator MinimumValue="1" MaximumValue="1000"
runat="server" ControlToValidate="passingMarks" CssClass="text-warning"
ErrorMessage="Please choose a number between 1 and 100">
</asp:RangeValidator>
</div>
<div class="form-group p-1 card mb-2">
<div><b runat="server" id="questions">Quesions</b></div>
<div class="form-group">
<asp:Label runat="server" Text="Question"></asp:Label><br />
<asp:TextBox runat="server" ID="question" CssClass="form-control"/>
<asp:Label runat="server" Text="Type of Question"></asp:Label><br />
<select runat="server" id="questionType" class="form-control"
onchange="questionTypeChange()"></select>
<div runat="server" id="questionOptions">
<small>Please check checkbox in front of Options to denote an option as true</small>
<div class="form-group">
<asp:Label runat="server" Text="Option 1"></asp:Label><br />
<input runat="server" type="text" maxlength="64" id="questionOption1"
class="form-control" />
<input runat="server" type="checkbox" id="questionOption1Validity"
class="input-group-append"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="questionOption1"
ErrorMessage="Option 1 is required!" CssClass="text-danger">
</asp:RequiredFieldValidator>
</div>
<div class="form-group">
<asp:Label runat="server" Text="Option 1"></asp:Label><br />
<input runat="server" type="text" maxlength="64" id="questionOption2"
class="form-control" />
<input runat="server" type="checkbox" id="questionOption2Validity"
class="input-group-append"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="questionOption2"
ErrorMessage="Option 2 is required!" CssClass="text-danger">
</asp:RequiredFieldValidator>
</div>
<div class="d-flex flex-row-reverse">
<button class="btn btn-sm btn-primary">Add another Option</button>
</div>
</div>
</div>
</div>
</div>
</asp:Content>
new_quiz.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace onlineQuiz_bsef17m35.teacher_quizes
{
public partial class new_quiz : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
return;
}
DatabaseEntities db = new DatabaseEntities();
var quizes = db.getQuestionTypes().ToArray();
questionType.DataSource = quizes;
questionType.DataBind();
if (questionType.Value == "Multiple Choice")
{
questionOptions.Visible = true;
} else
{
questionOptions.Visible = false;
}
/* register client scripts */
Type scriptType = this.GetType();
String scriptName = "script";
String scriptUrl = "./new_quiz.js";
String scriptText = File.ReadAllText(Server.MapPath(scriptUrl));
ClientScriptManager scriptManager = Page.ClientScript;
if (!scriptManager.IsClientScriptBlockRegistered(scriptType, scriptName))
{
scriptManager.RegisterClientScriptBlock(scriptType, scriptName, scriptText, true);
}
}
}
}
new_quiz.js
function questionTypeChange() {
const element = document.getElementById("<%= question.ClientID %>");
console.log(element);
}
First check if your jQuery is loaded correctly.
Open console (press F12) and type "jQuery" and enter - you should get something back. If you get "not defined" - then make sure you do load it.
Then, you should be able to access your HTML, via jQuery selector.
More info here: https://www.w3schools.com/jquery
Real problem was that I was using external script. ASP.NET Tag in external script does not work. For that I used jQuery pattern matching to find controls.
To find button with ID="saveButton", I used $("[id$=saveButton]") that results in all Controls having an ID ending with saveButton.
Above works, because ASP.NET appends original ID to some random ID generated while compilation, so final html id always ends with original id given in markup.
Related
I am working on Asp.net form as follows
<form runat="server" id="form">
<label>Select Category <span>*</span></label>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Mobiles</asp:ListItem>
<asp:ListItem>Electronics and Appliances</asp:ListItem>
<asp:ListItem>Cars</asp:ListItem>
<asp:ListItem>Bikes</asp:ListItem>
<asp:ListItem>Furniture</asp:ListItem>
<asp:ListItem>General</asp:ListItem>
</asp:DropDownList>
<div class="clearfix"></div>
<label>Ad Title <span>*</span></label>
<asp:TextBox ID="txt_title" class="phone" runat="server"></asp:TextBox>
<div class="clearfix"></div>
<label>Ad Description <span>*</span></label>
<%--<textarea class="mess" placeholder="Write few lines about your product"></textarea>--%>
<asp:TextBox ID="txt_Body" class="mess" placeholder="Write few lines about your product" TextMode="multiline" Style="resize: none" Width="770px" Height="150px" Wrap="true" runat="server" Font-Bold="True"></asp:TextBox>
<div class="clearfix"></div>
<div class="upload-ad-photos">
<label>Photos for your ad :</label>
<div class="photos-upload-view">
<asp:ImageButton ID="ImageButton1" UseSubmitBehavior="false" OnClientClick="return chooseFile();" ImageUrl="Images/Capture.JPG" runat="server" />
<asp:FileUpload ID="FileUploadControl" runat="server" Visible="False" />
<div id="messages">
<p>Status Messages</p>
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="personal-details">
<label>Your Name <span>*</span></label>
<asp:TextBox ID="txt_name" class="name" runat="server"></asp:TextBox>
<div class="clearfix"></div>
<label>Your Mobile No <span>*</span></label>
<asp:TextBox ID="txt_phn" class="phone" runat="server"></asp:TextBox>
<div class="clearfix"></div>
<label>Your Email Address<span>*</span></label>
<asp:TextBox ID="txt_email" class="email" runat="server"></asp:TextBox>
<div class="clearfix"></div>
<p class="post-terms">By clicking <strong>post Button</strong> you accept our Terms of Use and Privacy Policy</p>
<asp:TextBox ID="post_sub" Text="Post" type="submit" runat="server"></asp:TextBox>
<div class="clearfix"></div>
</form>
Where I want to call a hidden fileupload when Imagebutton is clicked using JavaScript as follows:
<script type="text/javascript">
function chooseFile() {
document.getElementById("#FileUploadControl").click();
alert("grt");
return false;
}
</script>
But, I was not able to call the function instead page reloads, as you can see I am returning false in the function also. Please guide me to make this work.
You have set the Visible property of the FileUpload Control to false. Therefore it does not exist on the client side. The Visible property is not the same as display:none in HTML/CSS.
You should do something like this:
<span style="display: none">
<asp:FileUpload ID="FileUploadControl" runat="server" />
</span>
And it's always better to use the ClientID instead of hard coding the ID of the FileUpload Control.
<script type="text/javascript">
function chooseFile() {
document.getElementById("<%= FileUploadControl.ClientID %>").click();
return false;
}
</script>
When you use document.getElementById you shouldn't mention # since it already searches for id attribute, in your current state it will look for id #FileUploadControl which is not your element id. change your code to this:
function chooseFile() {
document.getElementById("FileUploadControl").click();
alert("grt");
return false;
}
<form runat="server" id="form">
<div class="photos-upload-view">
<img id="ImageButton1" OnClick="return chooseFile();" src="https://maxcdn.icons8.com/office/PNG/512/Computer_Hardware/mouse_left_click-512.png" style="widdth:40px;height:40px;" />
<input type="file" ID="FileUploadControl" runat="server" style="display:none;" />
</div>
</form>
Yes, number one is you using # of you document.getElementById("#FileUploadControl") it's wrong and you should use it without # document.getElementById("FileUploadControl").
second thing if you use Visible="False" attribute it not rendering the HTML element, without that you can use below two methods.
FileUploadControl.Style["visibility"] = "hidden" in your backend file
using following css class for hide
function chooseFile() {
document.getElementById("FileUploadControl").click();
alert("grt");
return false;
}
.setDisplayNone {
display:none;
}
<asp:FileUpload ID="FileUploadControl" runat="server" CssClass="setDisplayNone" />
I try to ajaxify RadNumericTextBoxs in Edit Form of Rad grid using (RadAjaxManager or RadAjaxManagerProxy) but i failed .
all i want to do is :
when text changed of (txt_CashAndEquivalents,txt_ShortTermInvestments) sum the values of both text boxes and set the result in txt_OneTotal without full postback .
<EditFormSettings EditFormType="Template">
<EditColumn UniqueName="EditCommandColumn1" FilterControlAltText="Filter EditCommandColumn1 column">
</EditColumn>
<FormTemplate>
<div class="FinancePositioncontainers">
<div class="FinancePosition-container" id="decorationZone">
<h4>Finance</h4>
<fieldset>
<legend>List</legend>
<div class="formRow" style="padding-right: 10px; padding-left: 10px;">
<h5>Bal</h5>
<label for="txt_CashAndEquivalents">bal1:</label>
<telerik:RadNumericTextBox ID="txt_CashAndEquivalents" runat="server" Text='<%# Eval("CashAndEquivalents")%>' Type="Number" DataType="System.Decimal" Width="160" NumberFormat-GroupSizes="3" AutoPostBack="True" TabIndex="1" OnTextChanged="txt_CashAndEquivalents_TextChanged"></telerik:RadNumericTextBox>
<div>
</div>
<label for="txt_ShortTermInvestments">bal2:</label>
<telerik:RadNumericTextBox ID="txt_ShortTermInvestments" runat="server" Text='<%# Eval("ShortTermInvestments")%>' Type="Number" DataType="System.Decimal" Width="160" NumberFormat-GroupSizes="3" TabIndex="2" AutoPostBack="True" OnTextChanged="txt_CashAndEquivalents_TextChanged"></telerik:RadNumericTextBox>
<div>
</div>
<hr />
<label for="txt_OneTotal">total :</label>
<telerik:RadNumericTextBox ID="txt_OneTotal" runat="server" ReadOnly="true" Type="Number" DataType="System.Decimal" Width="160" NumberFormat-GroupSizes="3"></telerik:RadNumericTextBox>
<div>
</div>
</div>
<asp:LinkButton ID="btnUpdate" runat="server" CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>'
ValidationGroup="Main" CssClass="btn btn-primary btn-xs white_cr"><span class="glyphicon glyphicon-floppy-disk"></span> <%# (Container is GridEditFormInsertItem) ? "Uppdate" %>
</asp:LinkButton>
<asp:LinkButton ID="btnCancel" runat="server" CausesValidation="False" CommandName="Cancel"
CssClass="btn btn-primary btn-xs white_cr"><span class="glyphicon glyphicon-ban-circle"></span>Cancel</asp:LinkButton>
<br />
<br />
</div>
</div>
</FormTemplate>
</EditFormSettings>
One approach you can consider is to utilise the client event, OnValueChanged of RadNumbericTextBox control, instead of the server side event.
For example,
<telerik:RadNumericTextBox ID="txt_CashAndEquivalents" runat="server" Text='<%# Eval("CashAndEquivalents")%>' Type="Number" DataType="System.Decimal" Width="160" NumberFormat-GroupSizes="3" TabIndex="1">
<ClientEvents OnValueChanged="DoSum" />
</telerik:RadNumericTextBox>
<script type="text/javascript">
function DoSum(sender, eventArgs)
{
var txt_ShortTermInvestments = $find('<%=txt_ShortTermInvestments.ClientID %>');
var txt_OneTotal = $find('<%=txt_ShortTermInvestments.ClientID %>');
var val_CashAndEquivalents = sender.get_value();
var val_ShortTermInvestments = txt_ShortTermInvestments.get_value();
txt_OneTotal.set_value(val_CashAndEquivalents + val_ShortTermInvestments);
}
</script>
Above code is just demonstrating the idea and hasn't been tested. So give it a go and see if it works for you or not.
For more details on the available client side events, please refer to the following link.
http://docs.telerik.com/devtools/aspnet-ajax/controls/numerictextbox/client-side-programming/radnumerictextbox-client-object#radnumerictextbox-client-object
Is there a way to access specific textbox control inside custom ASP.NET control from another page by using javascript?
In other words:
I have custom control BankInformation:
<%# Register Src="~/Controls/Attachments/SingleAttachment.ascx" TagName="SingleAttachment" TagPrefix="ABS" %>
<div id="divIBAN" runat="server" class="control-group">
<asp:Label ID="lblIBAN" runat="server" CssClass="control-label" AssociatedControlID="txtIBAN" meta:resourcekey="lblIBAN"></asp:Label>
<div class="controls">
<asp:TextBox ID="txtIBAN" runat="server"></asp:TextBox>
</div>
</div>
<div id="divRoutingABANumber" runat="server" class="control-group">
<asp:Label runat="server" ID="lblRoutingABANumber" CssClass="control-label" AssociatedControlID="txtRoutingABANumber" meta:resourcekey="lblRoutingABANumber"></asp:Label>
<div class="controls">
<asp:TextBox ID="txtRoutingABANumber" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" CssClass="validator" ValidationGroup="vgDirectDebitApplication" ID="rfvRoutingABANumber" ControlToValidate="txtRoutingABANumber" SetFocusOnError="True" Display="Dynamic" Enabled="false" meta:resourcekey="rfvRoutingABANumber"></asp:RequiredFieldValidator>
</div>
</div>
I've made an instance of this custom control inside of another control:
<%# Register Src="~/Controls/BankInformation.ascx" TagName="BankInformation" TagPrefix="ABS" %>
<script type="text/javascript">
$(document).ready(function () {
var isAccountNumberEmpty = document.getElementById('<%=txtAccountNumber.ClientID%>').value; //This is not valid of course
function validateAndCloseDirectDebitDialog(validationGroup, dialogID){
if (isAccountNumberEmpty != "")
dialogID.modal('hide');
else {
}
}
</script>
<div id="bankInfoDialog" runat="server" class="modal hide fade" tabindex="-1" role="dialog">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" style="display: none">×</button>
<h1 id="bankInformationDialogHeader"><%=GetLocalResourceObject("BankInfoHeader") %></h1>
</div>
<div class="modal-body">
<ABS:BankInformation runat="server" ID="bankInformation" />
</div>
<div class="modal-footer">
<asp:Button runat="server" ID="btnUpdate" meta:resourcekey="btnUpdate" CausesValidation="False" />
<button id="btnCancel" runat="server" data-dismiss="modal" aria-hidden="true"><%=GetLocalResourceObject("Cancel")%></button>
</div>
</div>
What I am trying to do is to access text box with an ID of 'txtAccountNumber' inside BankInformation control, from control where it is instantiated and get it's value so I can do client side validation on btnUpdate click event. I know how to do everything except most important part: Is it possible to get value of txtAccountNumber outside it's control and how to do this in javaScript if it is possible?
Yes, it is possible. You can use ClientIDMode property (ASP.NET 4.0):
<asp:TextBox ID="txtAccountNumber" runat="server" ClientIDMode="Static"></asp:TextBox>
then access text box:
var accountNumber = document.getElementById('txtAccountNumber').value;
Another approach is to save txtAccountNumber.ClientID to global javascript variable, or better save it as property of global application object.
Please help me out i am new to asp.net, wanted to create one simple page with form validation.
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Form1").validate({
rules: {
UserName: "required"
},
messages: {
UserName: "Enter your firstname"
}
});
});
</script>
Login.aspx Page
Log In
<p>
Please enter your username and password.
<asp:HyperLink ID="RegisterHyperLink" runat="server" EnableViewState="false">Register</asp:HyperLink> if you don't have an account.
</p>
<asp:Login ID="LoginUser" runat="server" EnableViewState="false" RenderOuterTable="false">
<LayoutTemplate>
<span class="failureNotification">
<asp:Literal ID="FailureText" runat="server"></asp:Literal>
</span>
<div class="accountInfo">
<fieldset class="login">
<legend>Account Information</legend>
<p>
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label>
<asp:TextBox ID="UserName" runat="server" CausesValidation="True" ClientIDMode="Static" ></asp:TextBox>
</p>
<p>
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
</p>
<p>
<asp:CheckBox ID="RememberMe" runat="server"/>
<asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="RememberMe" CssClass="inline">Keep me logged in</asp:Label>
</p>
</fieldset>
<p class="submitButton">
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In"/>
</p>
</div>
</LayoutTemplate>
</asp:Login>
Above shown is partial code i have written on my master page.
No error displayed, but unfortunately script is not working.
Didn't knew that script should be as per the asp:login control.
"<%= ((TextBox)LoginUser.FindControl("UserName")).UniqueID %>"
Sorry guys, before i missed my HTML code :(
I am trying to use a customvalidator to validate a DIV form and then close it if there is no validation errors. Below is my code, I can't get my custom validator to work, when I click submit, nothing validates, not sure what's wrong. Please advice. Thanks.
function validateRedemptionDialog(src, args) {
var rDate = document.getElementById('<%=uitxtRedemptionDate.ClientID%>').value;
if (rDate == "") {
args.IsValid = false;
return;
}
args.IsValid = true;
}
function closeRedemptionDialog() {
$('#dialog_Active_Redemption_confirm').dialog('close');
}
<div id="dialog_Active_Redemption_confirm" style="display: none">
<div class="section_body">
<div class="section_body_content">
<div class="row">
<asp:Label runat="server" ID="uilblRedemptionDate" Text="<%$ Resources:MembersNContactsManagerResources, uigrdhdrTransDate %>"
CssClass="label">
</asp:Label>
<asp:TextBox ID="uitxtRedemptionDate" runat="server" CssClass="text DatePicker" Style="width: 120px;
margin-right: 2px;">
</asp:TextBox>
<asp:CustomValidator ID="ctvtxtCamDateEnd" runat="server" ClientValidationFunction="validateRedemptionDialog"
ControlToValidate="uitxtRedemptionDate" ErrorMessage='<img src="../Images/icons/error.png" style="vertical-align:middle"/> XXX!'
Font-Names="arial" Font-Size="X-Small" SetFocusOnError="True" Display="Dynamic" />
</div>
<div class="row">
<asp:Label runat="server" ID="uilblRedemptionAmountSpent" Text="<%$ Resources:MembersNContactsManagerResources, uilblRedemptionAmountSpent %>"
CssClass="label">
</asp:Label>
<asp:TextBox ID="uitxtRedemptionAmountSpent" runat="server" Style="width: 120px;">
</asp:TextBox>
</div>
<div class="row">
<ul class="inline" style="margin-left: 137px; padding: 3px;">
<li><span class="button grey_btn">
<%--Submit button--%>
<asp:Button ID="uibtnRedemption" runat="server" Text="<%$ Resources : MembersNContactsManagerResources, uilblSubmit %>" OnClientClick="javascript:closeRedemptionDialog();"/>
<span> </span> </span></li>
</ul>
</div>
</div>
</div>
</div>
The validator will not validate empty text with your current configuration.
Set ValidateEmptyText to true if you need it to fire even when the user has entered nothing.
A CustomValidator does not need to have a ControlToValidate. If you need to validate in any case, you should leave that property empty.