Using Jquery in UserControl with MasterPage - javascript

I can't seem to get Javascript to work on my usercontrol. All I want to do is count the characters in a mulitline textbox (which adds another level of complexity). I want to count the characters and display them in a label.
I have my javascript in a .js file included in the MasterPage:
function textCounter(field, countfield, maxlimit) {
var output = document.getElementById(countfield);
if (output == null) { return; }
if (field.value.length > maxlimit)
field.value = field.value.substring(0, maxlimit);
else
output.value = maxlimit - field.value.length;
}
My UserControl has little code:
<script type="text/javascript" language="javascript">
if (typeof contentPageLoad == 'function') {
var outputField = $("[id$='lblCharacterCount']");
}
</script>
<asp:TextBox ID="txtMyTest" runat="server" Height="75px" CssClass="form-field full" TextMode="MultiLine" MaxLength="140"
onkeyup="textCounter(this, outputField, 140);" onkeydown="textCounter(this, outputField, 140);" ></asp:TextBox>
<asp:Label ID="lblCharacterCount" runat="server"></asp:Label>
outputField is always null when it tries to execute the function. I've tried adding it(the script on the UserControl) in a scriptblock in the UserControl PageLoad, PreRender and PreInit. Nothing seems to work.
UPDATE:
I was able to get UserControl Javascript working w/o an UpdatePanel. That was the problem, the UserControl was in an UpdatePanel. I've given up on using a Usercontrol in an updatepanel with JS unless someone can offer any advice.

Try changing the selector to something like this:
var outputField = $("#<% lblCharacterCount.ClientId %>");
The ID you set on the control is usually not the ID that gets assigned to it in the HTML that is generated. Using the ClientId property, will get you that HTML ID.
Of course I haven't used ASP.NET in a while so this answer might be worthless.

Related

How to pass data from (front-end) .aspx to (back-end) .aspx.cs using hidden filed

