ASP.NET - using javascript to change text of LinkButton on every click - javascript

I have a LinkButton that essentially toggles a menu, "show/hide".
So I am doing the show/hide logic in a javascript method called onShowFiltersClick(), that is attached as an OnClientClick event.
But how do I reach (and change) the text value of the button? It is currently being set statically in the .cs file to "Show filters". But I want to toggle this on the client side. And the changes will probably have to persist across postbacks.
But as it stands now, I can't even retrieve the string "Show filters" from the .js, trying everything both sending the button's clientID as a parameter to the javascript and by accessing it through jQuery $ and the button's css class. I then try to view all sorts of parameters, including text, innertext, value and innerHTML.
So how do I access it?
edit: Neha requested a code snippet, so I'm including one of several I have tried:
function onShowFiltersClick() {
var filtersPanel = $('.filters-panel');
var displayStyle = filtersPanel.css('display');
filtersPanel.toggle('fast');
var showFiltersButton = $('.show-filters-button');
alert(showFiltersButton.text);
alert(showFiltersButton.innerText);
alert(showFiltersButton.innerHTML);
alert(showFiltersButton.value);
if(displayStyle === 'none')
$('.price-slider').repaint();
}
This produces the following:
function (a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)}
followed by a bunch of undefined.

Related

ASP setting control value from Javascript

From a list of names i dynamically create anchor tags on an aspx form page. The result of each is as follows with different names/IDs/titles.
From a list of names i dynamically create achor tags on an aspx form page.
<a target= href="mailto:johnbrown#site.net" onclick="updateSql(document.getElementById('PersonJB'))" runat="server" id="PersonJB" title="JB">John Brown</a>
Java function updateSql is
function update(passLink) {
/* alert("this dialogue has been invoked through codebehind."); */
document.getElementById('<%= btnUpdateSql.ClientID%>').click();
}
btnUpdateSql is defined hidden
<asp:Button ID="btnUpdateSqlt" runat="server" Text="Button" CssClass="hidden"/>
It all seems to work. except I want the click event to be aware of the different link that was clicked.
What I want to achieve: Update btnUpdateSql text with the ID or title of the passed link before called the click event in the javascript function.
How can I set the button text in the Java function? Or how can i use another hidden field?
The purpose being to update SQL table in the click event using the initials as a key.
First of all, multiple links triggering a button click event under the hood is very fragile.
Why not use LinkButton since you are posting back to server anyway.
The advanatage is LinkButton has CommandArgument and CommandName. All links can use same Common Event, and you can see which link trigger the event by looking at the CommandArgument.
If you do not plan to postback to server, you will need to redesign the application to use Ajax. It is out of the scope of original question.

Dropdown's SelectedIndexChanged event is not fired when its populated from client side

