Append Content to HTML and Remove Appended Content When Click Button - javascript

The following code allows me to append new content to the div "users". However, I want to be able remove the appended content if the user clicks button.
The current code removes only the "remove" button when its clicked. However, I need to remove the entire appended code with the class "removeuser", in the beginning of the appended code.
Any help will be appreciated!
<div id="users"></div>
<script>
function adduser() {
count += 1;
$('#users').append('<div id="field'+ count +'" class="removeuser[]"><div
id="left"><div id="fieldname">user #'+ count +' Name:</div><div
id="field"><input id="user_name'+ count +'" name="user_name[]"' + '"
type="text" /></input></div><div id="clear"></div></div><div id="leftleft">
<div id="fieldname">user #'+ count +' Age</div><div id="field"><input
type="number" id="user_age'+ count +'" name="user_age[]"
style="width:50px;" min="0"></input></div><div id="clear"></div><br></div>
<div id="leftleft"><a href="javascript: void(0)" onclick="adduser(); return
false;"><div id="field" class="add"><div
style="position:relative;left:-4px;top:1px;">add another user +</div></div>
</a><br></div> <div id="leftleft"><a href="javascript: void(0)"
onclick="$(this).remove();" ><div id="deluser[]" class="add"><div
style="position:relative;left:-4px;top:1px;">-</div></div></a><br></div>
<div id="clear"></div></div>');
var no = document.getElementById("deluser");
no.onclick = function(){
$('#users .removeuser').$(this).remove();
};
</script>

From what I can tell this is might be the solution you're looking for (note not supported in all browser. See below for transpiled version)...
var count = 0;
adduser();
function adduser() {
$('#users').append(newUser(count))
count++;
}
function deluser(e) {
$(e.target).closest('.user-container').remove();
}
function newUser(count) {
var deleteButton = `
<div>
<a href="javascript: void(0)" onclick="deluser(event); return false;">
<div class="add delete-user" data>
<div style="position:relative;left:-4px;top:1px;">-</div>
</div>
</a>
<br>
</div>
`;
return `
<div class="user-container">
<div id="left">
<div class="fieldname">
user #${count} Name:
</div>
<div class="field">
<input id="user_name${count}" name="user_name[]" type="text" /></input>
</div>
<div id="clear"></div>
</div>
<div>
<div class="fieldname">
user #${count} Age
</div>
<div class="field">
<input type="number" id="user_age${count}" name="user_age[]" style="width:50px;" min="0"></input>
</div>
<div id="clear"></div><br>
</div>
<div>
<a href="javascript: void(0)" onclick="adduser(); return false;">
<div class="field" class="add">
<div style="position:relative;left:-4px;top:1px;">add another user +</div>
</div>
</a>
<br>
</div>
${count > 0 ? deleteButton : ""}
<div class="clear">
</div>
</div>
`;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="users"></div>
There area quite a few things wrong with your initial attempt though and I don't mean to be rude, but you should probably do more work learning the basics of HTML, JS and in this case jQuery. Treehouse is where I started out many years ago and think it is a great introduction to web development (Treehouse - front-end web development). That being said here are the most glaring issues...
Unique ids
id attributes must be unique per HTML document. As in, having id="leftleft" and then on another element in same document having id="leftleft" is invalid.
Missing closing bracket of function block }
HTML template strings
Honestly I don't know how you're able to read that HTML template string, but this is one of the issues front-end frameworks like React and Angular are meant to solve. Writing HTML templates like this will definitely introduce bugs and also drive you insane.
Instead or rewriting your whole program in React or Angular I would suggest using Template Literals and either using Webpack + babel to transpile your code to achieve browser support or for now just visit Babel repl and manually drop in your JS (with template literals) then replace with output code.
This is how the code would look after being transpiled through Babel, which would be supported in all browsers..
var count = 0;
adduser();
function adduser() {
$('#users').append(newUser(count));
count++;
}
function deluser(e) {
$(e.target).closest('.user-container').remove();
}
function newUser(count) {
var deleteButton = "\n <div>\n \n <div class=\"add delete-user\" data>\n <div style=\"position:relative;left:-4px;top:1px;\">-</div>\n </div>\n \n <br>\n </div>\n ";
return "\n <div class=\"user-container\">\n <div id=\"left\">\n <div class=\"fieldname\">\n user #".concat(count, " Name:\n </div>\n <div class=\"field\">\n <input id=\"user_name").concat(count, "\" name=\"user_name[]\" type=\"text\" /></input>\n </div>\n <div id=\"clear\"></div>\n </div>\n <div>\n <div class=\"fieldname\">\n user #").concat(count, " Age\n </div>\n <div class=\"field\">\n <input type=\"number\" id=\"user_age").concat(count, "\" name=\"user_age[]\" style=\"width:50px;\" min=\"0\"></input>\n </div>\n <div id=\"clear\"></div><br>\n </div>\n <div>\n \n <div class=\"field\" class=\"add\">\n <div style=\"position:relative;left:-4px;top:1px;\">add another user +</div>\n </div> \n \n <br>\n </div> \n ").concat(count > 0 ? deleteButton : "", "\n <div class=\"clear\">\n </div>\n </div>\n ");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="users"></div>

use something like this
$( '#users' ).empty();

You need to use following code
var no = $(".deluser"); // add class 'deluser' to each div
no.onclick = function(){
$('#users').empty();
};

I tried to illustrate your approach in another way, I hope it will help you.
var count = 0;
function addUser(i) {
var userBloc = '<li class="list-group-item" id="user'+i+'"> I am the user'+ i +
' <br><button class="btn btn-danger remove" data-count="'+i+'">Remove me</button><hr></li>';
return userBloc;
}
$('#add').click(function(){
$('#blocs').append(addUser(count));
$('#user'+count).fadeIn(activeRemove); //important to active remove event
count++;
});
function activeRemove(){
$.each($('button.remove'), function(i,item){
$(item).click(function(){
$('#user'+$(item).attr('data-count')).remove();
});
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blocs" class="list-group"></div>
<button id="add">Add a another user</button>

Related

Why when I create several html tags with javascript then I can not delete it with the same javascript?

When I create a form with the write () command, then I want to delete it, but I can't. What is the cause of this problem?
In order to do this correctly, what command should I use or what should I change in my code?
var btn = document.querySelector('#btn');
var btn_alert = document.querySelector('#btn-alert');
var content = document.querySelector('.popup-container');
var div1 = document.getElementById('div1');
function message(message, btn) {
document.write('<div id="div1"><div id="content" class="popup-container"><div class="box-item"><div class="icon-success"><span class="span1"></span> <span class="span2"></span><div class="ring"></div></div><h2 class="alert-title">Good job!</h2><div class="alert-content">' + message + '</div><div class="actions-btn"><button onclick="ok()" class="btn-alert" id="btn-alert">' + btn + '</button></div></div></div></div>')
}
function ok() {
div1.removeChild(content);
}
<button class="btn-alert" id="btn">OK</button>
<!-- <div id="content" class="popup-container dis-active">
<div class="box-item">
<div class="icon-success">
<span class="span1"></span>
<span class="span2"></span>
<div class="ring"></div>
</div>
<h2 class="alert-title">Good job!</h2>
<div class="alert-content">is ok.</div>
<div class="actions-btn">
<button class="btn-alert" id="btn-alert">OK</button>
</div>
</div>
</div> -->
<script src="script.js"></script>
<script>
message("خوش اومدی!", "کلیک کن");
</script>
document.write is really outdated. In your script you write the elements to the document after you're trying to retrieve them. That won't work.
Here is an example snippet using insertAdjacentHTML to create a message element with a button to remove it.
It is generally not a good idea to use inline event handlers. The snippet uses event delegation to handle button clicks.
It may be wise to first learn more about html document manipulation or javascript.
document.addEventListener(`click`, handle);
const create = () => message(`خوش اومدی!`,`کلیک کن`);
create();
function handle(evt) {
if (evt.target.id === `btn-alert`) {
document.getElementById('div1').remove();
}
if (evt.target.id === `recreate`) {
create();
}
}
function message(message, btnTxt) {
document.body.insertAdjacentHTML(`beforeEnd`, `
<div id="div1">
<div id="content" class="popup-container">
<div class="box-item">
<div class="icon-success">
<span class="span1"></span>
<span class="span2"></span>
<div class="ring"></div>
</div>
<h2 class="alert-title">Good job!</h2>
<div class="alert-content">${message}</div>
<div class="actions-btn">
<button class="btn-alert" id="btn-alert">${btnTxt}</button>
</div>
</div>
</div>
</div>`);
}
<button id="recreate">(re)create message</button>

How can I add elements in JS to certain divs

How do I put the created input into the other div in situation I presented below? If I introduce divs in js like this - '<div class="monday_input"><input type="button" class="remove_button" value="-" onclick="removeMon(this)" /></div>' removing the whole element is not working for some reason in this specific case. Answering the question. No I cannot create div in parent in html because input won't magically suit to created div . Please help me somehow, thank you!
HTML:
<div class="day">
<div class="day_info">
<p>Monday</p>
</div>
<div class="add">
<div class="button" onclick="add_monday()">
<i class="fas fa-plus" id="plus"></i>
</div>
</div>
<div style="clear:both"></div>
</div>
<div id="mon">
<div style="clear:both"></div>
</div>
JavaScript:
Function to adding:
function add_monday() {
if (monday_sub_count < 5) {
monday_sub_count++;
{
const mon = document.createElement('div');
mon.className = 'subcategory';
mon.innerHTML = '<textarea name="monday'+monday_id_count+'" placeholder="Type anything you want here" class="subcategory_text"></textarea><input type="button" class="remove_button" value="-" onclick="removeMon(this)" />';
monday_id_count++;
document.getElementById('mon').appendChild(mon);
}
}
}
Function to removing:
function removeMon(mon) {
document.getElementById('mon').removeChild(mon.parentNode);
monday_sub_count--;
monday_id_count--;
};
with your own HTML
function add_monday() {
var monday_sub_count = 0;
var a;
while (monday_sub_count < 5) {
a = '<div><textarea name="monday'+monday_id_count+'" placeholder="Type anything you want here" class="subcategory_text"></textarea><input type="button" class="remove_button" value="-" onclick="removeMon(this)" /></div>';
monday_sub_count++;
$('#mon').append(a);
}
}
Here is working, "proper" version of your code. I think your problem may come from over-complicating the removal process.
function add_monday()
{
let monday_count = 0;
// Use DocumentFragment for marginal optimizations
let fragment = new DocumentFragment();
while(monday_count < 5)
{
let monday = document.createElement('div');
monday.classList.add('subcategory');
let textarea = document.createElement('textarea');
textarea.classList.add('subcategory_text');
textarea.name = "monday_"+monday_count;
textarea.placeholder = "Type anything you want here";
let removeBtn = document.createElement('input');
removeBtn.type = "button";
removeBtn.classList.add('remove_button');
removeBtn.value = "-";
removeBtn.addEventListener('click', removeMon.bind(null, removeBtn));
monday.append(textarea, removeBtn);
fragment.appendChild(monday);
monday_count++;
}
document.getElementById('mon').appendChild(fragment);
}
function removeMon(button)
{
button.parentElement.remove();
}
I simplified your script a little and changed your name attributes: Instead of assigning individual names I simply gave all textareas the name monday[]. When posting this to a PHP page the values will be pushed into an array with the same name and in case you want to harvest the values with JavaScript, then this can be done easily too.
function add_monday(){
$("#mon").append('<div><textarea name="monday[]" placeholder="Type anything you want here"></textarea><input type="button" value="-"/></div>'.repeat(5))
}
$("#mon").on("click","input[type=button]",function(){$(this).parent(). remove()})
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div class="day">
<div class="day_info">
<p>Monday</p>
</div>
<div class="add">
<div class="button" onclick="add_monday()">
<i class="fas fa-plus" id="plus">click here to add fields</i>
</div>
</div>
<div style="clear:both"></div>
</div>
<div id="mon">
<div style="clear:both"></div>
</div>
And here a non-jQuery version:
const ad=document.querySelector(".alldays");
ad.innerHTML=
"Mon,Tues,Wednes,Thurs,Fri,Satur,Sun".split(",").map(d=>`
<div class="day">
<div class="day_info"><p>${d}day</p></div>
<div class="add">
<div class="button">
<i class="fas fa-plus" id="plus">click here to add fields</i>
</div>
</div>
<div style="clear:both"></div>
</div>
<div id="${d.toLowerCase().substr(0,3)}">
<div style="clear:both"></div>
</div>`).join("");
function add2day(el,n){
const wd=el.closest(".day"),
d=wd.querySelector("p").textContent.toLowerCase(),
html=`<textarea name="${d.toLowerCase()}[]" placeholder="Type anything you want here"></textarea><input type="button" value="-"/>`;
while (n--) {
let div= document.createElement("div");
div.innerHTML=html;
wd.nextElementSibling.appendChild(div);
}
}
ad.addEventListener("click",function(ev){
const el=ev.target;
switch(el.tagName){
case "INPUT": // remove field
el.parentNode.remove(); break;
case "I": // add new fields
add2day(el,3); break;
}
})
<div class="alldays"></div>
I extended the second script to make it work for any day of the week.

Link simillary name classes so that when one is clicked the other is given a class

Basically, I'm asking for a way to optimize this code. I'd like to cut it down to a few lines because it does the same thing for every click bind.
$("#arch-of-triumph-button").click(function(){
$("#arch-of-triumph-info").addClass("active-info")
});
$("#romanian-athenaeum-button").click(function(){
$("#romanian-athenaeum-info").addClass("active-info")
});
$("#palace-of-parliament-button").click(function(){
$("#palace-of-parliament-info").addClass("active-info")
});
Is there a way to maybe store "arch-of-triumph", "romanian-athenaeum", "palace-of-parliament" into an array and pull them out into a click bind? I'm thinking some concatenation maybe?
$("+landmarkName+-button").click(function(){
$("+landmarkName+-info").addClass("active-info")
});
Is something like this even possible?
Thanks in advance for all your answers.
EDIT: Here's the full HTML.
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button"></div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button"></div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Assuming you're not able to modify your HTML markup (in which case with use of CSS classes would be cleaner), a solution to your question would be as shown below:
// Assign same click handler to all buttons
$("#arch-of-triumph-button, #romanian-athenaeum-button, #palace-of-parliament-button")
.click(function() {
// Extract id of clicked button
const id = $(this).attr("id");
// Obtain corresponding info selector from clicked button id by replacing
// last occurrence of "button" pattern with info.
const infoSelector = "#" + id.replace(/button$/gi, "info");
// Add active-info class to selected info element
$(infoSelector).addClass("active-info");
});
Because each .landmark-button looks to be in the same order as its related .landmark-info, you can put both collections into an array, and then when one is clicked, just find the element with the same index in the other array:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
This does not rely on IDs at all - feel free to completely remove those from your HTML to declutter, because they don't serve any purpose now that they aren't being used as selectors.
Live snippet:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
.active-info {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button">click</div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button">click</div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Older answer, without knowing the HTML: You can extract the ID of the clicked button, slice off the button part of it, and then select it concatenated with -info:
$(".landmark-button").click(function() {
const infoSel = this.id.slice(0, this.id.length - 6) + 'info';
$(infoSel).addClass('active-info');
});
A much more elegant solution would probably be possible given the HTML, though.

JavaScript does not work after outsourcing

I'm using the Multi Page Template (all pages and javascriot in one html file). I just restructure my jQuery mobile app:
Before: all JavaSripts in the html file, example:
<div data-role="page>.....<script></script> </div>
Now: all JavaScripts are outsourced in a own file. But now comes the problem:
I'm searching after addresses at one page. Each result is stored in a history (localStorage). So the user can use the search or click on old history search results.
Since I outsourced the script for this page, the history doesn't work. I will show you the working code and the not working code:
Working code - pre outsourced:
This code works. JavaScript is in page div:
<div data-role="page" id="searchPage" class="bg-light">
<div data-role="content">
<div id="content-search">
<p><input type="text" name="address" id="address" class="stored" value="" /></p>
<p><input type="submit" id="submitAddress" value="Search" data-theme="a" data-corners="false" /></p>
</div>
<div id="searchHistory">
<div class="ui-corner-all custom-corners">
<div class="ui-bar ui-bar-c">
<h3>History:</h3>
</div>
<div class="ui-body ui-body-c">
<div id="lastResults" class="ui-body ui-body-c ui-corner-all"></div>
</div>
</div>
</div>
</div>
<script>
......
// check and show previous results in **lastResults** div
if (localStorage.getItem("history") != null) {
var historyTemp = localStorage.getItem("history");
var oldhistoryarray = historyTemp.split("|");
oldhistoryarray.reverse();
$("#lastResults").empty();
jQuery.each( oldhistoryarray, function( i, val ) {
$("#lastResults").append(
"<ul data-role=\"listview\" data-inset=\"true\" >" +
// store history in localStorage
"<li><a href=\"#mapPage\" onClick=\"getHistory("+i+");\" >"+oldhistoryarray[i]+"</a></li>" +
"</ul>"
);
// max. history
if (i==3) {
return false;
}
});
} else {
// hide search history
console.log("no history");
$("#searchHistory").hide();
}
function getHistory(i){
localStorage.setItem('address', oldhistoryarray[i]);
}
</script>
</div>
Not Working code - JS outsourced in own file:
JavaScript is now in own file (function.js):
index.html:
detail code see above
<div data-role="page" id="searchPage" class="bg-light">
<div data-role="content">
</div>
<script></script>
</div>
function.js:
// check and show previous results in **lastResults** div
if (localStorage.getItem("history") != null) {
var historyTemp = localStorage.getItem("history");
var oldhistoryarray = historyTemp.split("|");
oldhistoryarray.reverse();
$("#lastResults").empty();
jQuery.each( oldhistoryarray, function( i, val ) {
$("#lastResults").append(
"<ul data-role=\"listview\" data-inset=\"true\" >" +
// store history in localStorage
"<li><a href=\"#mapPage\" onClick=\"getHistory("+i+");\" >"+oldhistoryarray[i]+"</a></li>" +
"</ul>"
);
// max. history
if (i==3) {
return false;
}
});
} else {
// hide search history
console.log("no history");
$("#searchHistory").hide();
}
function getHistory(i){
localStorage.setItem('address', oldhistoryarray[i]);
}
if you are not executing your script after the page has finished loading, there's a chance queries like $("#searchHistory") might be returning empty.
Make sure you execute your script in a callback that is called at the onload event.
so I'd suggest something like this (please also check that you initialize your "history")
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
<script src="function.js"></script>
<script>
$(document).on( "pagecreate", function( event ) {
console.log("page created")
$('#submitAddress').on('click',function(){
makeHistory();
})
});
</script>
</head>
<body>
<div data-role="page" id="searchPage" class="bg-light">
<div data-role="content">
<div id="content-search">
<p><input type="text" name="address" id="address" class="stored" value="" /></p>
<p><input type="submit" id="submitAddress" value="Search" data-theme="a" data-corners="false" /></p>
</div>
<div id="searchHistory">
<div class="ui-corner-all custom-corners">
<div class="ui-bar ui-bar-c">
<h3>History:</h3>
</div>
<div class="ui-body ui-body-c">
<div id="lastResults" class="ui-body ui-body-c ui-corner-all"></div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
function.js then would be
// check and show previous results in **lastResults** div
function makeHistory()
{
if (localStorage.getItem("history") != null) {
var historyTemp = localStorage.getItem("history");
var oldhistoryarray = historyTemp.split("|");
oldhistoryarray.reverse();
$("#lastResults").empty();
jQuery.each( oldhistoryarray, function( i, val ) {
$("#lastResults").append(
"<ul data-role=\"listview\" data-inset=\"true\" >" +
// store history in localStorage
"<li><a href=\"#mapPage\" onClick=\"getHistory("+i+");\" >"+oldhistoryarray[i]+"</a></li>" +
"</ul>"
);
// max. history
if (i==3) {
return false;
}
});
} else {
// hide search history
console.log("no history");
//and you probably need to initialize your history here, something like
localStorage.setItem("history", "lalala");
$("#searchHistory").hide();
}
}
function getHistory(i){
localStorage.setItem('address', oldhistoryarray[i]);
}
Now the pagecreate event also binds a behaviour to your search button to actually update the history each time it is clicked.

can't get .on() to work

I know this topic has been asked a lot before but I read a lot of stackoverflow posts and can't figure it out. Either I'm doing a silly mistake or using the code wrong. In any case I'd appreciate other sets of eyes.
My code is actually simple. Elements are being dragged into boxes and I want the user to be able to close the dragged boxes so they can redo the dragging.
<div id="questionContainer">
<div class='row-fluid'>
<div class='span3 box-content'>
<div class="box span12">
<input type="text" placeholder="Column 1" />
</div>
<div class="box span12 groupBoxes">
</div>
</div>
<div class='span3 box-content'>
<div class="box span12">
<input type="text" placeholder="Column 2" />
</div>
<div class="box span12 groupBoxes">
</div>
</div>
<div class='span3 box-content'>
<div class="box span12">
<input type="text" placeholder="Column 3" />
</div>
<div class="box span12 groupBoxes">
</div>
</div>
<div class='span3 box-content'>
<div class="box span12">
<input type="text" placeholder="Column 4" />
</div>
<div class="box span12 groupBoxes">
</div>
</div>
</div>
Then there is the javascript which appends the dragged element. And I have an .on() function there that doesn't work at all.
$( ".groupBoxes" ).droppable({
accept: ".sDrag",
drop: function( event, ui ) {
var studentID = $(ui.draggable).attr('Uid');
var studentName = $(ui.draggable).find(".sName").text();
console.log(studentID + ' ' + studentName);
var dropbox = "<div class='box questionBox' Uid='"+studentID+"' ><div class='box-content box-statistic'><h3 class='title text-error'>"+studentName+"</h3><div class='icon-remove align-right card-remove' style='font-size:12px'></div></div> </div>";
$(this).append(dropbox);
}
});
$("#questionContainer").on('click', '.card-remove', function () {
console.log('hi');
var student = $(this).parent('.questionBox').attr('Uid'); // get user number
var box = $(".studentBox[value='"+student+"']")// find the original object through user
box.removeClass('muted-background').addClass('sDrag');// back in the original object, add class sDrag and remove class muted-background
// remove the object clicked
});
Any ideas about what's going wrong here?
try to define dropbox outside the function
var dropbox;
$( ".groupBoxes" ).droppable({
accept: ".sDrag",
drop: function( event, ui ) {
var studentID = $(ui.draggable).attr('Uid');
var studentName = $(ui.draggable).find(".sName").text();
console.log(studentID + ' ' + studentName);
dropbox = "<div class='box questionBox' Uid='"+studentID+"' ><div class='box-content box-statistic'><h3 class='title text-error'>"+studentName+"</h3><div class='icon-remove align-right card-remove' style='font-size:12px'></div></div> </div>";
$(this).append(dropbox);
}
});
$("#questionContainer").on('click', '.card-remove', function () {
console.log('hi');
var student = $(this).parent('.questionBox').attr('Uid'); // get user number
var box = $(".studentBox[value='"+student+"']")// find the original object through user
box.removeClass('muted-background').addClass('sDrag');// back in the original object, add class sDrag and remove class muted-background
// remove the object clicked
});

Categories

Resources