I want to pass data from back-end to front-end and front-end to back-end so far I have tried like below
back-end to front-end :-
back-end (.aspx.cs):-
public string amt;
protected void Page_Load(object sender, EventArgs e)
{
amt = "100";
}
front-end (.aspx):-
<body>
<form id="form1" runat="server">
<script type="text/javascript">
var amt = "<%=amt%>";
alert(amt); // data coming
</script>
</form>
</body>
The above example is working fine but while passing the value from front-end to back-end I'm getting the null("") value (for this concept I have read this article)
front-end to back-end :-
front-end (.aspx) :-
<body>
<form id="form1" runat="server">
<script type="text/javascript">
var amt = "<%=amt%>";
alert("amt :- " + amt);
function getval() {
var keyid = "1234";
document.getElementById('key_id').value = keyid;
alert(document.getElementById('key_id').value);
alert('hit');
window.location.href = "http://localhost:49855/ValuePassig.aspx";
}
//alert(amt);
</script>
<input id="key_id" runat="server" type="hidden" name="key_id_1" />
<input type="button" id="btn" value="click" runat="server" onclick="getval()" />
</form>
</body>
back-end(.aspx.cs) :-
public string amt;
protected void Page_Load(object sender, EventArgs e)
{
amt = "100";
//I'm getting the null("") value
//string kId = this.Request["key_id_1"];
//string kId = Request.Form["key_id_1"];
string kId = key_id.Value; //Initially the value come null(acceptable) and next I'm clicking on the "click" button at that time null value should not come(but coming)
Response.Write(kId);
}
I did my best so far to achieve this concept and I don't why I'm getting a null value because, I have followed the article also(above mentioned link) to achieve this
concept
Suggest me where I did the mistake to pass the value from front-end to back-end and how to achieve this
Please give me your best suggestions.
Note :- I have changed the code for better understanding that is button added and when I click on the button the hidden value should come back-end.
Ok, so we want to have some value - set in code behind cs, to set/pass/have some value for use in the client side js code.
And of course in the js code, we want use of that value, and ALSO to be able to change that value, and then upon actions, or code behind, we want that value passed back to the code behind.
First up, don't use a server side expression to "set" that value for use in the js code. The reason of course then you don't have a easy way to pass back and have use of that change value in the code behind.
You can freely change the var in js code, but you really don't have a easy/nice way to get that value back to the code behind (so that <%= %> expression is a one way street to the client side.
There are a LOT of ways to do this, but probably best is to drop in a hidden field control (as per your question title)..
You can also use a hidden text box, but might as well use the hidden field.
So, lets on page load (and ONLY first page load - like all setup on the page should be inside of the !IsPostBack code block - all web pages quite much need this !IsPostBack code block).
And bonus?
the Hidden field control has automatic view state. (that means the value will persist on page post-backs).
So, lets drop in a server side button to "show" the value.
And THEN lets drop in a button (client side) to show the value, and ALSO to modify the value.
<asp:HiddenField ID="MyHotelName" runat="server" ClientIDMode="Static" />
<h3>Server side code</h3>
<asp:Button ID="cmdShowServer" runat="server" OnClick="cmdShowServer_Click"
Text="Show Hotel Name" CssClass="btn" />
<br />
<asp:Label ID="lblShow" runat="server" Text="Label"></asp:Label>
<h3>Client side code</h3>
<asp:Button ID="cmdShowClient" runat="server" Text="Show Hotel Name"
OnClientClick="ShowHotel();return false" />
<br />
<asp:Button ID="cmdChangeClient" runat="server" Text="Change Hotel Name"
OnClientClick="ChangeHotel();return false" />
<script>
function ShowHotel() {
alert("Hotel name = " + $("#MyHotelName").val())
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
$("#MyHotelName").val(sHotelNew)
}
</script>
And our code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MyHotelName.Value = "Zoo";
}
}
protected void cmdShowServer_Click(object sender, EventArgs e)
{
lblShow.Text = "Value of hotel = " + MyHotelName.Value;
}
So, we now have this:
Edit: Above used jquery.
Of course the js code above used jQuery.
however, we could assume pure js code, no jQuery.
so, the js code would then become this:
<script>
function ShowHotel() {
sHotel = document.getElementById("MyHotelName").value
alert("Hotel name = " + sHotel)
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
document.getElementById("MyHotelName").value = sHotelNew
}
</script>
I should also point out the "very" imprortant adding of clientidmode="static" for the hidden field. This will "prevent" asp.net system from changing the "id" used for the control, and as a result, the js code tends to be more "clean" and "easy" to reference controls.
If you don't want to use clientidmode=static for the hidden field, then the above code then becomes this:
hidden field thus is this: (no client id mode).
<asp:HiddenField ID="MyHotelName" runat="server" />
And now our code becomes this:
<script>
function ShowHotel() {
sHotel = document.getElementById('<%= MyHotelName.ClientID %>').value
alert("Hotel name = " + sHotel)
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
document.getElementById('<%= MyHotelName.ClientID %>').value = sHotelNew
}
</script>
So, I often will toss in a ClientIDMode="static" for the hidden field, as that makes the js code to get the hidden control less messy.

Accessing value of hidden variable in Javascript wiht VB

I tried the following code but did not succeed.It would be great if you could guide me. I was trying to test using a simple "Hello". In the actual program I would assign a string value to the hidden field.
I get an Alert box ( using this to test whether the value is accessible in javascript ) but with no values.
Server Side
ivar.Value = "Hello"
Javascript
<script>
function getval() {
var v = document.getElementById('<%= ivar.ClientID%>').value;
alert(v)
}
</script>
Form
<asp:Button ID="Button1" runat="server" Text="CALCULATE" onclientclick="getval()" />
<asp:HiddenField ClientIDMode="static" id="ivar" runat="server" Value=""/>
Let us say you have a public variable on server side:
public string iVar = "Hello";
You can directly add it to your javascript as below:
<script>
function getval() {
var v = <%=iVar%>;
alert(v);
}
</script>
Hope this helps.
Your call to find the client id in your script block may be trying to find the hidden field before it exists. try moving the script to the bottom of the page just before you close your body tag and see if that helps.