I have a dropdown on my page which I am populating from client side javascript code. The SelectedIndexChanged does not fire. But when I populate my dropdown from code behide (.cs file) the even is fired.
Any idea how to handle SelectedIndexChanged when dropdown is being populated from code behind. I could see that dropdown is getting populated as per my needs. Only SelectedIndexChanged even is not getting fired. Also note that the drop down is inside UpdatePanel. Will that be a reason?
Here is my html, javascript and code behind event:
<asp:DropDownList ID="ddS" runat="server" OnSelectedIndexChanged="ddS_SelectedIndexChanged"
AutoPostBack="True" Style="position: absolute; width: 50%;">
Javascript:
$('#ddS').append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>');
CS
protected void ddS_SelectedIndexChanged(object sender, EventArgs e)
{
}
Any help would be appreciated. Thanks in advance.
Edit
My main reason behind doing this is:
I have used jquery ui js for a popup, it has a multi-select drop down list. Since the button in a popup cannot have a server side event I have used ajax call to a web-method in .cs file. This method will update my tables from the database with the options selected in the multi-select drop down. Once it is done I want to close the popup and populate a drop down based on the options selected in multi-select.
I cannot populate my dropdown from code behind because the web-method is a static method and hence any method called from that method has to be a static method. If I write a static method then I cannot access UI controls(my drop down) from a static method. So I was hoping I can populate it from JS and then trigger my indexchange event for further computation.
The short answer is don't do this. This is not how ASP.NET Server Controls were designed to work and you will end up creating a Rube Goldburg making it work. Details below:
ASP.NET has a security feature (Event Validation) built in to prevent data being posted that was not present in the control after the Render stage of the page life-cycle. If this occurs an ArgumentException will be thrown. You can disable event validation or override Render and stick lots of code in your Page_Load function, but I wouldn't recommend it.
So why does all of this happen? ASP.NET Server controls use ViewState in an attempt to create state like the state in a desktop application (Windows Forms => Web Forms see what they did there). ViewState gets upset if it doesn't know about the <options> you added to the <select>. A few solutions are:
1) Populate the DropDownList on the Server-Side (unless you have a very good reason not to) and let the ASP.NET Framework do what it was intended to do (you may also have to add the EnableViewState=true attribute to the DropDownList control although I believe it is the default). If the DropDownList is in an update panel ViewState is updated form the PartialPostBack triggered by the panel so the ViewState stays happy while you get flicker-free updates.
2) Forget the Server-side code and create and populate the <select> control using JavaScript.
a) You can bind a JavaScript event listener to update a hidden field when the selected item is changed. Then on PostBack you can read the value of the hidden field to get the value of the last selected item.
b) You can bind a JavaScript event listener to run a POST or GET (AJAX Request) when the selection changes if you need to communicate those changes with the server-side code. You never really said what your objective is...
EDIT AFTER QUESTION UPDATE:
There are three ways I can think of:
1) Remove the ASP DropDownList control and make it a regular HTML select control. Give the control a name (use the name attribute not just the id attribute). ex:
<select name='options'></select>
On POST, HttpContext.Current.Request.Form is a NameValueCollection that will contain Key-Value pairs of the POSTed data. you should be able to get the selected items from your select control by using the name you gave the select control:
var options = HttpContent.Current.Request.Form["options"].Split(',');
options will now be a list of the selected values. If you need this to be AJAX enabled (no page refresh) wrap it in an UpdatePanel.
2) Write the selected items to a hidden field and collect the values from the hidden field on POST.
3) Trigger a POST to a Web Method that updates a session object which can then be read from inside your non-static code behind class members/methods. There is an optional attribute for the Web Method decoration that enables session:
[WebMethod(EnableSession = true)]
Generally, you need to make sure that your event handlers (your SelectedIndexChanged) are set after all DOM operations. In your case you append your html element by jQuery's append method. Unfortunately, adding callbacks to that method is not possible.
A settimeout with the timer "1ms" however always puts the function in the settimeout on the bottom of the call stack.
$('#ddS').append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>');
setTimeout(function() {
// set listener here
// e.g. $("#ddS option").change(function(){
// ddS_SelectedIndexChanged()
// });
}, 1);

Javascript to enable, disable drop down menu in JSP file having Java code only, no HTML directly

