passing clientID to javascript and extracting a value, clarification - javascript

Forgive the noob question, but I'm trying to get my head wrapped around this. I have some controls that are inside of an in a listview that are used to submit some information. I'm running a test pattern here to do this, but I'm getting object undefined errors. All of the articles I've seen about this are kind of vague. In this example, I'm trying to pass the id of a textbox, then pull the value from that in javascript. Can you tell me what I'm doing wrong?
<form id="form1" runat="server">
<asp:ScriptManager runat="server" />
<script type="text/javascript">
function ClientIDS(id) {
var info = document.getElementById(id).value;
alert(info);
return false;
}
</script>
<asp:ListView runat="server" ID="lsvTest">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtTextBox" />
<asp:Button runat="server" ID="btnSubmit" Text='<%#Eval("Name") %>' OnClientClick="ClientIDS('<%=txtTextBox.ClientID %>')" />
</ItemTemplate>
</asp:ListView>
</form>
Thanks

if you are want to doing using jquery than try this
just replace in button onclientclick with this one
OnClientClick="ClientIDS(this);"
and than find your previous input text in to asp:listview
function ClientIDS(obj) {
var txt = $(obj).prevAll('input[id*="txtTextBox"]:first');
alert($(txt).val());
return false;
}

You can't have inline code in a property for a server control.
Generally I would do this in the codefile.
for (int j = 0; j < this.lsvTest.Items.Count; j++)
{
var btnSubmit = (Button)this.lsvTest.Items[j].FindControl("btnSubmit");
var txtTextBox = (TextBox)this.lsvTest.Items[j].FindControl("txtTextBox");
btnSubmit.Attributes["onclick"] = string.Format("ClientIDS('{0}')", txtTextBox.ClientID);
}

Java Script Code
<script type="text/javascript">
function ClientIDS(Btnid) {
var textBoxID = Btnid.id.replace('btnSubmit', 'txtTextBox');
var info = document.getElementById(textBoxID).value;
alert(info);
return false;
}
</script>
HTML Code
<asp:ListView runat="server" ID="lsvTest">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtTextBox" />
<asp:Button runat="server" ID="btnSubmit" Text='<%#Eval("Name") %>' OnClientClick="ClientIDS(this)" />
</ItemTemplate>
</asp:ListView>

first of all, you're using javascript to do what you're jQuery library should be doing.
For example:
var info = document.getElementById(id).value;
// is easier as
var info = $("#"+id).val();
Secondly, it's been awhile, but i dont think you can put your asp script text in the form like that

You can use ItemDataBound event for the repeater to make this. See the following code
protected void lsvTest_ItemDataBound(object sender, ListViewItemEventArgs e)
{
string txtbox = e.Item.FindControl("txtTextBox").ClientID;
Button btn = e.Item.FindControl("btnSubmit") as Button;
btn.OnClientClick = string.Format("ClientIDS('{0}')", txtbox);
}

Related

Finding the Client ID for a RadGrid inside a RadLightBoxItem tag in a RadLightBox

