Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  49] [ 6]  / answers: 1 / hits: 40193  / 10 Years ago, fri, february 28, 2014, 12:00:00

JSFiddle



I'm creating a new button element with



$('<button>Remove Entry</button>', { 'type': 'button', 'class': 'delete_button' });


However the neither the type or class attributes seem to be defined, and the console prints an error saying this.parent() is not a function (though I'm positive I enabled jquery)



I'm afraid I've done something simple and stupid, but I can't seem to find anything wrong.


More From » jquery

 Answers
3

The reason that the attributes are not set on the element, is that you are mixing different uses of the jQuery method.



To use the method in a way that it uses an object for attributes, the first parameter should be a single tag, not a HTML snippet:



$('<button>', { 'type': 'button', 'class': 'delete_button' }).text('Remove Entry');


The reason that this doesn't have a parent method is that it refers to an element, not a jQuery object. You would use $(this) to make a jQuery object from the element reference.



Also, this referers to the new entry button, not the remove entry button, as you are calling the method when you are binding the event. You should call the method when the event happens:



delete_button.click(function() {
remove_entry($(this).parent())
});


Demo: http://jsfiddle.net/Guffa/9TcpB/1/





  var entries = 0;

function new_entry() {
entries++
new_entry_div = $('<div>', { 'class': 'entry' }).appendTo('form');
new_entry_div.html('<p><input type=text></p>')


// delete button
delete_button = $('<button>', { 'type': 'button', 'class': 'delete_button' }).text('Remove Entry');
delete_button.appendTo(new_entry_div);
delete_button.click(function(){
remove_entry($(this).parent());
});
}

function remove_entry(entry) {
entry.remove();
}

$(#newButton).click(function () {
new_entry();
})

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<div id=input>
<form>
</form>
<button id=newButton>New Entry</button>
</div>




[#72230] Thursday, February 27, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kalynnkathrynd

Total Points: 273
Total Questions: 101
Total Answers: 93

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
;