Query String in Javascript in Sharepoint ASPX page

Im trying to redirect a user to a new page in which there username will be displayed within a text box. I am using ASP.NET Loginname and Buttons to do this. My issue is that im not 100% sure on how to get the value from the LoginName into the javascript which needs this. I have no way to get into the server code so this all has to be done by SharePoint designer
I know the common way is to do something like this
window.location="http://mysite/default.aspx?u="+ LoginName1
But this seems it doesn't want to work. Any answers?
JavaScript Code
function Redirect()
{
window.location="http://mysite/default.aspx";
}
ASP.NET Code
<asp:Button runat="server" Text="To Sysomos" id="Button1" OnClientClick="if (!Redirect()) { return false;};"></asp:Button>
<asp:LoginName runat="server" id="LoginName1" ></asp:LoginName>
try something like this
<script>
var usrName = "#HttpContext.Current.User.Identity.Name";
</script>
window.location="http://mysite/default.aspx?u='+ usrName + '";
Reference :
How to get the current login user name in my Script file inside my asp.net mvc
Assuming you are using SP2010, you can use Sharepoint's Client Object Model to get the current user details.
<script type="text/javascript">
(function () {
var spUser;
// Ensure SP objects have been loaded before executing our code
ExecuteOrDelayUntilScriptLoaded(getSpUser,"sp.js");
function getSpUser() {
var clientContext = new SP.ClientContext.get_current();
var spWeb = clientContext.get_web();
spUser = spWeb.get_currentUser();
clientContext.load(spUser);
clientContext.executeQueryAsync(getSpUserSuccess, getSpUserException);
}
function getSpUserSuccess(sender, args) {
var curUserId = spUser.get_loginName();
// redirectToSomeAspxPage();
}
function getSpUserException(sender, args) {
// Do any necessary error handling.
}
})();
</script>
Only issue with this is that the time to redirect may take (slightly) longer as the code needs to wait for sp.js to load before you can get the current user's details. Alternatively, you can redirect without the username on the query string, and simply retrieve the username from your ASPX page using the above code.
You can find the username and other things for the current user. To do it, start by adding this line at the top of your .aspx page: <%# Register Tagprefix="SPSWC" Namespace="Microsoft.SharePoint.Portal.WebControls" Assembly="Microsoft.SharePoint.Portal, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
(Version=14.0.0.0 for Sharepoint 2010 and Version=12.0.0.0 for Sharepoint 2007)
Now, just after the <form> tag add this line:
<form>
<SPSWC:ProfilePropertyLoader runat="server"/>
Finally add the below block before the </form> tag:
<div id="userDetails" style="display:none">
<asp:LoginName runat="server" id="userLogin">
<SPSWC:ProfilePropertyValue PropertyName="FirstName" ApplyFormatting="false" id="userFirstName" runat="server"/>
<SPSWC:ProfilePropertyValue PropertyName="LastName" ApplyFormatting="false" id="userLastName" runat="server"/>
<SPSWC:ProfilePropertyValue PropertyName="WorkEmail" ApplyFormatting="false" id="userWorkEmail" runat="server"/>
<SPSWC:ProfilePropertyValue PropertyName="PreferredName" ApplyFormatting="false" id="userPreferredName" runat="server"/>
</div>
So in your page you'll see a "userDetails" block with the current user login, firstname, lastname, work email and preferred name. With JavaScript you can get the username with :
document.getElementById('ctl00_userLogin').innerHTML

ASP.NET UpdatePanel and Javascript __dopostback

