I want get a value from js to code behind but the value is always an empty string.
I tried to pass the value from js to a label with runat="server" specified but in vain.
html:
<input type="hidden" runat="server" id="Val1"/>
js:
document.getElementById("Val1").value = MyFunction();
function MyFunction()
{
var value = "111";
}
code behind:
protected void sss(object sender, EventArgs e)
{
string aa = Val1.Value;
}
You could also use the Session to return your data.
In js:
sessionStorage.setItem('Val1', '111');
In code behind:
int Val1 = Convert.ToInt32(Session["Val1"]);
Use this
var val = document.getElementById('<%=val1.Client ID%>');
val.value= "111';
In your cs use val1.value
Related
I have a Listbox defined as:
<asp:ListBox ID="lst_Agenda" onchange="drawChart()" OnSelectedIndexChanged="lst_Agenda_SelectedIndexChanged" SelectionMode="Multiple" CssClass="txt12 myListBox" AutoPostBack="true" DataTextField="Name" runat="server" Width="100%" Height="100%" />
After we select some items in this, lst_Agenda_SelectedIndexChanged method of codebehind is called which calls some other ListBoxes to be populated in cascading way. There is a function in Javascript named as drawChart which generates a Chart based on values selected in all these ListBoxes.
Hence I want that codebehind function should be called before the javascript function call on listbox changed event. But currently it is happening just opposite, Javascript function drawChart gets called first without filling values in the listboxes.
I tried calling Javascript function from codebehind method directly by using:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "myscript", "drawChart()", true);
But using this gives me null values for any 'document.getElementById' call.
The Codebehind Function and JS call is as:
protected void lst_Agenda_SelectedIndexChanged(object sender, EventArgs e)
{
lst_Agenda_Changed();
foreach (ListItem li in lst_SubAgenda.Items)
li.Selected = true;
foreach (ListItem li in lst_Doctors.Items)
li.Selected = true;
lst_SubAgenda_Changed();
lst_Group_Changed();
//ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "myscript", "drawChart()", true);
}
The Javascript for drawChart is as:
function drawChart() {
var tempDateToWeek = "";
var tempDateToYear = "";
var DateOfWeek = new Date();
tempDateToWeek = document.getElementById('txtRangeTo').value.substring(0, 2);
tempDateToYear = document.getElementById('txtRangeTo').value.substring(6, 10);
...........
I am getting error in drawChart if I call it from codebehind at line where I fill variable tempDateToWeek by value of document.getElementById('txtRangeTo').
So how can I achieve this?
You should call RegisterStartupScript instead of RegisterClientScriptBlock in your event handler in code-behind. It will cause the Javascript code to be executed once the page has loaded after the postback, so that the DOM elements will be accessible with document.getElementById.
protected void lst_Agenda_SelectedIndexChanged(object sender, EventArgs e)
{
lst_Agenda_Changed();
foreach (ListItem li in lst_SubAgenda.Items)
li.Selected = true;
foreach (ListItem li in lst_Doctors.Items)
li.Selected = true;
lst_SubAgenda_Changed();
lst_Group_Changed();
ScriptManager.RegisterStartupScript(this, GetType(), "DrawChart", "drawChart();", true);
}
The onchange event handler should also be removed from the DropDownList to avoid calling the client code before the postback.
Why don't you try removing onchange="drawChart()" from asp Control.
Hope this will help you.
//your code here
string script = "window.onload = function() { drawChart(); };";
ScriptManager.RegisterClientScriptBlock(this, this.Page.GetType(), "drawChart", script,true);
And
tempDateToWeek = document.getElementById("<%=txtRangeTo.ClientID %>").value.substring(0, 2);
my asp project has a asp button which named 'Save'. However, i need to change it to 'Update' in jQuery to do other thing in one button.
The problem is the C# onclick code is still read it as Save..
Code:
//Main
<asp:Button ID="btnSubmit" runat="server" Text="Save" />
//JQuery
$("#<%=btnSubmit.ClientID %>").val("Update");
//C#
var button = sender as Button;
var buttonName = button.Text; //Save
Update1
Question is:
I need to change the button name in JQuery
$("#<%=btnChangeName.ClientID %>").click({
$("#<%=btnSubmit.ClientID %>").val("Update"); //Change Save to Update
});
Then use it in C#:
protected void btnSubmit_Click(object sender, EventArgs e)
{
var button = sender as Button;
var buttonName = button.Text;
if (buttonName == "Save")
{//something}
else
{//something}
}
if you want to change the Name to Update1 in Jquery
try like this
$("#<%=btnSubmit.ClientID%>").val('Update');
Event you neeed to use is OnClientClick
Usage example
OnClientClick="onupd();return false;"
Update
Decalre a Hidden FIeld
<asp:HiddenField runat="server" ID="hdntest" Value="0" />
assign the button change value to update and assign it to the hidden field
not access that hidden value in your code behind.
you can assign Button value to Hidden Field like this
$("#<%=btnSubmit.ClientID %>").val("Update");
$("#<%=hdntest.ClientID%>").val($("#<%=btnSubmit.ClientID%>").attr("value"));
If you change the Button.Click value, then it will move to a different method onClick;
private void Form1_Load(object sender, EventArgs e)
{
Button b = new Button();
b.Name = "btnSubmit";// creating here for intellisense - you would create on your front-end
bool recordExists = true;
Button b1 = Controls.Find("btnSubmit", true)[0] as Button;
//the above is for winforms - you'd have to change for web form
b1.Text = recordExists ? "Update" : "Save";
b1.Click += doUpdateOrSave;
}
protected void doUpdateOrSave(object sender, EventArgs e)
{
Button b = sender as Button;
if (b.Text == "Save")
{
//save
}else
{
//update
}
}
I'm trying to disable the two list boxes on load of my web form, but the list boxes are not disabling. I tried the code below but it's still not working on my case. Please let me know where I'm going wrong.
DESIGNER CODE
<telerik:RadListBox ID="lbSelectedDepartmentContacts" runat="server" Width="220px" AutoPostBackOnTransfer="true" AutoPostBackOnReorder="true" AutoPostBackOnDelete="true" CheckBoxes="false" AllowTransfer="true" AllowTransferOnDoubleClick="true" TransferToID="lbDepartmentContacts"
Height="276px" SelectionMode="Single" AllowReorder="True">
<ButtonSettings ShowTransfer="false" ShowTransferAll="false" ReorderButtons="Common" ShowReorder="true" />
</telerik:RadListBox>
</td>
</tr>
<tr>
<td align="right">
<telerik:RadListBox ID="lbDepartmentContacts" runat="server" Width="200px" CheckBoxes="false" AutoPostBackOnTransfer="true" AllowTransfer="true" AllowTransferOnDoubleClick="true" TransferToID="lbSelectedDepartmentContacts"
Height="250px" SelectionMode="Single">
<ButtonSettings TransferButtons="Common" ShowTransfer="false" ShowTransferAll="false" />
</telerik:RadListBox>
BACKCODE
public void DisableControls()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script language='javascript'>function DisableControls(){");
sb.Append(#"var lbl = document.getElementById('lbSelectedDepartmentContacts').disabled = true;");
sb.Append(#" var Txt = document.getElementById('txtDepartmentCategoryContactsFilter').disabled = true;");
sb.Append(#" var btn = document.getElementById('RadButton1').disabled = true;");
sb.Append("}</script>");
if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock",
sb.ToString());
}
string funcCall = "<script language='javascript'>DisableControls();</script>";
if (!ClientScript.IsStartupScriptRegistered("JSScript"))
{
ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall);
}
}
Tried Also:
Page.ClientScript.RegisterStartupScript(this.GetType(), "text", "DepartmentLoad();", true);
JAVASCRIPT CODE
function DepartmentLoad(){
document.getElementById("lbSelectedDepartmentContacts").disabled = true;
document.getElementById("lbDepartmentContacts").disabled = true;
document.getElementById("txtDepartmentCategoryContactsFilter").disabled = true;
ducument.getElementById("RadButton1").disabled = true;}
C# only approach to disable your 2 listboxes...
Delete or comment out your existing DisableControls() method then add the following...
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
DisableControls();
}
private void DisableControls()
{
lbSelectedDepartmentContacts.Enabled = lbDepartmentContacts.Enabled = false;
}
You should generally:
Use Sys.Application.Load to register your script. Calling the function earlier will cause problems with using the client-side API of the IScriptControls: http://msdn.microsoft.com/en-us/library/bb383829.aspx and http://docs.telerik.com/devtools/aspnet-ajax/controls/window/troubleshooting/executing-javascript-code-from-server.
use the API the Telerik control provides: http://docs.telerik.com/devtools/aspnet-ajax/controls/listbox/client-side-programming/objects/radlistbox-object.
There seems to be no set_enabled() or set_disabled() method on the client (at least at the time of writing), so this seems to be impossible with JS, so you should go with the other answer that tells you to use server code.
I've got a multiline asp.textbox input control.
I don't know if my issue is with ASP.NET, the Multiline control, or something else, but the onblur and onfocus are not working.
<script type="text/javascript">
var defaultMsg = 'Write your message here or or call my voice at (xxx) xxx-xxxx.';
var controlMsg = doc.createElement("input");
controlMsg.id = "txtMessage";
controlMsg.type = "text";
controlMsg.value = defaultMsg;
controlMsg.onfocus=function jpFocus() { if (this.value == defaultMsg) this.value = ''; }
controlMsg.onblur=function jpBlur() { if (this.value == '') this.value = defaultMsg; }
</script>
And later....
<asp:TextBox ID="txtMessage" Columns="30" Rows="6" runat="Server" TextMode="MultiLine" />
Does anyone see a reason why this should not be working?
Actually, you're creating a html element and you are attaching an event to it.
In addition, ASP.NET controls does not use the server side id.
Here's what you should do :
var controlMsg = document.getElementById('<%= txtMessage.ClientID %>');
controlMsg.onfocus = // Some Code ...
controlMsg.onblur = // Some Code ...
Try using an anonymous function, like this:
controlMsg.onfocus=function() { if ( ...
Functions and function scope - MDN.
Also, you did call something like document.body.appendChild(controlMsg);, didn't you?
EDIT:
You are using doc.createElement. Make sure that doc definitely points to document.
Also, look at the page in Firefox and see if there are any errors or warnings in the Error Console.
Not sure which version your are using.Please Try this:
protected void Page_Load(object sender, EventArgs e)
{
txtMessage. Attributes["onfocus"]="JavascriptMethod";
}
I'm not sure why this worked and other techniques did not, but this got my HTML to work:
<textarea name="txtMsg" rows="6" cols="30"
onfocus="if(this.value==this.defaultValue)this.value='';"
onblur="if(this.value==='')this.value=this.defaultValue;">[Write your message here or call my voice number at (555) 222-1234.]</textarea>
The text can be very long, and the control does not seem to care. Also, the text is only written in a single location.
I have asp:LinkButton, input Button defined as:
<asp:LinkButton ID="lnkViewPdf" runat="server" CssClass="icoMiniTest" ClientIDMode="Static" >View Office Pdf</asp:LinkButton>
<input id="Button2" type="button" value="TestEnable" onclick="TestEnable(document.getElementById('lnkViewPdf'));" />
the LinkButton is initially disabled in code-behind as:
if (!IsPostBack)
{
this.lnkViewPdf.Enabled = false;
}
and needs to be enabled when Button2 is clicked, so I am calling javascript function to enable the link as:
function TestEnable(lnkbutton) {
alert('TestEnable() called');
alert(lnkbutton.id);
lnkbutton.disabled = "";
//$("#lnkbutton").removeAttr('disabled'); //even this doesn't work
}
But I am not able to enable the linkbutton.
Am I missing something?
Thank you!
__________________________________________________
Anyone interested in solution to above problem:
In code-behind:
this.lnkViewPdf.Attributes["disabled"] = "disabled";
this.lnkViewPdf.Attributes["onclick "] = "return false";
.js:
function TestEnable(lnkbutton) {
$(lnkbutton).removeAttr('disabled');
lnkbutton.onclick = "";
}
NOTE: When setting lnkViewPdf.Enabled = false; LinkButton was being rendered as
<a id="lnkViewPdf" class="aspNetDisabled icoMiniTest">View Office Pdf</a>
see the style class aspNetDisabled, something added by ASP.Net
However setting disabled/onclick attributes from the codebehind as shown above, render Linkbutton as:
<a id="lnkViewPdf" class="icoMiniTest" disabled="disabled" onclick ="return false" href="javascript:__doPostBack('lnkViewPdf','')">View Office Pdf</a>
HTH.
Try now...
function TestEnable(lnkbutton) {
lnkbutton.disabled = "";
lnkbutton.onclick = "";
}
In the code behind, rather than disable by setting Enabled = false, set:
lnkViewPdf.Attributes["disabled"] = "disabled"
So your javascript function:
function TestEnable(lnkbutton) {
alert('TestEnable() called');
alert(lnkbutton.id);
lnkbutton.disabled = "";
}
Your markup:
<asp:LinkButton ID="lnkViewPdf" runat="server" CssClass="icoMiniTest" ClientIDMode="Static" >View Office Pdf</asp:LinkButton>
<input id="Button2" type="button" value="TestEnable" onclick="TestEnable(document.getElementById('<%= lnkViewPdf.ClientID %>')); return false;" />
And your code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
lnkViewPdf.Attributes["disabled"] = "disabled";
}
$("#<%=lnkViewPdf.ClientID %>").removeAttr("disabled");
You need to know the .Net constructed name in order to accomplish it. The easiest way is to have it set in the head of the page if you can:
<script language="javascript">
var lnkbuttonToEnableId = "<%= this.lnkViewPdf.ClientId %>";
function TestEnable() {
alert('TestEnable() called');
lnkbuttonToEnableId.disabled = false;
}
</script>
At any rate, the only way to get it to work is to pass the ClientId of lnkViewPdf to the function somehow.
try both of those:
<input id="Button2" type="button" value="TestEnable"
onclick="TestEnable(document.getElementById('<%= lnkViewPdf.ClientID %>'));" />
or
$("#<%= lnkViewPdf.ClientID %>").removeAttr('disabled');
UPDATE: Since you are disabling the LinkButton on server side .NET strips the href attribute from the <a> html element. What you should do to prevent the lost of that information is to disable the LinkButton on the client and then enable it when you need to. Also instead of disabling it all you need to do is remove the href attribute.
So first you need to retain the href and remove it so the <a> link become disabled:
$(document).ready(function () {
var $lnkViewPdf = $("#lnkViewPdf");
$lnkViewPdf.data("href", $lnkViewPdf.attr("href"));
$lnkViewPdf.removeAttr("href");
});
and the function that enables it:
function TestEnable(lnkViewPdfId) {
var $lnkViewPdf = $("#" + lnkViewPdfId);
$lnkViewPdf.attr("href", $lnkViewPdf.data("href"));
}
If you disable the LinkButton using:
if (!IsPostBack)
{
this.lnkViewPdf.Enabled = false;
}
Then the href attibute won't be displayed in the HTML. If you manually add the disabled attribute instead:
if (!IsPostBack)
{
lnkViewPdf.Attributes.Add("disabled", "disabled");
}
Then you're code will work just fine.
Oh!.. and one last thing: You need to set the PostBackUrl property for the LinkButton. You missed it in your example.