I'm trying to fetch the ClientID for a RadGrid control from client side using JavaScript so that I'll be able to bind data to this from the client side.
The RadGrid is present within the RadLightBox and needs to be populated on a button click event. The markup for LightBox looks something like this.
<telerik:RadLightBox ID="RadLightBox1" runat="server">
<Items>
<telerik:RadLightBoxItem runat="server">
<ItemTemplate>
<telerik:RadGrid runat="server" ID="lightbox_radgrid" AutoGenerateColumns="false">
<MasterTableView>
<Columns>
<%-- Columns not shown here --%>
</Columns>
</MasterTableView>
<ClientSettings>
<ClientEvents OnCommand="window_radgrid_OnCommand" />
</ClientSettings>
<GroupingSettings CaseSensitive="false" ShowUnGroupButton="true" />
</telerik:RadGrid>
</ItemTemplate>
</telerik:RadLightBoxItem>
</Items>
</telerik:RadLightBox>
This is the partial Javascript Code that I have written. I am able to find upto the RadLIghtBoxItem element but unable to fetch the RadGrid and it's clientID. This method is to be executed on success of a call to a web service to return the data.
function onSucessCallThis(result, userContext, methodName) {
var radWindow = $find('<%= lightbox.ClientID %>');
var LightBoxItems = radWindow.get_items();
console.log(LightBoxItems);
console.log(LightBoxItems.get_count());
var item = LightBoxItems.getItem(0);
console.log(item); //Able to fetch LightBoxItem
var radGrid = item.FindControl("lightbox_radgrid"); //Doesn't work
}
I'm not sure if this is the right way to have a radGrid inside a radLightBox. There isn't many examples of this online.
I think it will be easier for you to use a RadWindow's ContentTemplate. Something like:
<telerik:RadWindow ID="RadWindow1" runat="server" Modal="true">
<ContentTemplate>
<telerik:RadGrid ID="RadGrid1" runat="server"></telerik:RadGrid>
</ContentTemplate>
</telerik:RadWindow>
<script>
function onSucessCallThis(result, userContext, methodName) {
var wnd = $find("<%=RadWindow1.ClientID%>");
if (!wnd.isVisible()) {
wnd.show();
}
var grid = $find("<%=RadGrid1.ClientID%>");
var mtv = grid.get_masterTableView();
mtv.set_dataSource(result);
mtv.dataBind();
}
</script>
If you want to keep using a lightbox, review the Get Client-side Reference to a Control Object article. The gist is that you can easily loop through the DOM, for example:
<telerik:RadLightBox ID="RadLightBox1" runat="server">
<Items>
<telerik:RadLightBoxItem runat="server">
<ItemTemplate>
<telerik:RadGrid CssClass="gridInLightbox" runat="server" ID="lightbox_radgrid" AutoGenerateColumns="false">
</telerik:RadGrid>
</ItemTemplate>
</telerik:RadLightBoxItem>
</Items>
</telerik:RadLightBox>
<script>
function onSucessCallThis(result, userContext, methodName) {
var lightbox = $find('<%= RadLightBox1.ClientID %>');
//item objects do not refer the DOM so we can use the lightbox as a parent for the traversal
var radGrid = $telerik.$(".gridInLightbox", lightbox.get_element())[0].control;//of course, add defensive checks
alert(radGrid);
var mtv = radGrid.get_masterTableView();
mtv.set_dataSource(result);
mtv.dataBind();
}
</script>

Assign value of textbox in Javascript and set the value in session with C#

I've been struggling for a while with a Javascript/C# issue i have. I've been trying to set a Session variable from Javascript. I tried to use page methods before but it resulted in my javascript crashing.
In the javascript :
PageMethods.SetSession(id_Txt, onSuccess);
And this page method :
[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
Page aPage = new Page();
aPage.Session["id"] = value;
return value;
}
I haven't had any success with this. Therefore, i tried to set the value of a textbox from my javascript and put a OnTextChanged event in my c# to set the session variable but the event is not fired.
In the javascript:
document.getElementById('spanID').value = id_Txt;
In the html :
<asp:TextBox type="text" id="spanID" AutoPostBack="true" runat="server"
ClientIDMode="Static" OnTextChanged="spanID_TextChanged"
style="visibility:hidden;"></asp:TextBox>
In the cs :
protected void spanID_TextChanged(object sender, EventArgs e)
{
int projectID = Int32.Parse(dropdownProjects.SelectedValue);
Session["id"] = projetID;
}
Does anyone have an idea as of why none of my events where fired ? Do you have an alternative solution that I could try ?
I found the issue, I didn't have the enableSession = true and i had to use the HttpContext.Current.Session["id"] = value, like stated by mshsayem. Now my event is fired properly and the session variable is set.
First, ensure you have sessionState enabled (web.config):
<sessionState mode="InProc" timeout="10"/>
Second, ensure you have page-methods enabled:
<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
Third, set session value like this (as the method is a static one):
HttpContext.Current.Session["my_sessionValue"] = value;
Sample aspx:
<head>
<script type="text/javascript">
function setSessionValue() {
PageMethods.SetSession("boss");
}
</script>
</head>
<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
<asp:Button ID="btnSetSession" Text="Set Session Value (js)" runat="server" OnClientClick="setSessionValue();" />
<asp:Button ID="btnGetSession" Text="Get Session Value" runat="server" OnClick="ShowSessionValue" />
<br/>
<asp:Label ID="lblSessionText" runat="server" />
Sample code behind:
[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
HttpContext.Current.Session["my_sessionValue"] = value;
return value;
}
protected void ShowSessionValue(object sender, EventArgs e)
{
lblSessionText.Text = Session["my_sessionValue"] as string;
}