I'm calling a partial postback from javascript like so:
function GetPolicyClick()
{"__dopostback('UpdatePanel1', 'PostCall')";}
It does 1/2 of what I need it to. It does call a partial postback, just for my UpdatePanel.
Now the tricky part. I'm trying (somehow) to reference the second argument of __dopostback in my code behind. This does not work:
Private Sub UpdatePanel1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles UpdatePanel1.Load
Dim MyArg As String = Request("__EVENTARGUMENT")
End Sub
I just get an empty string.
Of course, what I'm trying to do might be completely wrong (as with everything else I try to do with ASP). I'm suspecting that my codebehind is grabbing the event argument from the page instead of the panel, but I really don't know, Any ideas?
If you want to put some value inside _EVENTARGUMENT you should do this with javascript before sending form by _doPostBack('UpdatePanel1','') because __EVENTTARGET is hidden field and in your html document it looks like this:
<input type="hidden" value="" id="__EVENTARGUMENT" name="__EVENTARGUMENT">
I recommend you to do something like this:
function setArgAndPostBack() {
var arg = document.getElementById('__EVENTARGUMENT');
var arg = document.getElementById("__EVENTARGUMENT");
arg.value = 'something you want to put to server';
__doPostBack('UpdatePanel1', '');
}
If you use jQuery it would be shorter:
function setArgAndPostBack() {
$("#__EVENTARGUMENT").val('something you want to put to server');
__doPostBack('UpdatePanel1', '');
}
If it doesn't work I would like to suggest you to put one hidden field inside Update panel:
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<asp:HiddenField ID="hdnData" value="" runat="server" />
<!-- your content goes here -->
</ContentTemplate>
</asp:UpdatePanel>
And then do the same work like above:
function setArgAndPostBack() {
//Here hidden field is filled with your data
$("#<%=hdnData.ClientID%>").val('something you want to put to server');
__doPostBack('UpdatePanel1', '');
}
In first scenario you are able to get __EVENTARGUMENT in server side:
String args = Request["__EVENTARGUMENT"];
If first scenario doesn't work you can use something like that:
String args = hdnData.Value;//This works even in Page_Load function.

Value set using JavaScript is not persisted on Postback

I have two list controls in my asp.net page and am populating the second list control using javascript. Problem is the script executes and i can see the value moved from first list box (ConfiguredOrgListBox) to second list box(SelectedOrgListBox) but when i try to save using submit button i find my second list as empty and first list box as it was earlier. Below is the script and mark up.
//call this method to register the script
private void CreateMoveOrganizationScript(StringBuilder sb) {
sb.Append( #"<script language=javascript type=text/javascript>;
function moveOrganisation() {");
sb.Append( #"var source = document.getElementById('"+ ConfiguredOrgListBox.ClientID +#"');
var target = document.getElementById('"+SelectedOrgListBox.ClientID+ #"');
if ((source != null) && (target != null)) {
var newOption = new Option();
newOption.text = source.options[source.options.selectedIndex].text;
newOption.value = source.options[source.options.selectedIndex].value;
target.options[target.length] = newOption;
source.remove(source.options.selectedIndex) ;
}
} </script>");
}
Markup
<asp:Label ID="ConfiguredOrgLabel" runat="server" Text="Available Organizations"></asp:Label><br />
<asp:ListBox ID="ConfiguredOrgListBox" runat="server" Width="98%" Height="100px"></asp:ListBox>
<input id="MoveOrgRight" type="button" value=">>" onclick="moveOrganisation()" />
<asp:Label ID="SelectedOrgLabel" runat="server" Text="Selected VNA Organizations"></asp:Label><br />
<asp:ListBox ID="SelectedOrgListBox" runat="server" Width="98%" Height="100px"></asp:ListBox>
Please let me know what I am doing wrong
Regards,
JeeZ
According to this, it's because the list box doesn't post back to tell the back-end that it's changed. They use a hidden field which holds info on what changes were made with JavaScript and then on postback it updates the back-end.
You need to process these changes during postback. When postback happens ASP.NET engine loads control's data from view state and it doesn't know that client modified values using javascript, so you should manually extract those values from Request.

Categories

Resources