Draw a datatable when document.ready - javascript

Is there a way to automatically dra a datatable, after document.ready?
It means, draw the datatable without make an action such as changing the sorting, filtering or paging?
This how actually I'm doing it, but it just works util I make one of the actions mentioned, and I need to do it whithouth that action. It is possible?
$(document).ready(function(){
var table = $('#dataTable').DataTable();
// Event listener for DT 1.10+
table.on('draw', function() {
$(".auditButton.Submitted").removeClass('btn-outline-primary');
$(".auditButton.Submitted").addClass('btn-outline-success');
$(".auditButton.Expired").addClass('btn-outline-danger');
$(".auditButton.Capturable").addClass('btn-outline-warning');
});
});
Using body.onload
$(document).ready(function(){
$(document).on('load','body *',function(){
$(".auditButton.Submitted").removeClass('btn-outline-primary');
$(".auditButton.Submitted").addClass('btn-outline-success');
$(".auditButton.Expired").addClass('btn-outline-danger');
$(".auditButton.Capturable").addClass('btn-outline-warning');
});
});

Yes you can. At the moment of the load body.
body.onload = function(){myScript};
or onload on other object:
object.onload = function(){myScript};

I gave you an example, I let you adapt it.
$( document ).ready(function() {
$('#test').text('Insert text after on load webpage!');
});
https://jsfiddle.net/NicolasLsn/whvoa7yg/14/

Related

javascript events not working with dynamic content added with json

I'm stuck with a situation where my DOM elements are generated dynamically based on $.getJSON and Javascript functions for this elements are not working. I'll post some general idea on my code because I'm looking just an direction of what should I do in this situation.
site.js contains general features like
$(document).ready(function() {
$('.element').on('click', function() {
$(this).toggleClass('active');
});
$(".slider").slider({
// some slider UI code...
});
});
After that:
$.getJSON('json/questions.json', function (data) {
// generating some DOM elements...
});
I have also tried to wrap all site.js content into function refresh_scripts() and call it after $.getJSON() but nothing seems to be working.
Firstly you need to use a delegated event handler to catch events on dynamically appended elements. Then you can call the .slider() method again within the success handler function to instantiate the plugin on the newly appended content. Try this:
$(document).ready(function(){
$('#parentElement').on('click', '.element', function() {
$(this).toggleClass('active');
});
var sliderOptions = { /* slider options here */ };
$(".slider").slider(sliderOptions);
$.getJSON('json/questions.json', function(data) {
// generating some DOM elements...
$('#parentElement .slider').slider(sliderOptions);
});
});
Instead of calling on directly on the element, call it on a parent that isn't dynamically added and then use the optional selector parameter to narrow it to the element.
$('.parent').on('click', '.element', () => {
// do something
});
The difference between this and:
$('.element').on('click', () => {});
is with $('.element').on(), you're only applying the listener to the elements that are currently in that set. If it's added after, it won't be there.
Applying it to $(.parent), that parent is always there, and will then filter it to all of it's children, regardless when they're added.
the easiest way is to add this after you add/generate your DOM
$('script[src="site.js"]').remove();
$('head').append('<script src="site.js"></script>');
of course your js function that generates DOM needs to be on another file than your site.js

add simple onclick js to rails

I have a simple div in one of my views that I want to click to hide another element on the page. I put this in my application.js But it doesn't do anything. Did I put it in the wrong place?
function toggleNewPostForm {
$('.new-post-btn').hide();
}
Use document ready to make sure document is loaded before selecting an element from HTML and call your function inside
function toggleNewPostForm(){
$('.new-post-btn').hide();
};
$( document ).ready(function() {
toggleNewPostForm();
});
Try something like this
<div class="xyz">Click here!</div>
in javascript
$(".xyz").click(function(){
$('.new-post-btn').hide();
});
Also check if event listener is added after document ready method? i.e
$(function(){
$(".xyz").click(function(){
$('.new-post-btn').hide();
});
});
If this is the only js you have, there will be no click-behaviour. You have to tell the element, that is has to react to a click-event.
Try this in your application.js-file:
function toggleNewPostForm() {
$('.new-post-btn').hide();
}
$(document).on('ready page:load', function(){
$('.new-post-btn').on('click', function(){
toggleNewPostForm();
});
});
P.S.: As RGraham points out, you have to write the parameter-paranthesis if you define a function.
P.P.S.: In ruby on rails, you should check against 'ready' and 'page:load' as document-ready-handlers, because Ruby on Rails uses the "Turbolinks"-library by default.

