Chnage asp.net button text permanently using Javascript - javascript

Hi hope this is an easy one. So help me.
i have asp.net button. based upon the input values given to javascript function I want to change the asp.net button value permanently. Even if the page post backs, it should not affect.

What I understood from the above description is you want to change the "Button" text through java script and it should not change, when user post-back page to server. If yes then this solution might helpful for you but below solution will not work, if browser closed and open again.
According to me the best way to persist the value is storing into hidden field, which will be posted every time when your page post backs. So it will never change until your code will not modified it for e.g.:
**ASPX PAGE :**
asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick="javascript:xyz()" />
<asp:HiddenField ID="HiddenField1" runat="server" />
**JavaScript:**
<script>
var value = document.getElementById("HiddenField1").value;
document.getElementById("Button1").value = value;
function xyz() {
document.getElementById("HiddenField1").value = 'world';
}
</script>
**Code Behind [C#]:**
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HiddenField1.Value = "Hello";
}
}
In an above code, when user clicks button then its value (World) will stored into hidden field and set as title through javascript otherwise it will display default value (Hello).
hope this helps !!

It would probably be the easiest using jquery. The code will look like this:
$(document).ready(function() {
$("#button_id").val(new_value);
});

Related

Call the Java script to set value after values loaded in dot net drop down list

Need help to insert an item value into drop down list(asp.net).
Using java script values should be inserted into drop down index 0 value.
ddlState having lists but index 0 should be set from previous page.
Coming from page 1 where state showing as KER when i open page 2 state name KER should be taken using Javascript and set as initial drop down value .
Protected void page_load()
{
this.BindCountrydropdown();
}
public void Bind_ddlState()
{
conn.Open();
SqlCommand cmd =new SqlCommand("select State,StateID from countryState where CountryId='" + ddlcountry.SelectedValue +"'", conn);
SqlDataReader dr = cmd.ExecuteReader();
ddlstate.DataSource = dr;
ddlstate.Items.Clear();
ddlstate.Items.Add("--Please Select state--");
ddlstate.DataTextField = "State";
ddlstate.DataValueField = "StateID";
ddlstate.DataBind();
conn.Close();
}
"Please Select state" should show below Java script value (“StateName”) from previous page. Drop down list loaded once second page opened from 1st page. Java script should set value after page load"
function loadState()
{
document.getElementById(“ddlState”).value=window.opener.parent.document.getElementById(“StateName”).value;
}
<body onload =“ loadState()”>
<asp:DropDownList ID=“ddlState” runat =“server”> </asp:DropDownList>
Well, you leaving out a boatload of details here.
So, we have web page 1, user selects country, and then selected state (two values).
They then are to hit a button and we jump to page 2.
On page two, we want to load up the drop down list, and set it to the same state value chosen on the previous page.
Since we loading up the ddl, and since the page load WILL run, then I see no need, nor advantage or benefits by attempting to use JavaScript for this purpose. Perhaps if we were to remain on the one page - maybe JavaScript might help, but since we are jumping and navigating to a whole new page, then JavaScript not really required, and benefits us in no way that I can determine.
So, say we have a drop down, on page 1
This:
<h4>Select State</h4>
<asp:DropDownList ID="DropDownList1" runat="server"
DataValueField = "Alphacode"
DataTextField = "State" Width="160px" >
</asp:DropDownList>
<br />
<br />
<asp:Button ID="Button1" runat="server"
Text="Jump to next web page" CssClass="btn" OnClick="Button1_Click" />
And our code to load that ddl is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCombo();
}
void LoadCombo()
{
DropDownList1.DataSource =
General.MyRst("SELECT AlphaCode, State FROM tblStates ORDER BY State");
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select State", "0"));
}
And now we have this:
So, we select a state from the drop down, and hit the button to jump to the 2nd page.
And now we click on the button:
So, our button click now has to pass the value to the next page
So, say this code for the button click:
protected void Button1_Click(object sender, EventArgs e)
{
Session["StatePick"] = DropDownList1.SelectedItem.Value;
Response.Redirect("WebFormB.aspx");
}
Now, we jump to our 2nd page WebFormB.aspx.
So, this page has the same drop down but we need to pass/set/get the value from the previous page.
So, we have this markup:
<h4>This is web page B</h4>
<h4>Select State</h4>
<asp:DropDownList ID="DropDownList1" runat="server"
DataValueField = "Alphacode"
DataTextField = "State" Width="160px" >
</asp:DropDownList>
So our page load (ALWAYS use !IsPostBack stub in on-load), has to load up the ddl, but ALSO set the value from the previous page:
eg this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCombo();
}
void LoadCombo()
{
DropDownList1.DataSource =
General.MyRst("SELECT AlphaCode, State FROM tblStates ORDER BY State");
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select State", "0"));
// select state pick from previous page.
DropDownList1.SelectedValue = Session["StatePick"].ToString();
}
So, now when we select a ddl, then click button to jump to next page, we get this:
So, SINCE you note we are to jump to a whole new page, then really no JavaScript code can help, will help, and as above shows, not required anyway.

