Reputation: 3
I've got two code samples, the first one is working properly, the second one isn't. Both of them should increase a counter when I click on the #incrementBtn.
Here are the samples (and I will provide all the code for further clarifications):
$('body').on('click','#incrementBtn', function(){
let textAreaValue = parseInt($('textarea').val());
$('textarea').val(textAreaValue+1)
});
$('#incrementBtn').on('click', function(){
let textAreaValue = parseInt($('textarea').val());
$('textarea').val(textAreaValue+1)
});
And one more question, what is the difference between using this (code doesn't work):
let textArea = $(<'textarea'>);
let textAreaValue = parseInt(textArea.val());
textArea.val(textAreaValue+1);
And this (code works):
let textAreaValue = parseInt($('textarea').val());
$('textarea').val(textAreaValue+1)
Here is the full working code: https://jsfiddle.net/wjnjdk72/3/
Upvotes: 0
Views: 40
Reputation: 1866
With jQuery you select HTML tags only with its name: "textarea", you don't need to include the <> characters
Upvotes: 0
Reputation: 66345
First issue:
You're applying the onclick handler to the element before you've inserted it dynamically into the DOM. The body handler works because it's listening for click events on the body element (which bubble up to it) from an element that matches that #incrementBtn selector (it doesn't matter if it's added to the page later on).
You can see this in action by swapping the order, if you add the element first it works:
incrementCounter('#wrapper'); // add the element first
$('#incrementBtn').on('click', function(){
let textAreaValue = parseInt($('textarea').val());
$('textarea').val(textAreaValue+1)
});
Second issue:
This syntax is invalid Javascript: $(<'textarea'>);
You've added some random <> there.
Upvotes: 1