Im having a problem attaching an event to a dynamically generated button. However after some research most of the solutions claim this error is usually generated from a form control. However in my case the error "invalid form control with name='answer'" is being generated and triggered when a button i have dynamically generated is pressed :
$("#BoxInner").append($("<button id='dynamicButton' class='btn btn-success' onclick='clickEvent()'>"+ "Button"+"</button>"));
I have appended a button to an existing div and call an onclick function that removed this element when it is clicked like this :
function clickEvent()
{
$(this).remove();
}
After running this in chrome this method works only on the first button added. After the first button is removed as expected it begins to generate the error "clickEvent" and adding a number count on each click and after reading many posts here about the error being attributed to a form i remain unsure how to solve the issue as the button is completely unrelated to the form on my HTML document and subsequently setting the form to not require validation does not solve the issue with the "novalidate" property. But note, if i remove the attached onclick event the error is not triggered.
Any help would be appreciated :)
$("#BoxInner").append($("<button id='dynamicButton' class='btn btn-success' onclick='clickEvent(this)'>"+ "Button"+"</button>")); // pass this to clickEvent function
function clickEvent(obj)
{
$(obj).remove(); // remove button like this
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="BoxInner"></div>
This is because the event listener is created on page load.
You should do something like this
$(wrapper_that_always_exists).on('click', the_freshly_added_element, function() {
...
});
So in your example it would be something like
$('#BoxInner').on('click', '#dynamicButton', function() {
...
});
When you do this, the BoxInner element will always listen for all clicks on any element inside, initially created or not, that has the id dynamicButton
Related
I'm relying on another plugins javascript that has code for a specific submit event that submits the form after some validation.
I'm not able to change that validation without hacking into that code.
Therefore I've came up with a hack without hacking into that plugin's code.
I'm changing the input type from submit to button type so I can do my own validation without having to take in account for action that is triggered upon submit.
There are two radiobuttons with class .give-gateway. Basically I'm doing this.
HTML (element in form):
<input type="submit" class="give-submit give-btn" id="give-purchase-button"
name="give-purchase" value="Donate Now" data-before-validation-label="Donate
Now">
jQuery:
$('body').on('click', '.give-gateway', check_gateway);
function check_gateway(id) {
//Value from which radiobutton is selected
if (current_gateway == 'swish') {
alert('changing button from ORIGINAL to new. NOW IT SHOULD BE
TYPE BUTTON!!!');
$('#give-purchase-button').prop('id', 'give-purchase-button-
new').prop('type','button');
$('body').on('click touchend', '#give-purchase-button-new', function
(e) {
alert('NEW give purchase button clicked');
//some code...
});
}
else {
alert('changing button from NEW to original. NOW IT SHOULD BE TYPE
SUBMIT!!!');
$('#give-purchase-button-new').attr('id', 'give-purchase-
button').prop('type','submit');
}
}
This works the first time:
From Submit to button
From Button to Submit
From Submit to Button
Step 3 (NOT WORKING (first click on swish gateway work but second time it does not change from submit to button)!? **Why?) **
I've also tried to programmatically add onsubmit to form but the issue there is that other plugins jquery code has a listener for click event on the actual submit - button which means that that code are executed first anyway. I don't want that to happen.
I've figured it out why now. When I click on another gateway the form is loaded with other content. When I go from swish to paypal. It loads content that is dependent of paypal stuff and creates a new submit - button. If I just change from type submit to button it does not affect anything because that change is made before the actual content is loaded (through ajax) and therefore creates a new submit button.
Let's say I have a collection containing 3 elements.
Each element has a corresponding remove button that I would like to initiate a POST to my server. Right now I have it setup so that when "Remove" button is pressed, a confirmation modal pops up with "yes" and "no" buttons. I am using the same modal for each element.
Problem is, when I click "yes" in modal, how can I have it know which remove button I clicked that launched the modal?
Here is a link to a gist containing the problematic code
https://gist.github.com/anonymous/85481507a1171467cae5
I have tried using a suggestion below that implements the following:
$('#hingle_dingle_0').on('click', function(e){
$('#confirmRemoveNetwork').modal('toggle', $(this));
});
$('#confirmRemoveNetwork').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
console.log(button);
});
However this returns an empty set. I can't for goodness sake figure out why it doesn't find the event.
Thanks for any help!
The modal is autoposting because you are opening it with a <button> inside a form with an input. Unless you tell it not to, this will cause a form submit. Simply set the type to button (instead of submit which is default): <button type="button">
You can capture the calling button by tapping into the event thrown when the modal is opened:
$('#confirmRemoveNetwork').on('shown.bs.modal', function (e) {
console.log(e.relatedTarget.id);
});
Finally, be sure your IDs are unique. You cannot have both "remove network" buttons using the same id of removenetworkbtn.
I'm updating the user posts via this code:
var auto_refresh = setInterval(function()
{
$('.contenido-publicaciones')
.load("refresh_p.php?search_user="+search_user).fadeIn();
}, 2500 ); //Which is working.
1: <div class="contenido-publicaciones">, all the <div class="this-is-a-post"> div's from refresh.p.php load here every 2,5 seconds.
2: I have a textarea tag inside for each <div class="this-is-a-post"> that refreshes from refresh_p.php.
3: When <div class="contenido-publicaciones"> refreshes, it also refresh the textarea and prevent the user for typing.
4: All of the textareas have the class b_green
I want to clearInterval(auto_refresh) when the user clicks a textarea with the class b_green so another user can send a comment to that post.
I've tried the following:
$(".b_green").click(function(){
clearInterval(auto_refresh);
}); // Didn't work, <div class="contenido-publicaciones"> keep refreshing.
$("textarea").click(function(){
clearInterval(auto_refresh);
}); // Works only when i click a textarea that i have on the top of the page to send posts, but doesn't work when i click a textarea with the class b_green.
$(this).click(function(){
clearInterval(auto_refresh);
}); //This works if i click on b_green textareas, but stop the Interval on every click that the user does on the page, I only want to stop on b_green textareas click.
Is there any error on my code? Any help would be appreciated.
The clicks do not fire because at the time you are binding them there are no textareas or the ones that there are are latter replaced with new ones. These new textareas do not have the onclick handler attached.
You could do either of these:
Add onclick="clearInterval(auto_refresh);" to the code of the textarea that backend sends and get something like:
<textarea onclick="clearInterval(auto_refresh);"></textarea>
Use on to bind the click handler to a higher element that remains on the page like so:
$(".contenido-publicaciones").on('click', 'textarea', function(){
clearInterval(auto_refresh);
});
As I understood your loaded content contains all nodes which you are trying to handle by click.
If so . There is an issue. Because each time you get update you loose click handlers, because DOM has changed. as + you probably have memory leak here from previous "unreachable" handlers
i am trying to submit my page using jquery with different actions, but below code seems not working
adding user
$("#createBtn").click(function() {
$("#formname").submit(function(event){
$(this).attr('action', 'addUser.html');
});
});
updating user
$("#updateBtn").click(function() {
$("#formname").submit(function(event){
$(this).attr('action', 'updateUser.html');
});
});
EDIT :-
<form:form name="formname" commandName="comandNamd">
i didnt give action name, since i want to change actions.
on click of button, the page is not getting submitted.
You are writing submit handler inside the click handler. This should work.
$("#createBtn").click(function() {
$("#formname").attr('action', 'addUser.html');
$("#formname").submit();
});
Change for update button also.
"i have place my script inside the tag in top of the page"
In that case your script won't actually bind event handlers to your buttons, because the script will run before the form and buttons have been parsed. $("#createBtn") will find no matching element. You can correct this either by putting your script at the end of the page, just before the closing </body> tag, or by wrapping your code in a document ready handler.
Also, the code inside your .click() handler is binding a submit handler to the form, which doesn't really make sense. You just want to set the action:
$(document).ready(function() {
$("#createBtn").click(function() {
$("#formIdHere").attr('action', 'addUser.html');
// OR
$(this).closest("form").attr('action', 'addUser.html');
});
$("#updateBtn").click(function() {
$("#formIdHere").attr('action', 'updateUser.html');
});
});
You said in a comment that the "buttons are inside the form" - if they are submit buttons then the above code should work. The click will run the code shown to set the action, after which the default behaviour (form submission) will continue.
i have fixed the issue, and thanks for your help, since i am using spring form tag,
<form:form name="formName" commandName="command">
but in jquery i was using above form name attribute value, but actually spring form tag generates form id value and final html looks like
<form:form id="formid" name="formName" commandName="command">
after changing the code to have formid, it worked thanks
$("#formid").attr('action', 'addUser.html');
In a function called outputProducts I have added a submit button to my table:
$(addToCartCell).append("<input type='submit' id='addToCart' value='Add To Cart'>");
In order to check the submit button was pressed I make another function:
function addToCart()
{
$(#addToCart).submit(function() {
alert('Submit Detected.');
});
}
But this isn't working and the table created in the function before doesnt even show up, but when I get rid of the addToCart function it does.
You have a syntax error, instead of $(#addToCart) you need $('#addToCart').
Besides that, you need to bind the submit event to the form, not the submit button (you'd bind click to the button, but since you want to do something on submit, binding the submit event to the form is the way to go).
If you do not have a form, use type="button" since there's nothing to submit anyway and bind a click event to the button.
If you need to bind the event before the button exists, use a delegate. #container should be an element that already exists and is a parent of the button:
$('#container').on('click', '#addToCart', function() { ... });
And since you seem to have multiple products, remember that IDs have to be unique - so if you have more than one button, use a class instead and change the selector to .addToCart accordingly.
You have a syntax error. Try $('#addToCart').
please try the following code
function addToCart()
{
$("#addToCart").live("submit", (function() {
alert('Submit Detected.');
});
}
Note: i have tried the same but since you have added the element at runtime you need to bind the event to the element.