click event not working on hyperlink ajax data

Jquery Click event on table hyperlink does not work for table data that comes from ajax call, yet it works for static data entered.
Fiddle
$("a").click(function (e) {
var txt = $(e.target).text().replace(/\s/g, "%20");
alert(txt);
});
It is not working because you are adding data dynamically.
Use event delegation.
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.
Write:
$(".table").on("click","a",function (e) {
var txt = $(e.target).text().replace(/\s/g, "%20");
alert(txt);
});
Updated fiddle here.
Refer this document.
use $(document).on("click", "a", function (e) { instead of $("a").click(function (e) {
use on by jquery framework
it will work nice, if you do in such a way
$(document).on("click","selector",function(ev){
$(this)// your stuff..
});
as jquery doesn't bind events to dynamic content, so you need to parse the DOM again to find your element.

Paging and double click with jQuery datatable

After lots of reading posts and fiddling, I thought this was working to attach a doubleclick 'handler' to each row of my jQuery datatable:
$('#myTable').find('tr').dblclick( function(e){
var ref = $(this).find('td:first').text();
someThingToDoWithTextFromFirstCell(ref);
});
Unfortunately, this only seems to work for rows on the first page. I tried doing something like this as a workaround (basically do the same thing when paging):
$('#myTable').on('page', function () {
$('#myTable').find('tr').dblclick( function(e){
var ref = $(this).find('td:first').text();
someThingToDoWithTextFromFirstCell(ref);
});
} );
However, when it fires there are no tr's found so nothing happens. I assume the event is firing before the datatable has new rows?
Does anyone know how I can get this to work?
Here is a JS Fiddle example, Nikola. Thanks for your time. Double click a row and get an alert, click next and double click a row and get no alert.
JS Fiddle example
This is what you can add in for the workaround that doesn't work:
$('#example').on('page', function () {
$('#example').find('tr').dblclick( function(e){
var ref = $(this).find('td:first').text();
alert(ref);
});
} );
You could find answer here.
So, for dynamically created elements you should use:
$(document).on("dblclick", "#myTable tr", function () {
//code here
});

JQuery event handler when select element is loaded

Is there an event handler to use in JQuery when a DOM select element has finished loading?
This is what I want to achieve. It is working with other events except 'load'.
This piece of code is loaded in the head.
$(document).on('load', 'select', function(){
var currentSelectVal = $(this).val();
alert(currentSelectVal);
} );
The question was badly formed earlier. I need to attach the event handler to all select elements, both present when the document is loaded and dynamically created later.
They are loaded from a JQuery Post to a php-page. Similar to this:
$.post("./user_functions.php",
{reason: "get_users", userID: uID})
.done(function(data) { $("#userSelector").html(data);
});
I think we're all confused. But a quick break down of your options.
After an update made to the Question, it looks like the answer you might seek is my last example. Please consider all other information as well though, as it might help you determine a better process for your "End Goal".
First, You have the DOM Load event as pointed out in another answer. This will trigger when the page is finished loading and should always be your first call in HEAD JavaScript. to learn more, please see this API Documentation.
Example
$(document).ready(function () {
alert($('select').val());
})
/* |OR| */
$(function() {
alert($('select').val());
})
Then you have Events you can attach to the Select Element, such as "change", "keyup", "keydown", etc... The usual event bindings are on "change" and "keyup" as these 2 are the most common end events taking action in which the user expects "change". To learn more please read about jQuery's .delegate() (out-dated ver 1.6 and below only), .on(), .change(), and .keyup().
Example
$(document).on('change keyup', 'select', function(e) {
var currentSelectVal = $(this).val();
alert(currentSelectVal);
})
Now delegating the change event to the document is not "necessary", however, it can really save headache down the road. Delegating allow future Elements (stuff not loaded on DOM Load event), that meet the Selector qualifications (exp. 'select', '#elementID', or '.element-class') to automatically have these event methods assigned to them.
However, if you know this is not going to be an issue, then you can use event names as jQuery Element Object Methods with a little shorter code.
Example
$('select').change(function(e) {
var currentSelectVal = $(this).val();
alert(currentSelectVal);
})
On a final note, there is also the "success" and "complete" events that take place during some Ajax call. All jQuery Ajax methods have these 2 events in one way or another. These events allow you to perform action after the Ajax call is complete.
For example, if you wanted to get the value of a select box AFTER and Ajax call was made.
Example
$.ajax({
url: 'http://www.mysite.com/ajax.php',
succuess: function(data) {
alert($("select#MyID").val());
}
})
/* |OR| */
$.post("example.php", function() { alert("success"); })
.done(function() { alert($("select#MyID").val()); })
/* |OR| */
$("#element").load("example.php", function(response, status, xhr) {
alert($("select#MyID").val());
});
More reading:
.ajax()
.get()
.load()
.post()
Something else to keep in mind, all jQuery Ajax methods (like .get, .post) are just shorthand versions of $.ajax({ /* options|callbacks */ })!
Why dont you just use:
$(document).ready(function () {
//Loaded...
});
Or am I missing something?
For your dynamic selects you can put the alert in the callback.
In your .post() callback function, try this:
.done(function(data) {
data = $(data);
alert(data.find("select").val());
});
Ok, correct me if I understand this wrong. So you want to do something with the selects when the document is loaded and also after you get some fresh data via an ajax call. Here is how you could accomplish this.
First do it when the document loads, so,
<script>
//This is the function that does what you want to do with the select lists
function alterSelects(){
//Your code here
}
$(function(){
$("select").each(function(){
alterSelects();
});
});
</script>
Now everytime you have an ajax request the ajaxSend and ajaxComplete functions are called. So, add this after the above:
$(document).ajaxSend(function () {
}).ajaxComplete(function () {
alterSelects();
});
The above code will fire as soon as the request is complete. But I think you probably want to do it after you do something with the results you get back from the ajax call. You'll have to do it in your $.post like this:
$.post("yourLink", "parameters to send", function(result){
// Do your stuff here
alterSelects();
});
Do you want all Selects to be checked when the User-Select is loaded, or just the User-Select?...
$.post("./user_functions.php", {reason: "get_users", userID: uID}).done(function(data) {
$("#userSelector").html(data);
//Then this:
var currentSelectVal = $("#userSelector").val();
alert(currentSelectVal);
});
If your select elements are dynamically loaded, why not add the event handler after you process the response?
e.g. for ajax
$.ajax({
...
success: function(response) {
//do stuff
//add the select elements from response to the DOM
//addMyEventHandlerForNewSelect();
//or
//select the new select elements from response
//add event handling on selected new elements
},
...
});
My solution is a little similar to the posters above but to use the observer (pubsub) pattern. You can google for various pub sub libraries out there or you could use jQuery's custom events. The idea is to subscribe to a topic / custom event and run the function that attach the event. Of course, it will be best to filter out those elements that have been initialize before. I havent test the following codes but hopefully you get the idea.
function attachEventsToSelect(html) {
if (!html) { // html is undefined, we loop through the entire DOM we have currently
$('select').doSomething();
} else {
$(html).find('select').doSomething(); // Only apply to the newly added HTML DOM
}
}
$(window).on('HTML.Inserted', attachEventsToSelect);
// On your ajax call
$.ajax({
success: function(htmlResponse) {
$(window).trigger('HTML.Inserted', htmlResponse);
}
});
// On your DOM ready event
$(function() {
$(window).trigger('HTML.Inserted'); // For the current set of HTML
});

Categories

Resources