Reputation: 2496
I have the following js code:
$(document).ready(function() {
$(".button").bind("click", function() {
var div = $('<div></div>');
$(".label").append(div);
div.html($(".textField").val());
console.log(div);
});
});
with html:
<input type="text" class="textField"/>
<input type="button" class="button" value=" >>"/>
<div class="label" style="color: red;"></div>
and when I click the button, nothing happens. Console output shows that created div
is not a proper div object.
But when I copy onclick function handler code into browser console and run it, it works properly.
Here is jsFiddle.
What is wrong here?
Upvotes: 3
Views: 131
Reputation: 14604
Simply use .click()
event
$(document).ready(function () {
$(".button").click(function () {
var div = $('<div></div>');
$(".label").append(div);
div.html($(".textField").val());
console.log((div));
});
});
Upvotes: 1
Reputation: 36
You probably have something wrong in your code dependencies or structure because this seems to be working. Here's your code running on codepen: http://codepen.io/chriteixeira/pen/qNvoPN
About the log object not being a proper html, maybe you're comparing the plain output in the browser console instead of the log console. To make sure you're comparing the same data, you should run this:
var $div = $('<div></div>');
console.log($div);
Running like this, the result should be the same as in the codepen example.
Upvotes: 1
Reputation: 1661
Change your Code
JQuery
$(document).ready(function() {
$(".button").on("click", function() {
var div = "<div class='id-of-div'></div>"; //changes
$(".label").append(div);
div.html($(".textField").val());
console.log(div);
});
});
HTML
<input type="text" class="textField"/>
<input type="button" class="button" value=" >>"/>
<div class="label" style="color: red;"></div>
I Think, This is helpful
Upvotes: 2