Simple onclick in a row using jquery - javascript

I just cant figure out what i am doing wrong in the code below:
<table width='100%'>
<script>$("#101m").on("click", function() {alert($( this ).text());});</script>
<tr id='101m'><td class='dayavailible'>A</td></tr>
<script>$("#101a").on("click", function() {alert($( this ).text());});</script>
<tr id='101a'><td class='dayavailible'>A</td></tr>
<script>$("#101e").on("click", function() {alert($( this ).text());});</script>
<tr id='101e'><td class='dayavailible'>A</td></tr>
</table>
Any help will be much appreciated.

Your onclick event couldn't bind to all the rows as at the time when script occurs there is no element present in HTML, so either move your JavaScript code after html or use $(function(){ ... }); DOM Ready.
Though what I would suggest you is to use modular code so that you don't have to write the same code again and again.
<script>
// DOM Ready
$(function(){
$("[id*='101']").on("click", function() {
alert($( this ).text());
});
});
</script>

Your script is executed before the DOM is loaded so the element doesn't exist yet, and the jQuery selector doesn't match anything, so no elements get a click handler bound to them. You need to call the init() method with in $(document).ready().
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
$(document).ready(function() {
$("#101a").on("click", function() {
alert($( this ).text());
});
});
OR, move your script to the end of page before </body> tag.

Related

Issue with jQuery .on() function on DOM created elements

