I have uploaded my code to JSfiddle:
http://jsfiddle.net/TSM_mac/pnQEe/
I want to be able to type into the text inputs on the page, and click the “Add Div Type” button, and it will append (create) the div element inside of the div you click on (that has the class = “editable”).
I have having difficulty making this code work. Can anyone find where I went awry?
Code
var $currentInput = null;
$("#add_div1, #add_div2, #add_div3").click(function() {
$currentInput = null;
if ($currentInput == null) {
$currentInput = $(this).prev();
$("label").html($currentInput.attr("id"));
}
});
var editid;
$("div.editable").click(function(e) {
e.stopPropagation();
if ($currentInput == null) return;
editid = $(this).attr("id");
var adddiv = GetElements();
$(this).append(adddiv);
$("label").html("");
});
function GetElements() {
if ($currentInput == null) return null;
var value = $currentInput.val();
if ($currentInput.attr("id") == "add_div1") return {
"<div>"+value+"</div>"
}
if ($currentInput.attr("id") == "add_div2") return {
"<div>"+value+"</div>"
}
if ($currentInput.attr("id") == "add_div3") return {
"<div>"+value+"</div>"
}
}
–
<input type="text" id="add-div1" value="Content of Div 1" />
<div id="add_div1">Add Div Type 1</div>
<input type="text" id="add-div1" value="Content of Div 2" />
<div id="add_div2">Add Div Type 2</div>
<input type="text" id="add-div1" value="Content of Div 3" />
<div id="add_div3">Add Div Type 3</div>
<div id="2" class="defaultclass editable">
Add a Div Here
</div>
<div id="3" class="defaultclass editable">
Add a Div Here
</div>
<div id="4" class="defaultclass editable">
Add a Div Here
</div>
<label></label>
–
input { display: block; padding-top: 10px; }
#add_div1, #add_div2, #add_div3 { background: #c0c0c0; border: solid 1px #777; display: inline-block; }
.editable { border: solid 5px green; margin: 20px; background: blue; color: #fff; }
Regards,
Taylor
this one works now
http://jsfiddle.net/pnQEe/5/
(I added some
console.logbut now is commented out)seems like your code is that you need to click the button and then click the div
Issue #1: you have
return { ... }It should be{ return ... }or justreturn ...Issue #2: you have
add-div1but the code checked againstadd_div1(underscore, not hyphen)Also, I try not to have two elements with the same or similar id name as well. (such as
add-div1for the text input, andadd_div1for the button — looks too similar.