jQuery .on click event does not occur - javascript

Hi and thanks for reading. I've been trying to avoid using HTML onclick="__" references and instead putting these events in my .js file. After reading about jQuery's .click() and then .on() events, I tried to use this in my code for a button.
edit In my haste to make up a <p> that didn't have the rest of the contents, I entered "name" instead of "id". Many answers have recommended I either switch to a p[name=p+ or #p+ reference, but my main problem has been that I can't even hit the alert before the reference to the id/name. Thanks again for your answers.
HTML:
<p name="pBananas"> junk </p>
<button class="deleter" id="dBananas" name="Bananas">Delete</button>
JS:
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
$("p" + $(this).attr("name")).remove();
});
});
The above code won't even get to the alert when I click the button. I've also tried referring to the button by name and ID, and going by $(document).ready($('.deleter')___.
I tried using the $(handler) format as well to have the click event be set after the document is ready. Neither way seems to work. At this point, I resorted to onclick="deleteButton()" and have a deleteButton() function in my .js file, but the function won't detect $(this) and just deletes all <p> tags.
The rest of my javascript is working. I haven't tried including this .on() at the bottom of the HTML, but I'm trying to avoid scripts in my HTML as well. For completeness' sake, I've been testing on both Chrome and Firefox, using a .jsp file to render the HTML.
Thanks again.
Edits
here's how I'm referencing my jquery and js, directly copy-pasted.
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="javascript/index.js"></script>
</head>
here is how my html looks leading up to the div where the is inserted:
<body>
<div id="wrapper">
<div id="header">Card Draw Probability Calculator</div>
<div id="main">
<div id="cardList">
<fieldset>
<legend> Select cards for probability calculation</legend>
<div id="innerCardList"></div>
Here is how the <p> is generated:
function newestCardListLineMaker() {
var $newLine = $('<p id="newestPara"><input type="checkbox" name="new" value="none"/> <input class="cardText" type="text" maxlength="30" name="newestCard" /> Quantity <input type="text" maxlength="1" class="quantityText" name="newestQuant" /><button class="deleter" id="newestDelete">Delete</button><br/></p>');
$("#innerCardList").append($newLine);
On another note, which I should have seen before as significant: the HTML that the .click or .on(click, handler) is referencing has been created by another js function.

Try using .on() function, so your code would be:
$(document).ready({
$('.deleter').on('click', function(){
//do stuff here
});
});
Even better would be this:
$(document).ready({
$('div_above_.deleter').on('click', '.deleter', function(){
// do stuff here
});
});
Hope this helps you.

I have modify your javascript code check it.
$('.deleter').click(function() {
alert('click function works');
var p="p"+$(this).attr("name");
$('p[name='+p+']').remove();
});

working demo
<p id="pBananas"> junk </p>
<button class="deleter" id="dBananas" name="Bananas">Delete</button>​
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
$("#p" + $(this).attr("name")).hide();
});
});​
Edited Jsfiddle

For me it works. Didn't delete the Paragraph element though so your code should look like this instead:
<p id="pBananas"> junk </p>
<button class="deleter" id="dBananas" name="Bananas">Delete</button>
and
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
$("#p" + $(this).attr("name")).remove();
});
});

$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
//alert($(this).attr("name"));
$("p[name=p" + $(this).attr("name") + "]").remove();
});
});​

The final code I used to complete the .on('click') event was:
$(document).ready(function() {
$("div#innerCardList").on("click", "button.deleter", function() {
var paraName = $(this).closest("p").attr("id");
$("#" + paraName).remove();
});
});
The HTML elements which I wanted to assign click events to were generated after the page was already loaded. I needed to delegate the events to the containing div.
Thanks for all the help and different perspectives!

Related

How to write content within tags of a html element JavaScript

So I am thinking something similar to how you in php can just run a function within a html element and that way get it to echo something in the html element.
Is there a way to choose a specific place for javascript to write with for example .innerHTML or .createTextNode?
What I wanna do is to add contenteditable="true" within a html element onclick of another button.
The reason I wanna do this is because I have a paragraph that should become editable only after onclick of a button.
I apologize that I haven't put in any code for an example, but I don't really think that is needed, as it would only be a paragraph and a button, as I don't know how the javascript should be written.
With a simple js onclick event you can do this
onclick="document.getElementById('p').setAttribute('contenteditable', true);"
here's a fiddle for this.
I'm assuming you mean something like this:
HTML
<textarea id="c" readonly>Some data</textarea>
<button id="a">
Make editable
</button>
Javascript (with jQuery)
$("#a").on('click', function() {
$("#c").attr('readonly', false);
});
$(function() {
$("#myButton").click(function() {
$("#myDiv").prop("contenteditable", true);
});
});
#myDiv{
height:300px;
width:300px;
background:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"></div>
<button id="myButton">Enable content Editable</button>
see with http://api.jquery.com/attr/#attr2 & https://api.jquery.com/click/
for exemple:
$( "#target" ).click(function() {
$("#yourId").attr("contenteditable", true);
});

