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.
Related
I am using datatables to dynamically create input fields. Each input field has a unique ID.
I need to run a function once the entire page has been loaded and all elements have been rendered.
The function should update the values of all the dynamically created inputs.
Using document.onload does not seem to work. It works sometimes and sometimes doesn't.
I have tried using document.onload. It works like 20% of the time. I can't seem to understand why. document.onload should call the function after document.ready has been fully executed. But the values of dynamically created inputs don't change.
$(window).on('load', function(){
refresh_all_equity_credit_values();
});
$('#dynamic_input_id').val('2'); // Does not work
The values of dynmically created inputs should be updated once the entire page has been loaded and all elements has been rendered.
If you're using the datatables library, you'll likely want to wait until you're certain it has finished rendering the inputs before you attempt to update them. Check out their documentation on available events
You'll likely want to use the draw event:
$(window).on('load', function() {
$('#yourDataTable').on('draw', function() {
refresh_all_equity_credit_values()
})
})
I'm attempting to implement an experiment in Qualtrics, but I've run up against this wall.
A button appended to a qualtrics question using JQuery will refresh the page, regardless of whether or not .click or .event have been defined. In my design this has the effect of wiping all the responses a participant has given up until that point, which is probably the last thing I want to happen.
My code is too complicated (a.k.a. poorly written) to post here. However you can replicate the error by creating a new survey consisting of a single 'descriptive text' question and attaching this code. Here jq refers to Jquery
Qualtrics.SurveyEngine.addOnload(function(){
/*Place Your Javascript Below This Line*/
jq('.QuestionBody').append('<button>This shouldn\'t do anything</button>')
});
This link is an example of the above.
https://sydneypsy.qualtrics.com/SE/?SID=SV_1ZGMxfENT0ykxBr
Why does this happen? Does anyone know to prevent it?
Source: robbrit
This is the default behaviour of a button. If you want to change it, do something like this:
$("button selector").click( function(event) {
event.preventDefault();
});
In your case, I would give the button an ID to use for a selector.
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
});
I want to disable/enable a button with JavaScript. Because the JavaScript is called, after a Flash animation is rendered, the button exists at the time of the execution.
The button is in a hierarchy:
<html><body><form#form1><div#control><asp:Button#Export1>
I tried for hours to get a reference to that button, but nothing seems to work:
document.getElementById("Export1")
// and
document.getElementbyId("form1").getElementById("control").getElementById("Export1")
// and many more
How to get a reference to that button (in order to change btnref.disabled = true)?
Thanks a lot for your help!
Have you tried right-clicking in the document and selecting "view source" to see how that code actually renders? An asp:Button is a server control, that gets translated to an input field during render. During this, the ID of the field will not be exactly what you set it to in your aspx.
You can use Export1.ClientID at serverside to get the ID of the control.
If it's the only button in your div, this should work:
var btnref = document.getElementById("controls").getElementsByTagName("button")[0];
Usually the id of the button won't stay the same in the page source. Click on view source in the HTML and look for that tag to find the new id. You can then use that id in something like:
document.getElementbyId("Export1_some_unique_id")...
Newbie question...
The objective:
I intend to have an HTML text input field as a kind of command line input.
An unordered HTML list shows the 5 most recent commands. Clicking on one of the last commands in this list should populate the command line input text field with the respective command (in order to re-execute or modify it).
An unordered HTML list contains a result set. Clicking on an ID in this list should bring the respective ID into the command line input text field.
In HTML (DHTML):
Works as expected: when clicking on the the link the command line input text field is populated with a recent command.
<li>here would be one of the recent commands</li>
In Javascript file:
Doesn't work as expected: when clicking on the the link the command-line-input-text-field gets populated with the respective value (as it should), BUT then it seems like the full HTML page is being reloaded, the text input field and all dynamically populated lists become empty.
function exec_cmd(cli_input_str) {
// a lot of code ...
// the code that should provide similar behavior as onclick=... in the DHTML example
$('.spa_id_href').click(function(){document.getElementById('cli_input').value = document.getElementById('cli_input').value + this.firstChild.nodeValue;});
}
Now the Question:
Besides a potential Javascript (syntax) error, what could cause the browser to reload the page?
In both cases, you do nothing to cancel the default function of clicking on a link.
In the plain HTML example, the link to the top of the page is followed.
You don't specify what the href attribute for the second example looks like, but whatever it is, it will be followed.
See http://icant.co.uk/articles/pragmatic-progressive-enhancement/ for a good explanation of event cancelling and good event design. See http://docs.jquery.com/Tutorials:How_jQuery_Works for some jQuery specific guidance.
Change
$('.spa_id_href').click(function(){...
to
$('.spa_id_href').click(function(evt){...//notice the evt param
and in the function, call
evt.preventDefault();
It seems that you just follow the link target URL. That is because you do not prevent the default click action:
e.preventDefault(); // `e` is the object passed to the event handler
// or
return false
Alternatively, you can set up a href starting with #, or not use <a> element at all (use <span style="cursor:pointer"> instead) β if itβs not a real link of course.
It's basically related to event cancelling...
Try this:
try { (
e || window.event).preventDefault();
}
catch( ex )
{
/* do Nothing */
}
While the other answers here make excellent points about canceling events, you will still run into problems if your JavaScript contains errors which prevent your event-canceling code from being run. (As might be the case if you're, say, debugging your code.
As an additional precaution, I strongly recommend you not use href="#" on links which only trigger scripts. Instead, use the void operator:
...
The reason for this is: when the event is not canceled, the browser will attempt to load the URL supplied by the href attribute. The javascript: "protocol" tells the browser to instead use the value of the accompanying code unless that value is undefined. The void operator exists explicitly to return undefined, so the browser stays on the existing page β with no reload/refresh β allowing you to continue debugging your script.
This also allows you to skip the entire event-canceling mess for JS-only links (though you will still need to cancel events in code attached to links which have a "fallback" URL for non-JS clients).