Unable to call External jquery file - javascript

I am unable to call the external jquery file. The code that is in the same aspx page is working but the external js is not working. Please help -
My aspx Page code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="loginvalidation.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js" type="text/javascript"></script>
<script src="http://jquery.bassistance.de/validate/additional-methods.js" type="text/javascript"></script>
<script src="JScript1.js" type="text/javascript"></script>
</head>
<body">
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Username:</td>
<td><asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Password:</td>
<td><asp:TextBox ID="txtPassword" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
My external jquery code:
$(document).ready(function() {
$("#form1").validate({
rules: {
<%=txtUserName.ClientID %>: {
required: true,
email: true
},
<%=txtPassword.ClientID %>: {
required: true,
digits:true,
minlength:10,
maxlength:10
}
},
messages: {
<%=txtUserName.ClientID %>:{
required: "* Required Field *"
},
<%=txtPassword.ClientID %>:{
required:"* Required Field *"
}
}
});
});

You have to replace <%=txtUserName.ClientID %> and <%=txtPassword.ClientID %> with generated client IDs when you move the script to external js file.
Thanks !

Server Side code like <%=txtUserName.ClientID %> will not be work in JS file. They will not be parsed and will be rendered as simple text.
You can use the rules add function.
In ASPX Page, Add a CSS class (Here I have added username)
<asp:TextBox ID="txtUserName" runat="server" CssClass="username"></asp:TextBox>
In Your External File
jQuery(function() {
jQuery('form').validate();
// Use custom class added to input and add rules like this
jQuery('.username').rules('add', {
required: true,
email: true,
messages: {
required: "* Required Field *"
}
});
});

Add the script complete path like
<script src="~/foldername/foldername/JScript1.js"></script>
you just need to pick the file and drop to the page in visual studio.
And also as comment suggested <%=txtUserName.ClientID %> these are asp.net code that would not work in javascript external file.
In place of it please follow any of the solution
Solution 1
Either use StaticId on controls or page by setting ClientIdMode = "Static". you can find more details on link
like
<asp:TextBox id="txtUserName" runat="server" ClientIdMode ="static" />
After setting it you can aceess your controls like
$('#txtUserName')
Solution 2
Look into your html page that is rendered by Asp.net engine. Asp.net engine convert the controls id depends on Master page used and append it on the control id. Now rendered controlId should be look like 'ct100_txtUserName' and you can get your control like
$('#ct100_txtUserName')
Solution 3
Add classes on controls like
<asp:TextBox id="someId" CssClass="someClass" runat="server" />
and get the control like
$('.someClass')
But the last one is slow compare to other

Related

Uncaught TypeError: Cannot set property 'type' of null

I'm using the master page in asp.net and receiving the following error in the chrome browser inspection tool console.
Uncaught TypeError: Cannot set property 'type' of null
at myFunction (StudentPassword.aspx:258)
at HTMLInputElement.onclick
I guess that the problem is with the script tag. where should I place it? Inside tag or at the bottom of content page or at the bottom of the master page?
Masterpage is:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Student.master.cs" Inherits="Project_Placements.Student" %>
<!DOCTYPE HTML>
<HTML>
<head runat="server">
</head>
<body>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<script type="text/javascript">
function myFunction() {
var checkBox = document.getElementById("myCheck");
var pwd = document.getElementById("password");
if (checkBox.checked == true) {
pwd.type = 'password';
} else {
pwd.type = 'text';
}
}
}
</script>
</body>
</html>
and the content page code is as follows:
<%# Page Title="" Language="C#" MasterPageFile="~/Student.Master" AutoEventWireup="true"
CodeBehind="StudentPassword.aspx.cs" Inherits="Project_Placements.WebForm7" %>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<form id="form1" runat="server">
<asp:TextBox ID="password" runat="server" TextMode="Password" ></asp:TextBox>
<label for="myCheck">Show Password :</label>
<input type="checkbox" id="myCheck" onclick="myFunction()">
</form>
</asp:Content>
ASP.Net chains up all id from serverside ran parent elements to the id of the current element, unless overwritten on the server. So the outputted id actually looks something like ContentPlaceHolder1$Content3$form1$password.
You can use the ends-with selector to omit this.
var pwd = document.querySelector("[id$=password]").
Yet be aware to still choose unique id which will also be unique using ends-with.
Alternatively you could use a data-attribute and select on that:
<asp:TextBox ID="password" runat="server" TextMode="Password" data-id="password" />
var pwd = document.querySelector("[data-id=password]");
Finally you could use something like:
var pwd = document.getElementById('<%=password.ClientID %>');
Yet I never really liked it and it demands the script to be inline.
You are getting the error because the script is getting loaded before the DOM is being rendered completely. Try placing the content of your script inside document.ready and that should solve the problem.

