Reputation: 2425
Take a look at my function:
$(".select-default").on("click", function() {
$(".dropdown-menu li a").on("click", function() {
var x = $(".select-default label").children()[0];
$(".select-default label").text($(this).text()+x);
});
$(this).off("click");
});
I'm trying to figure out why x prints undefined, where I expect it to print the actual child node:
<span class="caret"></span>
Edit. Here is the markup:
<ul class="select-default select-sm dropdown-toggle" data-toggle="dropdown">
<label for="select" id="select_value">Select Action <span class="caret"></span></label>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Value 0</a></li>
<li><a href="#">Value 1s</a></li>
<li><a href="#">Value 2</a></li>
<li><a href="#">Value 3</a></li>
I'm trying to get the entire span node nested inside label, and join it with the value of the clicked a tag. x should be printing:
<span class="caret"></span>
Upvotes: 0
Views: 422
Reputation: 2725
this could work:
$(".dropdown-menu li a").on("click", function(e) {
e.preventDefault();
var $label = $(".select-default").children("label");
$label.text($(this).text());
});
working fiddle here: http://jsfiddle.net/uaqHg/2/
Upvotes: 0
Reputation: 388316
$(".select-default label").children()[0]
will be returning undefined
because, from the looks of it the label
has text node as the child. text nodes of a element will not get selected by .children()
, instead you can use $(".select-default label").text()
to get the text of the label
element
$(".select-default").on("click", function() {
$(".dropdown-menu li a").on("click", function() {
var a = $($(".select-default label").contents().get(0));
a.replaceWith($(this).text())
});
$(this).off("click");
});
Demo: Fiddle
Upvotes: 1
Reputation: 2425
The Answer was simple.
Use append(x). Replace:
$(".select-default label").text($(this).text()+x);
With:
$(".select-default label").text($(this).text()).append(x);
Thanks anyway.
Upvotes: 0