Unable to select element paragraph using jquery - javascript

<html>
<head>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
function func(){
var s = "<p id=" + id +">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>";
document.getElementById("stat").innerHTML+=s;
}
</script>
</head>
<body>
//call function func
<pre id="stat" > </pre>
</body>
</html>
Guys the function func is supposed to create a paragraph with id as "id " and the content as a message inside the tag with id as "stat " .. it works fine
But i cant use the 'Jquery' selector to use the click function on tag :/ !
the reason i am inserting inside in is i need the interpreter to consider "\n" as a new line.
Why is that , not working ?
and is there any other way to do it ?

Try this,
$(document).ready(function(){
$(document).on('click','p',function(){
$(this).hide();
});
});

$(document).on('click', 'p', function() { $(this).hide();})
The code you wrote is not working because the p element is not present when the document is loaded. Since the p element is dynamically added, you have to attach the event to the document object

the fastest way will be to change
var s = "<p id=" + id +">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>";
to
var s = "<p id=" + id +" onclick=\"$(this).hide()\">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>";
and delete this
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});

This may help:
$('body').on('click', 'p', function(){
$(this).hide();
});

use .on() instead
$(document).on('click', 'p', function(){
$(this).hide();
});
.on() has to ability to add a click handler to elements that are created dynamically , like your <p> tags are

Attach the click event handler inside func:
function func(){
var s = "<p id=" + id +">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>";
document.getElementById("stat").innerHTML+=s;
$("#" + id).click(function(){
$(this).hide();
});
}
Or better still:
function func(){
var s = $("<p id=" + id +">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>");
$("#stat").append(s);
s.click(function(){
$(this).hide();
});
}

Related

JavaScript button event handler not working