How to move cursor at first character positon using jquery mask plugin?

I have searched a lot and found out same kind of question but not exactly same and didn't find satisfactory answer. So thought, Should ask that more specific.
Using Jquery mask plugin, I would like my cursor at the beginning always no matter which positon I click. If I click into that textbox, cursor should be at the beginning. with my below code. wherever I click into the textbox, cursor gets that particular positon. How to avoid that?
<asp:TextBox ID="tbMobile" CssClass="ContactNumber" runat="server" onfocus="GetPhoneMask();" MaxLength="15" placeholder="555-555-5555" ValidationGroup="Application"></asp:TextBox>
function GetPhoneMask() {
$(".ContactNumber").mask("999-999-9999", { autoclear: false });
}
Updated:
Live link https://dotnetfiddle.net/Gipb8h
I changed the phone class name.
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebFormsPW._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.js"></script>
<script type="text/javascript">
$(function () {
$('.phone_us').mask('(000) 000-0000');
})
//took out
//function GetPhoneMask() {
// $(".ContactNumber").mask("999-999-9999", { autoclear: false });
//}
</script>
<%-- took out onfocus="GetPhoneMask();"--%>
<asp:TextBox ID="tbMobile" CssClass="phone_us" runat="server" MaxLength="15" placeholder="555-555-5555" ValidationGroup="Application"></asp:TextBox>
</asp:Content>

jquery click function does not work

I have a asp.net web application written in VS 2013. The application has nested master pages and main master page has following codes:
<!DOCTYPE html>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
My web form consists of following codes also:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#textbox1').click(function () {
alert('Hello');
});
});
</script>
<div class="form-group">
<label class="control-label">Name</label>
<input type="text" id="textbox1" class="form-control" placeholder="Name" maxlength="50" runat="server">
</div>
And when I build the project and run on browser (either ie or chrome), I click on "textbox1" and browser does nothing.
Appreciate for help.
You should replace this:
$('#textbox1')
with this:
$('#<%=textbox1.ClientID%>')
Your textbox is a server side control. So you have to read the ClientID, in order to read the ID for HTML markup that is generated by ASP.NET. For further info please have a look here. Generally as it is stated in the previous link:
When a Web server control is rendered as an HTML element, the id
attribute of the HTML element is set to the value of the ClientID
property
Furthermore, you have to remove the closing script tag, </script>, just before the opening script tag, <script> of your script.
You have an extra </script> tag immediately after your asp tag.
Try the same code without it:
<script src="https://code.jquery.com/jquery-latest.min.js"type="text/javascript"></script>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#textbox1').click(function () {
alert('Hello');
});
});
</script>
<div class="form-group">
<label class="control-label">Name</label>
<input type="text" id="textbox1" class="form-control" placeholder="Name" maxlength="50" runat="server">
</div>
Works for me here: https://jsfiddle.net/mutjg5sq/
Try this, Hope it help you
Script:
<script src="https://code.jquery.com/jquery-latest.min.js"type="text/javascript"></script>
Html:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server>
Jquery:
<script>
$('#textbox1').click(function () {
alert('Hello');
});
</script>

Refresh user control inside an update panel from javascript