Listbox is null when removing items clientside

I inherited an Web Forms project and am still somewhat new to Web development. On this page, we have 2 listboxes: lstCaseLoad, that is populated with with "Caseloads" (ID numbers) and lstAssignedCaseLoad, that is populated with Caseloads selected by the Form User. The user can select Caseloads from lstCaseLoad and hit a button to remove and transfer them to lstAssignedCaseLoad, which is done clientside with JavaScript. The user can also do the opposite, removing from lstAssigned to lstCaseLoad on clientside. The user has to hit a Submit button which will Post and save the changes to SQL.
Adding new CaseLoads from lstCaseloads to lstAssigned and submitting works fine. Removing from lstAssigned is where I'm facing problems. lstAssigned seems to become null when Submitting and therefore can't save. Code below.
Listboxes:
<asp:ListBox ID="lstCaseLoad" runat="server" SelectionMode="Multiple" />
<asp:ListBox ID="lstAssignedCaseLoad" runat="server" Height="175px" SelectionMode="Multiple" />
//Adding Caseload to Assigned
$("#btnAddCaseLoad").bind("click", function () {
var options = $("[id*=lstCaseLoad] option:selected");
$("[id*=lstAssignedCaseLoad]").append($(options).clone());
$(options).remove();
return false;
});
//Removing Caseload from Assigned
$("#btnRemoveCaseLoad").bind("click", function () {
var options = $("[id*=lstAssignedCaseLoad] option:selected");
$("[id*=lstCaseLoad]").append($(options).clone());
$(options).remove();
return false;
});
Code Behind
protected void Page_Load()
{
if (!IsPostBack)
{
//Retrieving and Binding listboxes. No issues here
GetData();
BindData();
}
else
{
var test= Request.Form.AllKeys;
//Temp variable to check all elements for debugging. lstAssignedCaseLoad is missing when deleting. Is fine when adding new caseload
//Read listAssignedCaseLoad items to comma seperated strings. Becomes null when trying to remove items
string strCaseLoad = Request.Form[lstAssignedCaseLoad.UniqueID];
//Transfer string strCaseload to (field)List<string> for saving. Works fine when string is not empty
userCaseLoadList = ProcessListString(strCaseLoad, lstAssignedCaseLoad);
}
}
//Submit button method. Works as intended
protected void EditUser_Click(object sender, EventArgs e)
{
identityMgr.EditUser(Email.Text, userRoleList, userCaseLoadList);
}
I tried searching and can't quite find the same issue. Thanks for your time and help!
This is because of "selected" attribute of option in listbox. If you select the option in "lstCaseLoad" which doesn't have the "selected" attribute and click on remove button then it will add to "lstAssigned" but the added option also dont have this "selected" attribute because we are cloning. So if you want to do the reverse process then you have to select(click) that option again from "lstAssigned" before clicking on remove. You can observe that "selected" attribute behavior by inspecting the options before button click.

how can i use javascript variable value in asp.net button click

Given
<asp:Label ID="lbldistance" runat="server"></asp:Label>
I am assigning it the value with:
var distance = response.rows[0].elements[0].distance.text;
document.getElementById('<%=lbldistance.ClientID%>').innerHTML=distance;
I want to assign lbldistance value in textbox
protected void btnValue_Click(object sender, EventArgs e)
{
txtJSValue.Text = lbldistance.Text;
}
but when i click the btnValue, lbldistance value disappears and i don't see the value in the TextBox..
I am afraid you cannot do that with a label. In ASP.NET state is kept in ViewState across postback. An ASP.NET <asp:Label> is rendered into an HTML span and a span does not have ViewState. Therefore, when you change the innerHTML of the label, you are actually changing the innertHTML of the span tag. Once you press the button, the page is posted to the server where the Label is constructed and it is constructed with the initial text, NOT the one you think it should since it was changed for a span. This (not keeping ViewState for a label), I think, is done for a good reason:
An HTML label should display something to the user and it is not meant to be changed by the user so there is no point in keeping the state across postback.
To accomplish what you want, use a hidden field like this:
<asp:HiddenField ID="HiddenField1" runat="server" />
Your javascript:
var distance = response.rows[0].elements[0].distance.text;
// Assign distance to your label so it shows on the page
document.getElementById('<%=lbldistance.ClientID%>').innerHTML=distance;
// Assing distance to hidden field so you can get it on the server side
document.getElementById('<%=HiddenField1.ClientID%>').value = distance;
Here is how to get the value on the server side:
txtJSValue.Text = this.HiddenField1.Value;
I am not sure why you are going all the way to the server to change the Text of the txtJSValue textbox. You can do that easily on the browser side the same as you are setting the label:
document.getElementById('<%=txtJSValue.ClientID%>').value = distance;

