Pass [Object object] to a function - javascript

Hi I have a button that passes this to a function as below:
<div class="itemRow">
Delete
</div>
For the sake of keeping this simple, I have removed other elements within the itemRow div. Essentially this div contains information about an item as well as a button to delete that item. Every item will have a itemRow div so there are many on the page. I want to determine which row the button call came from so that when the item is actually deleted, the correct row is removed.
function deleteMessage(row, itemNum){
$('#deleteMsgModal').modal('show');
//Change the modal buttons's onclick handler
$("#deleteConfirmBtn").click(function(){ deleteRow(row, itemNum);});
}
So the above function will display a modal that asks for confirmation. The onclick handler of the button in the modal takes in the this object and the item number which then goes to a seperate function deleteRow that actually deletes the row and removes the row.
function deleteRow(contentRow, itemNo){
var item = itemNo;
//do some ajax code to remove the row from the database...
...
//then once it is removed then to remove the div that is showing the row...
$(contentRow).parent().remove();
}
The problem is that when the #deleteConfirmBtn button's click handler takes in this as an argument, it displays it as [Object object] which will not work. Is there a way I can get around this so that the final function can delete the correct div?

you need to wrap 'this' in $ sign. so in your case would be $(row)

Please clarify,
"The problem is that when the #deleteConfirmBtn button's click handler takes in this as an argument, it displays it as [Object object] which will not work."
Where is the html for this and how are you passing in 'this' value to this function.
My concern, Why is it required to pass this, when you are already binding click event to the button. this value should be already passed along in the function.
Thanks
Ashish

You may use the event handling that comes with jQuery. If you register the click handlers in Javascript, you don't need to pass this to the function. jQuery gives you that reference automatically.
I have done several changes to your code to make a running example without using bootstrap:
Each delete button now haves a data property data-row="x" where x is the number of the row. I have also added a tag class to retrieve all these buttons: .btn-delete.
As you can see, the click handler is registered on Javascript. Once you click a delete button, the row number is retrieved from the previously set data porperty.
Each time you process a Confirm delete event, you need to unbind the click handler. If you don't do it, you may end with unexpected behaviours where the previous delete actions are triggered again.
// Event delegated subscription for all the delete events
$(document).on('click', '.btn-delete', function(event) {
// Prevent navigation event of the anchor
event.preventDefault();
// Get the info of the clicked event
let rowElement = $(this);
let rowNumber = rowElement.data('row');
// Show the confirmation message
$('#deleteMsgModal').show();
//Change the modal buttons's onclick handler
$("#deleteConfirmBtn").click( function(ev) {
// Prevent event propagation
ev.preventDefault();
// Remove the 'modal' message and unbind this click event handler
$('#deleteMsgModal').hide()
$(this).unbind('click');
deleteRow(rowElement, rowNumber);
});
});
function deleteRow(contentRow, itemNo){
let item = itemNo;
alert('Item #' + itemNo + ' removed succesfully');
// do some ajax code to remove the row from the database...
// ...
// then once it is removed then to remove the div that is showing the row...
contentRow.parent().remove();
}
#deleteMsgModal {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="itemRow">
<span>Row 1</span>
Delete
</div>
<div class="itemRow">
<span>Row 2</span>
Delete
</div>
<div class="itemRow">
<span>Row 3</span>
Delete
</div>
<div id="deleteMsgModal">
You are about to delete a row. Are you sure?
Confirm delete
<div>

Related

dynamically generated button , invalid form control with name='answer'

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

JQuery Modal Trigger for Unique Elements

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.

Too many click handlers being called

I am using the following function to dynamically populate a div with some text and a button using the array messages:
var populateMessages = function(messages){
for (var index in messages){
(function(){
var id = index;
$("#messages").append(messages[index]["title"])
$("#messages").append("<button>Open</button><br/>").click(function(){console.log(message["id"])})
}())
}
};
This code correctly populates the div with the text and the button. The problem is that if I click on ANY of the buttons, the click handlers for ALL of them fire. So with two buttons, it should log "0" if I click on the first one and "1" if I click on the second. Instead, if I click on either, it logs "0 1"
I'm not super up on Javascript so I don't know what the issue is.
The return value of
$("#messages").append("<button>Open</button><br/>")
is #messages, not the button that was added. So each time through the loop you're adding another click handler to #messages, not the button.
Try:
$.each(messages, function(index, message) {
$("#messages").append(message.title);
$("<button>Open</button>").click(function() {
console.log(message.id);
}).appendTo("#messages");
$("#messages").append("<br/>");
});
$("#messages").append("<button>Open</button><br/>")
Returns #messages not button so you are setting the click event to #message.
Try this:
$("#messages").append("<button>Open</button><br/>").find("button:last").click(/blabla/)

Alert text when submit detected

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.

Click events being appended on each click

I have a form with multiple rows and each row has a delete button with a link. I want to progressively enhance the links to add a bootstrap modal to these buttons. So what I'm doing is:
Grab all the delete button elements on the page.
Loop through each button.
For each button and change some attributes on the modal based on what button is clicked, including the url that is called when "OK" is cicked.
Everything is working like I want, except that each time the modal is triggered and the "OK" button is clicked the url attached to that gets appended to the previous one.
http://jsfiddle.net/bittersweetryan/9TpX8/ (click the remove button then OK more than once, have your console open)
Here's the code
//anonymous function to grab all delete buttons and turn into a modal
(function(){
var delBtn = $(".delete"),
$modal = $("#modal-delete");
if(!$modal.size()){
$modal = $('<div id="modal-delete" class="modal hide fade"><div class="modal-header"> ×<h3>Confirm Delete</h3></div><div class="modal-body" id="modal-content"></div><div class="modal-footer"> OK Cancel </div></div>').appendTo("body");
}
delBtn.each(function(){
var $button = $(this),
clickHandler,
href= $button.attr("href");
if(href){
clickHandler = function(){
console.log(href);
//return window.location=href;
};
}
else{
clickHandler = $button.click;
}
$button.attr("data-toggle","modal").
attr("data-target","#modal-delete");
$button.on("click",function(){
$modal.find("#okButton").on("click",function(){
clickHandler();
$modal.modal('hide');
}).
end().
find("#cancelButton").on("click",function(){
$modal.modal('hide');
}).
end().
find("#modal-content").html($button.attr("title"));
});
});
})();
You attach another click handler to 'ok' every time you invoke a dialog. Quick fix:
$modal.find("#okButton").one("click",function(){
clickHandler();
$modal.modal('hide');
})
Your updated fiddle.
In general, binding handlers with jQuery sticks a new handler in the queue; it doesn't overwrite the existing handler with a new one.
After getting burned by this a number of times, mostly trying to properly bind to dynamically generated controls, I just started sticking
.unbind("click")
in the queue before setting up onclick bindings.
Some new fiddle.

Categories