I am learning javascipt and now i have a piece of code but i am unable to get this to work, javascript isn't executed. I have already searched the web but i can't find an answer. Maybe you guys can help me with this.
HTML
<html>
<head>
<title>Text Game</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<button><span id="click">0</span></button>
</body>
</html>
Javascript
// Variables
var waarde = {
amount:2
};
$(document).ready(function() {
updateValues();
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
$('#click').click(function() {
waarde.amount = waarde.amount + 1;
updateValues();
});
You have a couple of issues here:
Issue #1:
The element does not exist in the DOM to bind to yet, so do any or all of the following:
Move your script tag to the footer, right before the closing </body> tag (generally best practice anyway).
Use event delegation to bind to events on future elements.
Put all the JavaScript in the ready handler.
Issue #2:
You should not bind a click event handler on an element inside a button, it will not work in specification compliant browsers as the button consumes the event, and it not propagated to children.
See the HTML5 spec for button for reference:
Content model:
Phrasing content, but there must be no interactive content descendant.
Instead, bind the click event handler to the button itself.
// Variables
var waarde = {
amount: 2
};
$(document).ready(function(){
updateValues();
});
function updateValues(){
document.getElementById("click").innerHTML = waarde.amount;
}
// Binding to the button element using event delegation.
$(document).on('#button').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button"><span id="click">0</span></button>
Also, unless you need the span element for something else, you could get rid of it and just use:
document.getElementById("button").innerHTML = waarde.amount;
You should put this code:
$('#click').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
Inside of $(document).ready(function(){}) function. $('#click') isn't in the DOM yet..
You have to write "Click" event in document.ready
var waarde = {
amount: 2
};
$(document).ready(function () {
$('#click').click(function () {
waarde.amount = waarde.amount + 1;
updateValues();
});
updateValues();
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
The problem with your code is you are not assigning an event handler when javascript loads the js file. It should be called in the ready function.
var waarde = {
amount:2
};
$(document).ready(function(){
$('#click').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
});
function updateValues(){
document.getElementById("click").innerHTML = waarde.amount;
}
You should wrap it inside the ready method!
// Variables
var waarde = {
amount:2
};
$(document).ready(function() {
$('#click').click(function() {
waarde.amount = waarde.amount + 1;
updateValues();
});
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
Here's a codepen link http://codepen.io/anon/pen/vKXQza
Two points:
You should put your jQuery event listener inside the document.ready.
There is no guarantee to work click event on span.
// Variables
var waarde = {
amount:2
};
$(document).ready(function(){
updateValues();
$('#click2').click(function(){
waarde.amount++;
updateValues();
});
});
function updateValues(){
document.getElementById("click2").innerHTML = waarde.amount;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<button id="click2">0</button>
You can see your problem solution is here
You are missing button click event in $(document).ready(function(){}(;

jQuery trigger click after insertBefore

I'm trying to figure out how to trigger click event right after insertBefore
$this = $(this);
var changeImageHTML = '<div class="sample1 sample2"> </div>';
//attempt 1
$(changeImageHTML).insertBefore($this).trigger('click');
//attempt 2
$(changeImageHTML).insertBefore($this).find('.sample2').trigger('click');
//attempt 3
$(changeImageHTML).insertBefore($this).find('.sample1.sample2').trigger('click');
//attempt 4
$(changeImageHTML).insertBefore($this).bind('click').trigger('click');
.sample2 --> a class of a particular plugin I'm trying to trigger.
Version: jQuery 2.1
Thanks for your help. :)
give a try , you need to give a click handler to target element, in your case click event is called but handler is missing so event is lost.
$(document).ready(function(){
$this = $("div.container");
var changeImageHTML = "<div class='sample1 sample2' onclick='test()'>test</div>";
$(changeImageHTML).insertBefore($this).click()
})
function test(){
alert("ok")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">Container</div>
Use event delegation
$(document).on("click", ".sample1.sample2", function() {
alert("clicked")
})
var changeImageHTML = '<div class="sample1 sample2"> sample</div>';
var $this = $("div");
$(changeImageHTML).insertBefore($this).trigger('click');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>div</div>

Append input box with JQuery

I was trying to add text into field with id #shouttext, but i need to trim value from onclick event which is just after (' and also delete ') symbols.
So if i have
<img src="images/smilies/at.png" alt="" title="" class="smilie smilie_9 smilie_pointer" onclick="MyBBEditor.insertText(':at:');">
I want to get
:at:
and add it to input with #shouttext id. Below is my code, which doesn't work - and i think its blocked by defined onclick value, which i was trying to remove.
<script type="text/javascript">
$( document ).ready(function() {
$('.smilie').click(function()
{
var s1,s1;
s1=attr("onclick");
s1=s1.replace('MyBBEditor.insertText(\'', '');
s2=s1.replace('\')', '');
$('.smilie').attr('onclick','').unbind('click')
$('#shouttext').val($('#shouttext').val()+s2);
})
});
</script>
Thanks for any help in advance!
you could try also:
var str = $(".smilie").attr("onclick").split("'")[1];
to get the :at: try it here: fiddle
now you can use it here:
$('.smilie').unbind("click");
$('.smilie').click(function() {
var str = $(".smilie").attr("onclick").split("'")[1];
$('#shouttext').val($('#shouttext').val() + "" + str);
});
or how #eg_dac says, you can override the click event with $.on()
instead of unbinding it in the click, you can do
$(".smilie").attr("onclick", ""); // clear the already declared attribute.
$(".smilie").on("click", function(){
$('#shouttext').val($('#shouttext').val()+s2);
});
Example found here http://jsfiddle.net/meougz1L/
$("img").attr("onclick","");
$("img").on("click", function(){
alert("click event overridden");
});

Read id with jquery and apply action to corresponding div

I want a certain button to show a certain div. Now I need to update my javascript for every new button & div. As this will be connected to a cms, for every post it needs to work automatically. How can I read the id/class from the button dynamically to apply an action to the corresponding div?
Way of thinking:
button_xxx opens div with id xxx
button_xxx_close closes it
Here's the html:
Button 001
Button 002
...
Button 099
<div id="001">
<p>CLOSE</p>
<p>Content</p>
</div>
<div id="002">
<p>CLOSE</p>
<p>Content</p>
</div>
<div id="099">
<p>CLOSE</p>
<p>Content</p>
</div>
And the javascript:
$(document).ready(function() {
// SHOWS DIV
$('#button_001').on('click', function(){
$('#001').removeClass('movedown');
$('#001').addClass('moveup');
});
$('#button_002').on('click', function(){
$('#002').removeClass('movedown');
$('#002').addClass('moveup');
});
$('#button_099').on('click', function(){
$('#099').removeClass('movedown');
$('#099').addClass('moveup');
});
// HIDES DIV
$('.button_001_close').on('click', function(){
$('#001').removeClass('moveup');
$('#001').addClass('movedown');
});
$('.button_002_close').on('click', function(){
$('#002').removeClass('moveup');
$('#002').addClass('movedown');
});
$('.button_099_close').on('click', function(){
$('#099').removeClass('moveup');
$('#099').addClass('movedown');
});
});
You can reduce your code using startswith attribute selector in jquery
$("a[id^=button_]").click(function () {
var id = this.id.split("_")[1];
$("#" + id).removeClass("movedown").addClass("mouseup");
});
$('[class^=button_]').on('click', function () {
var id = $(this).attr("class").split("_")[1];
$("#" + id).removeClass("mouseup").addClass("movedown");
});
First snippet will select all anchor elemets with id starts with button_ and bind click event to them.
Second snippet will select all elemets with class starts with button_ and bind click event to them.
Note
If your elements are created dynamically, use the below code
$(document).on("click", "a[id^=button_]", function () {
var id = this.id.split("_")[1];
$("#" + id).removeClass("movedown").addClass("mouseup");
});
$(document).on('click', '[class^=button_]', function () {
var id = $(this).attr("class").split("_")[1];
$("#" + id).removeClass("mouseup").addClass("movedown");
});
Edit
$('[class^=button_]').on('click', function () {
// var id = this.id.split("_")[1]; <-- changedd this line
var id = $(this).attr("class").split("_")[1];
$("#" + id).removeClass("mouseup").addClass("movedown");
});
I changed the line, Because that element doesnt have id. So you should pick the classname instead.
You can use $(this).attr("class") to get the current element's class name. Then split the classname to extract the div id
Simply with toggleClass
$("a[id^=button_] , [class^=button_]").click(function () {
var id = this.id.split("_")[1];
$("#" + id).toggleClass("movedown mouseup");
});
Try with this:
$(document).ready(function() {
// SHOWS DIV
var elem = '';
$('a[id*="button_"]').on('click', function(){
elem = this.id.split('_')[1];
$('#'+elem).toggleClass('movedown moveup');
});
// HIDES DIV
$('.button_'+elem+'_close').on('click', function(){
$('#'+elem).toggleClass('movedown moveup');
});
});
You could do this without the need for regular expressions with a small change to your html
Button 001
<div id="001">
<p>CLOSE</p>
<p>Content</p>
</div>
and then add click handlers for both
$('.button_open_div').on('click', function(ev){
$('#'+$(this).data('divid')).removeClass('movedown').addClass('moveup');
});
$('.button_close_div').on('click', function(){
$('#'+$(this).data('divid')).removeClass('moveup').addClass('movedown');
});
or a toggle function
$('.button_open_div, .button_close_div').on('click', function(ev){
$('#'+$(this).data('divid')).toggleClass('movedown moveup');
});
example: http://jsfiddle.net/XXE2R/

focusout event not working for dynamically generated textbox

//<![CDATA[
$(window).load(function() {
$('.n_val').focusout(function() {
alert(this.id);
});
});//]]>
To generate textbox dynamically
buffer += "<tr><td>" + nomen_list.getName() + "</td><td><input type='text' style='width:50px' class='n_val' id=" + nomen_list.getId() + "-" + nomen_list.getCat() + " value=" + nomen_list.getVal() + " /></td></tr>";
I getting dynamically textbox, but focusout is not working for dynamically generated textbox, whereas same page has some textbox, which is hard-coded for that, above script gets triggered.
$(window).load(function() {
$(document).on('focusout','.n_val',function() {
alert(this.id);
});
});
Instead of using document you could use the text box's closest parent id or class. I have no idea of your html layout, hence using document. Also see jQuery on.
$(document).on("focusout", ".n_val", function(){
alert("hi");
});
Try this:
$(document).ready(function() {
$(document).on('focusout','.n_val', function() {
alert(this.id);
});
});
$(document).on('focusout', '#randmSubstationTable tbody tr td', function () {
$('#randmSubstationTable tbody tr td')
.focusout(function(){
$(this).parent().parent().children().index($(this).parent());
});
});
You should call focusout AFTER every textbox is added to the DOM. Here you are probably calling it too soon (at load event, which probably occurs before you add the dynamic textboxes)

Categories