I am working on a project where I want to refresh a part of the web page where i have a user control that contain dynamic data.user control will load data from a text file as this text file will update frequently. I need to refresh the user control alone not the whole page using javascript. I tried the following but it did not worked for me.
<%# Page Language="C#" %>
<%# Register src="ucTest.ascx" tagname="ucTest" tagprefix="uc1" %>
<script runat="server">
void button_Click(object sender, EventArgs e)
{
lbltest.Text = "Refreshed by server side event handler at " + DateTime.Now + ".<br>";
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>How to update an UpdatePanel with JavaScript</title>
<script type="text/javascript">
function UpdPanelUpdate()
{
__doPostBack("<%= button.ClientID %>","");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
Update the Panel
<asp:Button ID="button" runat="server" OnClick="button_Click" style="display:none;"/>
<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
<ContentTemplate>
<uc1:ucTest ID="ucTest1" runat="server" />
<asp:Label ID="lbltest" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="button" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
my user control is.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ucTest.ascx.cs" Inherits="ucTest" %>
<table border="3">
<tr>
<td>
<% Response.WriteFile("TextFile.txt"); %>
</td>
</tr>
</table>
Here TextFile.txthas some information that will be changed frequently.
any help would be greatly appreciated.
To make things simpler, you can put the hidden button within the UpdatePanel so that you don't have to put async triggers. First keep the button visible and see if the update panel is refreshing or not. If yes then you can hide the button.
Next part is triggering the button by simulating click event. I will suggest you to use library such as jquery from cross-browser solution. For example,
function UpdPanelUpdate()
{
$("<%= button.ClientID %>").click();
}
For code __doPostBack("<%= button.ClientID %>",""); to work, you should try setting button's UseSubmitBehavior property as false.

jQuery function before the Postback for FileUpload in ASP.NET

So, I have an .aspx webpage as follows:
..
<form id="frm" runat="server">
<asp:FileUpload runat="server" id="fileupload" onchange="browsed()" />
<asp:Button runat="server" OnClick="Upload_Click" id="uploadbutton" class="uploadbutton" Text="start upload" Enabled="false" />
<div id="nfo" style="display: none">
blabla
</div>
</form>
..
Now, as you can guess correctly, user chooses file to upload, clicks #uploadbutton and, voila, Upload_Click is called after the postback.
Then, I want to show div #nfo with some jQuery effects during the upload. To do this, I write:
$(function() {
$('.uploadbutton').click(function() {
$('#nfo').slideDown().show("fast");
})
})
and everything works just fine, until the user starts browsing in IE...
First of all, in IE, user has to click #uploadbutton twice - first time to display #nfo, second time, for some reason, to initiate postback.
Secondly, after the postback, Upload_Click's this.fileupload.HasFile shows false.
FF and Chrome works quite well though.
As far, as I can understand this - in IE jQuery's function prevents something important for asp:FileUpload from happening and stops the postback. Though, on the second click it does initiate the postback, but still with no info for asp:FileUpload's Upload_Click.
Any help?
Update:
followed #joelt'd advice. turned out, there was some different problem, never thought it could be of importance, so I didn't provide source code for that part =(
see localizing <asp:FileUpload>. IE problem
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#Button1").click(function() {
$("#progress").show();
});
});
</script>
</head>
<body>
<form runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<div id="progress" style="display:none; background-color:Red;">test</div>
</form>
</body>
</html>
This works fine for me in FF and IE7, except in IE, the progress indicator doesn't really give you anything because of how it's rendering, I suppose. I would say the biggest difference between our code is the "onchange=browsed()" function. It's possible that's not getting called until you click the button? In any case, I would start with a stripped down page like this, and start adding in other elements you have until it breaks.
try this:
<asp:Button runat="server" OnClick="Upload_Click" id="uploadbutton"
class="uploadbutton" Text="start upload" Enabled="false"
OnClientClick="return myFunction();"/>
<script type="text/javascript">
function myFunction(){
$('#nfo').slideDown().show("fast");
return true;//THIS WILL FIRE POSTBACK EVENT
//return false;//THIS WILL STOP POSTBACK EVENT, WHICH YOU MAY WANT IF THERE
//IS NO FILE SELECTED
}
</script>

Categories

Resources