Let me introduce the design.
Each field in a JSP is made by a Map.
The label name, the input type (drop down or other), the input values, the default values, etc are added to the Map, say Map nameAttributes.
There is another class, GeneralWriter writer, to which I do not have access, which takes the values from Map, parses them and writes the proper HTML code.
After writing the Map, writer.writeSelectBox(nameAttributes); is called.
Now, the requirement is:
There is a drop-down menu, depending upon its selected value, some other drop-down menus are disabled (shown in UI, but not modifiable) or enabled.
Since, I am not writing HTML code for the added field, I can not write the function call events to do my job.
I have observed that a JS function is called on onMouseOut event from the fields, as seen in "View Source".
So I thought I might write my code there to check the field value and impact other drop-down menus.
But if I write alert in the JS function (just to check), it won't alert me, means the function is not called and I can not write the enable/disbale code.
Is there any way to achieve the job. The enabling and disabling should depend on what user selects in one of the drop downs.
Sample code:
<%
Map nameAttr = new HashMap();
nameAttr.put(GeneralConst.INPUT_MESSAGE, Const.MSG_FIELD_NAME);
//.....
writer.writeAllSelectBox(nameAttr);
%>
Urgent help needed, thanks.
In View Source of the JSP page, its clear that for some fields onChange and onMouseOut events etc. were added, and in the GeneralWriter class, those things were being written out to the out stream as follows
out.println("<td nowrap><select name=" + strName);
out.println(" style=\"width:" + strWidth + "px\"");
out.println(" onChange ="+onChange);
So, I added my own method there rather than using existing code and introduced the onChange event. The "onChange" variable that you see (the right one) is of java.lang.String type and this had to be passed from the JSP itself, as to what behavior I want or which particular function to call for a particular JSP.
Now I added the following in JSP
<body>
<script>
window.onload = setModeForPara2('MEMBERTYPE','MEMBERSTATE','CKSTATUS') ;
function resetevent(uri){
setModeForPara2('MEMBERTYPE','MEMBERSTATE','CKSTATUS') ;
}
</script>
</body>
where the parameters are the names of the drop down menus, and setModeForPara2() is a JS function to disable/enable as my requirement was stated in original post. It checks if MEMBERTYPE is 0, then render disabled state and gray color to MEMBERSTATE and CKSTATUS drop-down menus, else enable them and remove gray color.
The resetevent(uri) is also a JS function called when the Reset button is clicked to render the disabled state to the State and Status fields.
So that way, setModeForPara2() function is called whenever:
1. the page is loaded,
2. the value of first drop-down (MEMBERTYPE) is changed, and
3. the Reset button is clicked.
Resolved.

How can i apply java script to access the client id or a control placed in the grid view?

I want to access a dropdown asp control client id placed in the gridview.
function validate(){
var ddl = document.getElementById("ctl00_ContentPlaceHolder1_grdProducts_ctl02_ddlSelectSize");
}
I want a generalized way to access above id on a rowcommand event click of a gridview that holds a button.
And onButton click i am calling method onclientClick(return validate());
try this code,will work fine
var grid = document.getElementById(gridID);
var ddl= grid.rows[1].cells[1].getElementsByTagName('input');
You can add a marker css class to you dropdown. Than you can search for all inputs which have this class and attach to click event.
Attached event handler method has the information about sender so that you do not have to hardcode anything.
If you can use jQuery it gets really simple. I can provide you a sample code if you need

Make user Control visible using Javascript

All I want to make user control visible on button click. I am getting object null typical error on following code. How do I make complete user Control visible or invisible using javascript?
Dim ucAddNewChekcing As SubscriberSetupPages_UserControls_CheckingAccount
ucAddNewChekcing = DirectCast(pnlTopLevel.Items().FindItemByValue("pnlAddChecking").FindControl("CheckingAcct1"), SubscriberSetupPages_UserControls_CheckingAccount)
Dim openWinScript As String = "SetVisibility('" & ucAddNewChekcing.ClientID & "');"
btnAddChecking.OnClientClick = openWinScript
Thanks in advance.
have visible="false" set means your control doesn't get rendered at all, so there's no element available when you want to display it. you can address this in a couple ways:
leave the control visible, so it renders, and use css styling to hide it until you want it: style="display: none;" in place of visible="false".
change visible to true and set style="display: none;" on some wrapping element (see edit below).
in your SetVisibility function, you can do
element.style.display = '';
to remove the none value and show the element.
edit: ok after thinking about this some more, we can't put style="display: none;" right in the user control tag because that doesn't map to any specific html element. instead, this needs to be set on an element that wraps the contents of the user control.
if the user control has such an element already, that would be a good place to set the display styling. you can add a method to the control that will return the ClientID for that element so you can reference it in script.otherwise if your layout will tolerate it you can put the control inside an asp:Panel and set the display property there.
the other option is to wrap your control in an UpdatePanel containing some control (like HiddenField) as a flag which will indicate if the control is visible or not. if you go that route you SetVisibility function looks something like
// change value on flag control
hiddenControl.value = '1';
// trigger a partial postback
__doPostBack('UpdatePanel1', '');
and then in your UpdatePanel_Load function you can check the value of your flag control and set the Visible property on your user control accordingly.

Categories