Why is my Javascript function not being called when I have invoked it in OnClientClick

I have just today learned how to call backend functions from Javascript and my first Javascript function worked. However, when I tried the very same function and calls on a different front end webpage of the same project for the same button, which is delete, the Javascript function is no longer being called. This is so weird. Here is the Javascript function:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type = "text/javascript" >
function watchdelete() {
if (drpManufacturer.SelectedItem.Text != "") // If there is a selected Manufacturer
{
return confirm("Are you Sure You want to delete this Dimension Detail?");
}
else
{
alert("Please select a Manufacturer first before deleting");
return false;
}
}
</script>
<asp:ScriptManager ID="scripman1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
Here is the OnClientClick call for the delete button:
<asp:Button ID="btnDimensionDel" runat="server" Text="Delete" OnClientClick = " return watchdelete();" OnClick="btnDimensionDel_Click" />
Am I doing something wrong? All I did was add a few lines to a Javascript function that was previously working on another page. I have a feeling there is some syntax error in this Javascript function but you will have to excuse me as I am new to Javascript. Can one use a boolean type for return values in Javascript? Thank you very much in advance.
Use this code:
<script type = "text/javascript" >
function watchdelete() {
var manufacturer = document.getElementById('<%:drpManufacturer.ClientID%>');
var strManufacturer = manufacturer.options[manufacturer.selectedIndex].value;
if (strManufacturer) // If there is a selected Manufacturer
{
return confirm("Are you Sure You want to delete this Dimension Detail?");
}
else {
alert("Please select a Manufacturer first before deleting");
return false;
}
}
</script>
remove return statement:
<asp:Button ID="btnDimensionDel" runat="server" Text="Delete"
OnClientClick="watchdelete()" OnClick="btnDimensionDel_Click" />

Calling server side event in asp.net from java script