In my web application I use .on() from jQuery to bind click event to a specific li elements in a dynamic multilevel menu created by an AJAX call and passed to the DOM.
$(".dl-menu li:not(:has(li)):not(.dl-back)").on("click", function(){
// My Code...
});
Obviously I put this code behind all the dependencies (jQuery in this case), but I does not work, the code is not being executed.
Only works if I open Firebug and paste the code in it.
I also have tried this:
$(document).ready(function() {
$(".dl-menu li:not(:has(li)):not(.dl-back)").on("click", function(){
// My Code...
});
});
But it does not work too.
What I'm doing wrong?
EDIT: To add more details:
HTML structure:
<div id='tab2' class='col s12'>
<div class='section no-pad-bot' id='index-banner'>
<br><br>
<h2 class='header center green-text'>MENU</h2>
<div id='prodcontainer'>
<div id='dl-menu' class='dl-menuwrapper'></div>
</div>
</div>
</div>
AJAX: (the important parte - the code inside success
$(".dl-menuwrapper").html("<button class='dl-trigger' style='visibility:hidden;'></button>"+json.html.replace('dl-submenu', 'dl-menu dl-menuopen'));
$('#dl-menu').dlmenu();
The json.html contains the string with the HTML to being added to the DOM. Like this:
json.html='<ul class="dl-submenu"><li data-id="17">A<ul class="dl-submenu"><li data-id="18">B<ul class="dl-submenu"><li data-id="20">C</li><li data-id="21">D</li></ul></li><li data-id="19">E</li></ul></li></ul>'
Using .on() this way only binds elements that are currently in the DOM.
Because you load the menu through AJAX, it is not available when this code is executed.
The best workaround is to select a wrapper and specify a selector:
$(".dl-menu").on("click", "li:not(:has(li)):not(.dl-back)", function(){
});
Providing .dl-menu exists in the HTML that you do not create once the document is loaded.
EDIT - Alternative
Place the code setting up the event listener after the menu is loaded.
You should use .on('click'....) on an element that's already present. So you will need to use the code like:
$(document).ready(function() {
$(".dl-menuwrapper").on("click", ".dl-menu li:not(:has(li)):not(.dl-back)", function(){
// My Code...
});
});
Or alternatively,
$(document).on("click", ".dl-menu li:not(:has(li)):not(.dl-back)", function(){
// My Code...
});

Jquery script inside the loaded layer is not working

I have following code snippet in jquery when we click on layer 62 which loads a layer "loaded-page" from a page test.html as follows.
<script>
$(document).ready(function(){
$('#62').on('click', function(e) {
$("#62" ).load( "test.html #loaded-page" );
});
$('#loaded-page').on('click', function(e) {
alert('test');
});
});
</script>
<div id="62">Layer62</div>
Test page coding
<div id="loaded-page">Loaded page</div>
MY issue is when we click on layer loaded-page inside DOM, the alert test is not functioning. Can anybody suggest a solution for this ? If needed I can prepare a fiddle for this
This already has an answer, but essentially what you are looking for is event delegation
When you bind the event in your code, that element doesn't exist yet.
So, you bind the event differently, so that it will respond to dynamically added content:
$(document).on('click', '#loaded-page', function(e) {
alert('test');
});
NOTE: Without knowing your html structure, I can't provide the best solution, but I CAN tell you that you do not want to use document if possible. Instead, you should use the nearest parent that exists when the DOM is initially loaded. In your case, my guess is that this would work:
$('#62').on('click', '#loaded-page', function(e) {
alert('test');
});
because that when you bind the
$('#loaded-page').on('click', function(e) {
alert('test');
});
maybe that the #loaded-page element is not be loaded into the document,so can't find it
the better way is :
$(document).delegate('#loaded-page','click',function(){
alert('ok')
})

jQuery bind event on element fails

We are using jQuery 2.1.4 and have written out own JavaScript class that should take care of the event. It is a very simple "application". All it does is taking care of submitting a form. Before that, it processes the data.
Our initial method that we call on rendering the page:
OWebForm.prototype.init = function(){
console.log("init Method called");
...
$("#submit_message").on("click", this._submit);
console.log($("#submit_message"));
...
}
OWebForm.prototype._submit = function(e){
e.preventDefault();
console.log("_submit Method called");
...
}
Once the button "#submit_message" is clicked, it is supposed to call the _submit method of the OWebForm class. When looking at the element within the console I can see that it is not bound to anything, when the page is loaded. Hence the code is not executed once the button is clicked.
In the HTML I have the following code:
<script type="text/Javascript">
var _oWebForm = new OWebForm("0bcfwqx23xv02dfaqfujdqyafziic4b07uxkkg1y6lkof7x0px0vjm2tpaik2l2rmlrhnjya0bvctnpq26dqcom1ij5zpibodke3rs1z4f2syllthtj0kpl3p4vrw0vw");
_oWebForm.init();
</script>
From the documentation I understood, that the function has to exist before it is bound to an element event. Is this not the case when working with objects? How would I fix this?
Your script is executed before the DOM is loaded so the element doesn't exist yet, and the jQuery selector doesn't match anything, so no elements get a click handler bound to them. You need to call the init() method with in $(document).ready().
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
$(document).ready(function() {
var _oWebForm = new OWebForm("0bcfwqx23xv02dfaqfujdqyafziic4b07uxkkg1y6lkof7x0px0vjm2tpaik2l2rmlrhnjya0bvctnpq26dqcom1ij5zpibodke3rs1z4f2syllthtj0kpl3p4vrw0vw");
_oWebForm.init();
});
This works for me:
var OWebForm = function(a){
};
OWebForm.prototype.init = function() {
alert("init Method called");
$("#submit_message").on("click", this._submit);
}
OWebForm.prototype._submit = function(e){
e.preventDefault();
alert("_submit Method called");
}
$(function() {
var _oWebForm = new OWebForm("0bcfwqx23xv02dfaqfujdqyafziic4b07uxkkg1y6lkof7x0px0vjm2tpaik2l2rmlrhnjya0bvctnpq26dqcom1ij5zpibodke3rs1z4f2syllthtj0kpl3p4vrw0vw");
_oWebForm.init();
});
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<form id="myFrm">
<input type="text">
<input id="submit_message" type="submit" value="Click me To test">
</form>
You need to substitute:
$("#submit_message").on("click", this._submit);
with:
$(document).on("click", "#submit_message", this._submit);
If the submit_message is not already loaded!

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.

jquery hover() not firing

I have a ASP.NET user control with the below markup:
<div>
<script id="myTemplate" type="text/x-jquery-tmpl">
<table id="t1"><tr>...<td class="myclass"><span>First Name:</span></td>...<\tr> <\table>
</script>
<table id="t2"><tr>...<td class="myclass"><span>First Name:</span></td>...<\tr> <\table>
<\div>
I want to fire the hover() for all classes with class="myClass". I have placed the below code:
$(document).ready(function() {
$(".myClass").hover(
function() {
alert('in...');
},
function() {
alert('out...');
});
}
The problem is .hover() fires for td element in table "t2" but not for "t1". Can anyone please help?
.hover adds the event handler statically.
Try doing
$(".myClass").live("hover",
function() {
alert('in...');alert('out...');
}
}
"t1" is within a jQuery template. I guess this template has not been inserted into the DOM when your ready-function gets executed. Therefore it's not there and no event is attached. You have two possibilities: either you fire your function after the template has been inserted or you use the "delegate"-function of jQuery which binds an event to all existing and future elements.
maybe because the HTML for t1 is in script tags? Or is that how jQuery templates work?

Categories

Resources