This is a goofy question, so sorry about that.
I'm creating html elements dynamically from an ASP.NET server control. After an element is created, or all of the elments are created, is there a way to force an event to fire on one of them? I understand that it's coming from the server to the client, but I'm looking for a way around that. Is there anything in the document that can listen for html being added or anything?
I'm creating the controls like this:
protected override void RenderContents(HtmlTextWriter output)
{
// htmlString is a dynamically built string of html
output.Write(htmlString);
}
The elements are a series of cascading drop-downs of which the user has the ability to save the selected value. So, if I select the value of the item when I create it, there's no way to kick off the event, which calls out to the database for data to fill its dependent control. There's a "no postbacks" rule here (not my rule).
Any help would be appreciated.
You can output javascript as part of the rendering and bind events to the dynamically created controls.
jQuery makes binding events very easy.
If you want, fire a Function() from RegisterClientScriptBlock()
Example useage:
ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", false);
Or you can set up a live event on click etc on those new items.
$(document).on('click', '#exampleThing', function () {
// what you want to do
});
Related
How can I get the control ID of a asp.net control while mouseover on a control dynamically. For example, I've page called "Default.aspx" which has 5 text boxes, two check boxes, 2 radio buttons. So, when I mouseover a specific control I should be able to get the currently hovered controls ID using javascript or jquery. I dont want to write code for every control, instead the javascript should be able to detect the mouseover event when the mouse is moved over any control and in the backend the controld ID should be returned.
Any solution ?
$("input").mouseenter(function(e){
e.stopPropagation();
$id=$(this).attr("id");
});
this will return the id of input control currently being hovered
I chuckle a bit when jQuery developers use jQuery in their handler function when it's the long way to get the answer. Here's a shorter/faster way:
$("input").mouseenter(function(e){
var id = this.id;
// do whatever you want with the id here
});
If you're truly trying to pass this to your back-end web server (a part of your question that was not clear to me), then you will need to initiate communications to the web server either using a posted form or an ajax call.
This might not be the best practices way, but I would set the onmouseover event to trigger a function that sets the value of a hidden field. In your JQuery read the value of that field and you will know which one they did the mouseover on...
$("input").hover(function(){
// hover on
var theId = $(this).attr("id");
if(theId) {
// do something
}
else {
// no id found
}
},
function(){
// hover off
});
I suppose you won't need to check if an id exists since it's a .NET control though
So far I've created a table from a database query using the input from a dropdown menu. Now I want the user to be able to click on a cell in that table and using the the value of that cell query the database again for further information. Here's what I have:
echo "
<tr>
<td>".$value['Time']."</td>
<td>".$value['First_Name']."</div></td>
...
This continues on for the rest of the information but thats the code for my initial table. The user should then click on First_Name for further information provided by an AJAX request. My jQuery so far looks like this...I haven't even been able to start the AJAX as I can't pass in the value of the table cell.
$(document).ready(function(){
$('#tables').on('click','td', function(){
var module= $(this).val();
alert(module);
})
Once I figure out how to pass this value then I can move ahead with the database query but this is holding me back. Do I even need to do this if Im using JQuery AJAX? Any help is appreciated.
if you want get the text inside the element tag. Please use .text() not .val()
example:
var module= $(this).text();
I hope this usefull :)
It would be better to bind click event on <a> instead of <td>. That will work good too.
Now question is you want to pass some value through AJAX to PHP script. Good practice to do this is by setting data-* attributes to <a> element.
So your HTML/PHP code will look something like this,
<td>".$value['Time']."</td>
<td>".$value['First_Name']."</div></td>
In above code we've given a class to <a> to bind click event on each element having this class. (Useful for multiple records generated using loop), we have also set data-modelvalue attribute to <a>.
Now update your jQuery code like this,
$('#tables').on('click','.myLink', function(e){
e.preventDefault();
var module= $(this).data('modelvalue');
alert(module);
});
In above code we have bind click event on myLink class elements. Also we're fetching data-modelvalue using .data() jQuery method.
e.preventDefault() forces default action of the event to not be triggered, in our case page won't get refreshed(which is default action of any hyperlink).
References:
https://developer.mozilla.org/en/docs/Web/Guide/HTML/Using_data_attributes
https://api.jquery.com/data/
https://api.jquery.com/event.preventdefault/
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);
I'm not a newb to JavaScript but this is my first foray into Acrobat Scripting.
What I'm trying to do is change a text field based on the value selected in a comboBox.
Since I have many different comboboxes with the same set of options, and many text fields that are supposed to be bound to those, I would prefer a document scope function that could be reused for all of those.
I'm not sure if this is possible but here's what I'm thinking...
Detect when a combo box is changed. On the change event submission, take the export value from that and make it the value for the related text field.
Here's the steps:
capture combo box onmouseup event
detect which combo box triggered the event
match up the name of the combo box to its associated text field using an array listing
use a getField() to fetch the text field
set the text fields value to be the export value of the combo box
Any help with this would be appreciated. Especially good sources about Acrobat event triggers and how they work. I have been through a great deal of the API documentation and can't find anything on it.
Found it!
After exhaustive hours/days of Googling I finally found a solution that works.
The handler function needs to be bound to the 'Keystroke' event.
The handler function should contain:
if(!event.willCommit) {
this.getField('[field]').value = event.change;
}
Note: Where 'field' is the name of the field being updated and event.change is the value selected in the combobox.
To fetch the export value of the selection use the following:
if(!event.willCommit) {
this.getField('[field]').value = event.changeEx;
}
Apparently, 'Keystroke' is fired any time a UI element is interacted with. If you don't want it to execute when the document loads, be sure to bind the handler function to the event during the page load event.
Thoughts: AcroForms JS (Javascript for Acrobat) has a seriously broken event model. If you were to get the value of the combobox while using this even handler it would serve up a stale value. Not only does it take an obscure hack to make it work but there is little/no AcroForms JS community to provide answers to hard questions like these.
I have a page dynamically generated with javascript and it contains several input fields and a button. When I click the button, nothing happens...Is it because it is a javascript object and not a "real" dom object? If so, is there a way to interact with the object?
I just wrote a simple alert to see if the button is even working.
jQuery("#button").click(function() {
alert("yes it's working");
});
On first page load this works...I believe on first page load it is PHP generated and when I click to another section, this same button will show up BUT the page does not refresh so this leads me to believe when I click on to another section, it is dynamically re-generated with JS.
Now if I click the button, nothing happens...no errors or no alerts...
You need to use .live because at the point in time when you assign the handler the element doesn't exist.
$('#button').live('click', function() {
});
You should also look into delegate if you're doing this with multiple elements for efficiency purposes.
I think I get what you're saying.
When you run jQuery('#button'), it searches for the elements then and there. The event is attached to the button itself, not to the query string #button.
jQuery does, however, offer the behavior you want.
jQuery('#button').live('click', function () { /* on click event */ });
live attaches to the query string, not the elements, so it will apply to any #button ever generated in the future.