Change labels text with javascript and read it from code behind

I have an asp.net page with a label on it. The label has no text.
<asp:Label ID="Label1" runat="server"></asp:Label>
At some point, I call a javascript function that adds some content to the label, as follows:
function myFunc() {
label = document.getElementById("Label1");
list = document.getElementById("list");
label.innerHTML = list.innerText;
}
After that function is done, I click a button on the page, that calls its onclick event:
protected void Button1_Click(object sender, EventArgs e)
{
string a = Label1.Text;
}
For some reason, the Label1.Text is still empty. Why? Is there any way I could fix this?
Thanks.
Because the value doesn't get posted to the code-behind.
No matter how much WebForms tries to hide this, the only data that gets posted from a web page to the server is data that's in form elements. What WebForms does with things like label texts is stuff them into an input type="hidden" as one big serialized base-64 encoded string. (It calls this "view state" but it's really just a hidden form element.)
Changing the page markup doesn't change anything server-side because page markup isn't posted to the server.
What you can do is create a form element and change that along with the markup. Something as simple as:
<asp:HiddenField runat="server" ID="Hidden1" />
Whenever you change the markup in JavaScript, also change that value:
label = document.getElementById("Label1");
hidden = document.getElementById("Hidden1");
list = document.getElementById("list");
label.innerHTML = list.innerText;
hidden.value = list.innerText;
This will be posted back to the server, since it's a form element. Then you can access the value server-side:
string a = Hidden1.Value;
ID="Label1" for ASP.NET is server side, but for javascript we need a client side ID ie "<%=Label1.ClientID%>"

ASP.NET hidden field not updating after postback

I have some code on my ASP page which looks like this:
<asp:UpdatePanel runat="server" id="updatepanel1" UpdateMode="Conditional" onload="updatepanel1_Load" ChildrenAsTriggers="false">
<ContentTemplate>
<asp:HiddenField id="sendingRequest" runat="server" Value="0" />
....
</ContentTemplate>
</asp:UpdatePanel>
I also have some javascript on my page which does this, to trigger the update of the updatepanel:
var sendingRequest = document.getElementById("<%=sendingRequest.ClientID%>");
sendingRequest.value = "1";
__doPostBack('<%= updatepanel1.ClientID %>', '');
Everything works fine up to now, but in my updatepanel1_Load event, I try to set the value back to "0" :
sendingRequest.Value = "0";
This value never gets updated and set back to 0 on the client after the postback, and I can't figure out why!
Can anyone help? Thanks
If you're having problems with a hidden field, you could use a TextBox instead. Hide the textbox with css (display: none;) to achieve similar results to a hidden field. Its not exactly pretty, but its a workable workaround.
Try to call registerstartupscript or something like that from server side. I can't remember exactly the method name but its part of page object. This will register any javascript you would like to execute after postback on the client side.
This similar scenario is done here successfully:
http://encosia.com/easily-refresh-an-updatepanel-using-javascript/
Ensure you are following the same steps - I can't see all of your code. Try with a label first to make sure it gets updated as a visible control. If that works then narrow it down with your hidden value to make sure the behavior isn't different for a hidden control.
I had an issue with three HiddenFields being set in Code-Behind, but their values were not set when polled from JQuery.
My issue turned out being that my Master Page uses an UpdatePanel, and in my ASP.Net Init event I was purposing that UpdatePanel with conditional rendering.
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
mstr = CType(Master, Site)
'setup partial rendering so Log can update asynchronously
scriptManager = CType(mstr.FindControl("ScriptManager1"), ScriptManager)
scriptManager.EnablePartialRendering = True
scriptManager.AsyncPostBackTimeout = 28800
CType(mstr.FindControl("UpdatePanel1"), UpdatePanel).UpdateMode = UpdatePanelUpdateMode.Conditional
CType(mstr.FindControl("UpdatePanel1"), UpdatePanel).ChildrenAsTriggers = False
End Sub
The issue was that I forgot to then call update on my panel after setting the HiddenFields. I had to do this because my button was a partial-postback control (UseSubmitBehaviour=False)
hfParams.Value = paramlist.ToString()
hfForms.Value = formlist.ToString()
hfStartJob.Value = "True"
CType(mstr.FindControl("UpdatePanel1"), UpdatePanel).Update()

Categories

Resources