Surely will be marked as duplicate one but after tons of question and example i couldn't solve my problem.
What i want?
Calling server side event handler in asp.net from client side java script it is not going on server side. I checked it by setting breakpoint, the page flicks but server side method is not called.
My click event on code behind is
protected void btninsert_Click(object sender, EventArgs e)
{
// my code
}
aspx file
<asp:Button ID="btninsert" runat="server" ValidationGroup="form" CssClass="btn"
OnClientClick="DoPost()" Text="Save" />
Javascript method is
function DoPost() {
function DoPost() {
var chk = document.getElementById('<%= chkstatus.ClientID %>');
if (chk.checked)
__doPostBack('<%= btninsert.ClientID %>', 'OnClick');
return true;
//return false;
}
}
I also tried this
__doPostBack('btninsert', 'OnClick'); and __doPostBack('btninsert', ''); and $('btnSubmit').trigger('click'); with no success.
What am i doing wrong?
Edit: If i uses OnClick event then it is going in the server side event irrespective of the if condition in the DoPost method.
Ahh it was simple. Thanks to all answers.
Solution:
Use OnClick attribute for server side event and OnClientclick for client event for validation.
OnClientClick javascript method will return true and false which decides whether serverside onclick event will fire or not.
Code will be somthing like this
<script type="text/javascript">
function DoPost() {
var chk = document.getElementById('<%= chkstatus.ClientID %>');
if (chk.checked) {
var c = confirm("are you sure?");
if (c == true) {
return true;
} else
{ return false; }
}
return true;
}
</script>
And the Button tag
<asp:Button ID="btninsert" runat="server" ValidationGroup="form" CssClass="btn"
OnClientClick="return DoPost();" OnClick="btninsert_Click" Text="Save" />
it can work!!
if you call __doPostBack('btninsert', ''), add below to Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if ( Request["__EVENTTARGET"] == "btninsert" ) {
btninsert_Click(sender, e);
}
}
<asp:Button ID="btninsert" runat="server" ValidationGroup="form" CssClass="btn" OnClick="btninsert_Click" OnClientClick="DoPost()" Text="Save" />
Add OnClick="btninsert_Click", because without this information, asp.net has no way know which event handler to run for the "Click" event. In case you want to control whether to post back by client side script. You can do something like this:
<asp:Button ID="btninsert" runat="server" ValidationGroup="form" CssClass="btn" OnClick="btninsert_Click" OnClientClick="return DoPost()" Text="Save" />
function DoPost() {
__doPostBack('<%= btninsert.ClientID %>', 'OnClick');
return true;
//return false;
}
Note the OnClientClick="return DoPost()"
<asp:Button ID="btninsert" runat="server" ValidationGroup="form" CssClass="btn"
OnClientClick="return DoPost();" Text="Save" />
modify your line like this
You can try Ajax, by using Webmethod. I used this in my project and it works fine! You may see the question, solutions and code here: http://www.codeproject.com/Questions/416748/How-to-Call-WebMethod-of-Csharp-from-JQuery
Use ASP link button instead of ASP BUTTON. Button control is not called from javascript because it type is submit while link button type is button.
For example i have added two asp control
<asp:LinkButton ID="lbtest" runat="server" Text="Link Button"></asp:LinkButton>
<asp:Button runat="server" ID="btnbutton" Text="Button" />
and execute the page
When we view the source of running page its look like this
<a id="lbtest" href="javascript:__doPostBack('lbtest','')">Link Button</a>
<input type="submit" name="btnbutton" value="Button" id="btnbutton" />

asp.net hiddenfield.value is not updated by javascript

I want to assign a value to an asp.net hiddenfield via javascript prior to post back.
But in the code behind the hidden fieldvalue is null. The code I am using is:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="True" Visible="True">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="save1" EventName="Click">
</asp:AsyncPostBackTrigger>
</Triggers>
<ContentTemplate>
<asp:HiddenField ID="HiddenField1" runat="server" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="save1" runat="server" Text="Send" OnClientClick="return SaveFase();" />
function SaveFase() {
var UP = jQuery.get('<% = HiddenField1.ClientID %>');
UP.Value= "xxxxxxxxxxxxxxxxxxxx"
return true
}
Protected Sub PassBackImage(sender As Object, e As EventArgs) Handles save1.Click
dim Value = HiddenField1.Value
End Sub
Use the ID selector and the .val() method:
var UP = jQuery('#<% = HiddenField1.ClientID %>');
UP.val("xxxxxxxxxxxxxxxxxxxx");
You probably meant to write:
$('#<% = HiddenField1.ClientID %>').val('xxxxxxxxxxxxxxxxxxxx');
Also, put your javascript function in a sctipt block:
<script type="text/javascript">
function SaveFase() {
return $('#<% = HiddenField1.ClientID %>').val('xxxxxxxxxxxxxxxxxxxx');
}
<script>
Instead of using jQuery.get (which is a call to an HTTP GET method http://api.jquery.com/jQuery.get/), use
jQuery.find('#' + <% = HiddenField1.ClientID %>)
Then from there it should work. If it doesn't, use an error console to see what errors are being raised when the call is made (most browsers have one built in.

Categories

Resources