When an input button field is added to the page using jQuery, how to access values

I have generated input button fields based on values inputted elsewhere in the page
$('#saved_answers').prepend('<input type="button" name="remove_answer" value="' + answerstring + '"><br />');
Afterwards, I tried calling:
$("input:button[name=remove_answer]").click(function() {
alert("Test!");
});
But nothing happens. When I view source, I also notice that none of the new code shows up. However, it does show up visually in the window.
You should use the jQuery on method rather than click, so something like
$('#saved_answers').on('click', 'some selector for your newly added button', function(){
alert("Test!");
}
This will allow for the event to be attached correctly.
See jQuery .on method
If you use this it should work:
<html>
<head>
</head>
<body>
<div id="saved_answers"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
$('#saved_answers').prepend('<input type="button" name="remove_answer" value="test" />');
$('#saved_answers').on('click', 'input:button[name=remove_answer]', function(){
alert($(this).val());
});
});
</script>
</body>
</html>
Correct me if I misunderstood your question. What you did is binding an event handler to the click event,
$("input:button[name=remove_answer]").click(function () {
alert("Test!");
});
if you want to trigger the click event, you need this
$("input:button[name=remove_answer]").click();

jQuery input button click event listener

Brand new to jQuery.
I was trying to set up an event listener for the following control on my page which when clicked would display an alert:
<input type="button" id="filter" name="filter" value="Filter" />
But it didn't work.
$("#filter").button().click(function(){...});
How do you create an event listener for a input button control with jQuery?
First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:
$("#filter").click(function(){
alert('clicked!');
});
Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
So even if the order is this it will work:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
<input type="button" id="filter" name="filter" value="Filter" />
DEMO
$("#filter").click(function(){
//Put your code here
});
More on gdoron's answer, it can also be done this way:
$(window).on("click", "#filter", function() {
alert('clicked!');
});
without the need to place them all into $(function(){...})

jQuery prevent input default action

I have an ajax form I would like to prevent from preforming an action when submitted and have tried numerous methods and nothing works. My first method was:
return false;
and then I tried
event.preventDefault();
event being the callback name or whatever you call it.
function(event) {
event.preventDefault();
};
Heres the HTML I am using right now:
<form class="main_search" method="POST" action="ajaxsearch.php">
<input type="text" class="editable" placeholder="Search">
</form>
Heres the test javascript I set up:
$('.main_search').submit(function(event) {
event.preventDefault(console.log(event)); //Log the event if captured
});
Neither method works but the weird part is that they work on different things like buttons but they don't work on this one form. Am I missing something here? Thanks!
To deal with your specific problem (ie, inserting dynamically generated form), use $.on(). You're better off not using document.body as the parent observer (as $.live() essentially does) with $.on(), so the following would be appropriate (considering your actual markup):
<div id="searches">
<form class="main_search" method="POST" action="ajaxsearch.php">
<input type="text" class="editable" placeholder="Search">
</form>
</div>
var $main_search = $('.main_search'),
$searches = $('#searches');
$searches.on('submit', '.main_search', function(event) {
event.preventDefault();
console.log(event); //Log the event if captured
});
setInterval(function(){
$searches.append($main_search.clone());
}, 5000);
http://jsfiddle.net/5TVGn/2/
I set up a JSfiddle:
http://jsfiddle.net/XM679/
Could it be you forgot to wrap it into $(document).ready(function() {} ?
If this didn't solve the problem: Since the fiddle is working - we would need your context to help more.

unable to call click event in JS file

Below is the html code:
<input type="button" id="abc" name="TechSupport_PartsOrder" value="Open Editor" />
Below is the JQuery Code:
$('#abc').click(function () {
alert('x');
});
Now when i put the above JQuery code to JS file it does not work, while when i put the same in page it works fine. Why this is happening i don't knw.
And if i call the function onclick of button like this:
<input type="button" id="abc" name="TechSupport_PartsOrder" onclick="abc()" value="Open Editor" />
JQuery:
function abc()
{
alert('x');
}
it works well..
Wrap the code in a ready handler:
$(function() {
$('#abc').click(function() {
alert('clicked');
});
});
Did you make sure that the event handler is getting defined after the DOM has loaded? This is why jquery recommends putting all your code in
$(document).ready(function(){
//XXX code goes here
});
you're event handler is probably try to be assigned before the element has been loaded into the DOM.
Does the following solve the problem?
$(function(){
$('#abc').click(function () {
alert('x');
});
})
Your code may be getting called before '#abc' has been added to the DOM

Categories

Resources