Reputation: 8415
http://jsbin.com/kunawoho/1/edit
Working example - http://jsbin.com/vuwaxuqi/1/edit
I'm working on an experimental web designer and I'm trying to grab already added values of css selectors. The fiddle I made generates two buttons and is suppose to clone the input [type=text]. The first is an X meaning close. The second is the text of the value. However I keep getting [object Object]
returning from the dynamically cloned input [type=text]. (No errors are showing up in console either)
I want to click the button and grab the dynamically added value from before and display it in the selector. (I know I can grab this from the button's text, but cause I'm working wit 30+ values in my app it makes more since to stick with what I'm using and grab from that in a closed container. That way everything is grouped and easier to manage).
Not sure why it's not cloning.
$(document).ready(function() {
$(".addvalz").on('click', function() {
// Adds value
$(".val-nester").append("<div class='holddezvalz'><button class='deldizval'>x</button><button class='grabdezvalz'>"+ $(".inputval").val() +"</button>"+ $(".inputval").clone() +"</div>");
// Can't add same value twice. Replace?
var $cssselbtn = $(".val-nester > .holddezvalz button:contains(" + $(".inputval").val() + ")");
if($cssselbtn.length > 1) {
var x = window.confirm("Selector already exists. Want to replace it?");
if (x) {
$cssselbtn.first().parent().remove();
} else {
$cssselbtn.last().parent().remove();
return false;
}
}
// Delete a value
$(".deldizval").on('click', function() {
$(this).parent().remove();
});
});
});
Upvotes: 1
Views: 64
Reputation: 8205
Expanding on @Regent's answer, just split up the append
line:
$(".val-nester").append("<div class='holddezvalz'><button class='deldizval'>x</button><button class='grabdezvalz'>"+ $(".inputval").val() +"</button></div>");
$(".val-nester > div.hoddezvalz").append($(".inputval").clone());
Or, a little more readable:
$(".val-nester").append($("<div class='holddezvalz'>")
.append("<button class='deldizval'>x</button>")
.append("<button class='grabdezvalz'>"+ $(".inputval").val() +"</button>")
.append($(".inputval").clone())
);
Also, you should sanitize input.val()
before you append it to the DOM. Replace input.val()
with something like
.append( ... + $("<p>").text( $(".inputval").val() ).text() + ... );
Then, in the selector, you should surround it with quotes and escape quotes inside it
":contains('" + $(".inputval").val().replace("'", "\\'") + "')"
Upvotes: 2
Reputation: 5178
You placed $(".inputval").clone()
into the string, so it was converted to string.
Try this instead:
$(".val-nester").append($(".inputval").clone());
EDIT: about whole adding:
var addDiv = $("<div class='holddezvalz'><button class='deldizval'>x</button><button class='grabdezvalz'>" + $(".inputval").val() + "</button></div>");
$(addDiv).append($(".inputval").clone());
$(".val-nester").append(addDiv);
Upvotes: 1