Onsubmit form creating new div with id and class - javascript

I'm building a tabbed content page. I was trying to build a form that would take a value from the form and create a new tab and also create a new div that would attach to the tab, that would be triggered by an on click function. I was having some trouble creating the div, it didn't seem to launch. When the value is entered, the tab is supposed to go active so the content would show up. I think I'm either doing something wrong with the new div or the on click function. I wasn't sure if those two code pieces should be combined, since they seemed to be in conflict. Thanks.
jQuery(document).ready(function() {
jQuery('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
$('.tabs ' + currentAttrValue).show();
$('.tabs ' + currentAttrValue).animate({
opacity: 1,
paddingLeft: '30%'
}, 400);
$('.tabs ' + currentAttrValue).siblings().css({
opacity: 0,
paddingLeft: '0%'
});
$('.tabs ' + currentAttrValue).fadeIn(400).siblings().hide();
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
});
$(function() {
var $textInput = $('input:text');
$('#examine').on('submit', function(e) {
e.preventDefault();
var newText = $textInput.val();
$('ul:last').append('<li>Searching...</li>');
$('#tab-content').append('<div id ="tab5' + '"class="tab active"><p>the quick brown fox</p></div>');
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
$textInput.val('');
});
});
.tab-links {
float: left;
}
.tab-links:after {
display: block;
clear: both;
content: '';
}
.tab-links li {
list-style-type: none;
background-color: #303030;
border-bottom: 3px solid #858585;
font-family: 'Jacques Francois', serif;
text-transform: uppercase;
letter-spacing: 0.09em;
margin-left: -25%;
}
.tab-links li a {
color: #f2f2f2;
display: block;
padding: 3px 10px 3px 10px;
text-decoration: none;
}
.tab-links a:hover {
background: #a7cce5;
text-decoration: none;
}
.tab-links li.active,
.tab-links li.hover {
background-color: #e5e5e5;
border-bottom: 3px solid #e5e5e5;
}
.tab-links li.active a,
.tab-links li a:hover {
color: #666;
background-color: #e5e5e5;
}
/*----- Content of Tabs -----*/
.tab-content {
background-color: #e5e5e5;
color: #666;
min-height: 150px;
overflow: auto;
}
#tab1 {
padding-left: 30%;
}
#tab2,
#tab3,
#tab4,
#tab5 {
display: none;
opacity: 0;
padding-left: 0%;
}
.tab-content p {
margin: 20px;
text-indent: -40%;
}
.tab-content.active {
display: block;
text-indent: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="sidebar">
<div id="explore">
<form id="examine">
<p>Search</p>
<input type="search" name="explore" placeholder="Search Items" />
<p>Choose Your Search Restrictions</p>
<input type="radio" name="location" required="required" value="Your School" />Inside
<input type="radio" name="location" required="required" value="Whole system" />Outside
<input type="submit" value="Search" />
</form>
</div>
<div class="tabs">
<ul class="tab-links">
<li class="active">Tab1
</li>
<li>Tab2
</li>
<li>Tab3
</li>
<li>Tab4
</li>
</ul>
<div class="tab-content">
<div id="tab1" class="tab active">
<p>Tab1 content</p>
</div>
<div id="tab2" class="tab">
<p>Tab2 content</p>
</div>
<div id="tab3" class="tab">
<p>Tab3 content</p>
</div>
<div id="tab4" class="tab">
<p>Tab4 content</p>
</div>

First off you do not need two document ready handlers.
For clarity, I have added the NEW index to the "Searching..." string so you may need to edit that.
Use the index to get the new ID and append that to the list.
cache the tab and not process DOM for the tab
I assume you have some need for $textInput.val(''); so I left it
put your click handler on the .tab-links so new ones will have it (not on a1)
consider using classes and indexes instead of new IDs for tab5 etc.
if you use classes you could then clone the last tab and put in new content into the clone, making it more maintainable if the markup changes
I put a trigger on the newly added tab to activate it - it SEEMED as if that was your desire?
Consider a BUTTON rather than <input type="submit"...
Revised code:
jQuery(document).ready(function() {
jQuery('.tabs').find('.tab-links').on('click', 'a', function(e) {
var currentAttrValue = jQuery(this).attr('href');
// cache instead of multiple
var thisTab = $(currentAttrValue);
thisTab.show().animate({
opacity: 1,
paddingLeft: '30%'
}, 400);
thisTab.siblings().css({
opacity: 0,
paddingLeft: '0%'
});
thisTab.fadeIn(400).siblings().hide();
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
var $textInput = $('input:text');
$('#examine').on('submit', function(e) {
e.preventDefault();
var newText = $textInput.val();
var newIndex = $('.tab-links').find('li').length + 1;
$('.tab-content').append('<div id="tab' + newIndex + '" class="tab"><p>the quick brown fox ' + newIndex + '</p></div>');
$textInput.val('');
$('.tab-links').append('<li>Searching...' + newIndex + '</li>');
$('.tab-links').find('a').eq(newIndex - 1).trigger('click');
});
});f
EDIT: Per comment, update if already at max count:
This is not super efficient but you can get started with this.
jQuery(document).ready(function() {
jQuery('.tabs').find('.tab-links').on('click', 'a', function(e) {
var currentAttrValue = jQuery(this).attr('href');
// console.log(currentAttrValue);
var thisTab = $(currentAttrValue);
thisTab.show().animate({
opacity: 1,
paddingLeft: '30%'
}, 400);
thisTab.siblings().css({
opacity: 0,
paddingLeft: '0%'
});
thisTab.fadeIn(400).siblings().hide();
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
var maxTabCount = 5;
var $textInput = $('input[type=search]');
$('#examine').on('submit', function(e) {
e.preventDefault();
var newText = $textInput.val();
var tabCount = $('.tab-links').find('li').length;
var newIndex = tabCount + 1;
var newText = $textInput.val() ? $textInput.val() : "Default Tab Text";
if (tabCount < maxTabCount) {
$('.tab-content').append('<div id="tab' + newIndex + '" class="tab"><p>the quick brown fox ' + newIndex + '</p></div>');
$('.tab-links').append('<li>Searching...' + newIndex + '</li>');
} else {
$('.tab-content').find('div.tab').last().find('p').html("New Search Content");
$('.tab-links').find('li').last().find('a').html(newText);// new tab text
}
$textInput.val('');
$('.tab-links').find('a').last().trigger('click');
});
});

You are using id for tab-content instead of class. Use the following line:
$('.tab-content').append('<div id ="tab5' + '"class="tab active">...</div>');
Replace this line jQuery('.tabs .tab-links a').on('click', function(e) with the following:
jQuery(document).on("click",".tabs .tab-links a",function() {

Related

how to fix onClick button for append functions?

Here I work on a project where I want to implement open and close buttons but I am not able to do
currently, it's a close button for both, I need to add separate open and close buttons so that when the user clicks on open then it's open and when someones click on close then it should close properly also when I click continuously close then buttons freezes for sometime
Here is the demo of my JSFiddle Demo
please check the js Fiddle demo where buttons doesn't work properly
Here is the code
function createItem(item) {
var elemId = item.data("id");
var clonedItem = item.clone();
var newItem = $(`<div data-id="${elemId}"></div>`);
newItem.append(clonedItem);
newItem.appendTo('.item-append');
}
function countSaveItems() {
$('.count').html($(".item-append div.item-save[data-id]").length);
}
$('.item-all .item-save').click(function() {
$(this).toggleClass('productad')
window.localStorage.setItem('test_' + this.dataset.id, $(this).hasClass('productad'));
});
$('.item-all .item-save').each(function() {
var id = 'test_' + $(this).data("id");
$(this).append(`<button class='close'>Close</button>`);
if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
$(this).addClass('productad');
createItem($(this));
countSaveItems();
}
});
$(".item-all .item-save").click(function() {
var elemId = $(this).data("id");
var existing = $(`.item-append div[data-id="${elemId}"]`);
if (existing.length > 0) {
existing.remove();
} else {
createItem($(this));
}
countSaveItems();
});
$(".item-append").on("click", ".close", function() {
var id = $(this).parent().data("id");
localStorage.removeItem(`test_${id}`);
$(`.item-save[data-id='${id}']`).removeClass('productad');
$(this).parent().remove();
countSaveItems();
});
.item-save {
position: relative;
display: block;
font-size: 14px;
margin: 5px;
padding: 5px;
background: #a5a5a5;
float: left;
text-align: center;
cursor: pointer;
}
.productad {
background: red;
color: #eee
}
.count {
display: block;
background: #cbcbcb;
float: left;
font-size: 15px;
padding: 5px 18px;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>
Save1
</div>
<div class='item-save' data-id='124'>
Save2
</div>
<div class='item-save' data-id='125'>
Save3
</div>
<div class='item-save' data-id='126'>
save4
</div>
</div>
<div class='item-append'>
</div>
<div class='count'>0</div>
Any Kind of help or suggestion is highly appreciated
To do the effect you need to add the open button into the HTML because that will be static, then switch between "Open" and "Close" when the user clicks into the "Open" or close the item, also needs to fix the local storage instead of removing in the close button just switch the value to false and validate based on that value. check the following code to see if that is what you are looking for:
function createItem(item){
var elemId = item.data("id");
var clonedItem = item.clone();
var newItem = $(`<div data-id="${elemId}"></div>`);
newItem.append(clonedItem);
clonedItem.children('.open').remove();
clonedItem.append(`<button class='close'>Close</button>`);
newItem.appendTo('.item-append');
}
function countSaveItems(){
$('.count').html($(".item-append div.item-save[data-id]").length);
}
$('.item-all .item-save').click(function() {
var id = $(this).data("id");
var lsId = `test_${id}`;
$(this).toggleClass('productad');
if (!$(this).hasClass('productad')){
window.localStorage.setItem(lsId, false);
$(this).children(".open").html("Open");
createItem($(this));
}else{
window.localStorage.setItem(lsId, true);
$(this).children(".open").html("Close");
$(`.item-append div[data-id='${id}']`).remove();
}
countSaveItems();
});
$('.item-all .item-save').each(function() {
var id = 'test_' + $(this).data("id");
if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
$(this).addClass('productad');
createItem($(this));
}
countSaveItems();
});
$(".item-all .item-save").click(function() {
var elemId = $(this).data("id");
var existing = $(`.item-append div[data-id="${elemId}"]`);
if (existing.length > 0){
existing.remove();
}else{
createItem($(this));
}
countSaveItems();
});
$(".item-append").on("click", ".close", function() {
var id = $(this).parent().data("id");
window.localStorage.setItem(`test_${id}`, false);
$(`.item-save[data-id='${id}']`).removeClass('productad');
$(`.item-save[data-id='${id}']`).children(".open").html("Open");
$(this).parent().parent().remove();
countSaveItems();
});
.item-save {
position: relative;
display: block;
font-size: 14px;
margin: 5px;
padding: 5px;
background: #a5a5a5;
float: left;
text-align: center;
cursor: pointer;
}
.productad {
background: red;
color: #eee
}
.count {
display: block;
background: #cbcbcb;
float: left;
font-size: 15px;
padding: 5px 18px;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>
Save1 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='124'>
Save2 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='125'>
Save3 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='126'>
Save4 <button class='open'>Open</button>
</div>
</div>
<div class='item-append'></div>
<div class='count'>0</div>

specific menu with specific data for each object

I'm trying to make a page where you can create "documents" that are divs with specific properties.
For now I thought about name & color.
First, when you click in the body, you can create a document that is called "something+i" (i is its ID) then, when you click a specific document you can access a menu to edit its color and its name.
finally when you close the menu by clicking OK the specific document is updated.
Do you have any idea on how to do that?
Thanks a lot for the help.
var i = 1;
$(function(){
$(document.body).click(function(e){
var div = $("<div />", { "class":"document", id:"document"+i })
.css({
"left": e.pageX + 'px',
"top": e.pageY + 'px'
})
.append($( "<p>document</p>")+i )
.appendTo(document.body);
$('.document').click(function(event){
event.stopPropagation();
});
$('.menu').click(function(event){
event.stopPropagation();
});
document.querySelector(".document").addEventListener("click", function(){
document.querySelector(".menu").style.display = "block";
});
document.querySelector(".validate").addEventListener("click", function(){
document.querySelector(".menu").style.display = "none";
});
i++;
});
});
body{
width: 100vw;
height: 100vh;
background: grey;
}
.document {
position: absolute;
transform: translate(-50%, -50%);
opacity: 1;
background-color: red;
resize:both;
overflow: auto;
filter: drop-shadow(0 0 0.2rem black);
}
.menu{display: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="menu">
<li><input type="text" id="name" name="name" size="10" placeholder="name"></li>
<li><input type="text" id="color" name="color" size="10" placeholder="color"></li>
<button class ="validate">OK</button>
</div>
</body>
When you click on document first check if there is any menu exist with the id which is clicked if there is show that menu else create new menu .You can use clone to create new menu and then add data-id to it and append them under some divs .
Then , when ok button is clicked simply use $(this).closest(".menu_copy").hide(); to hide the menu .
Demo Code :
var i = 1;
$(function() {
$(document.body).click(function(e) {
var subject = $(".menu_copy")
//check if target click doesn't have class document && not inside menu_copy
if ((!$(event.target).hasClass('document')) && (!subject.has(e.target).length)) {
var div = $("<div />", {
"class": "document",
id: "document" + i
})
.css({
"left": e.pageX + 'px',
"top": e.pageY + 'px'
})
.append($("<p>document</p>") + i)
.appendTo(document.body);
i++;
}
});
//onclick of document
$(document).on('click', '.document', function(event) {
event.stopPropagation();
var id = $(this).attr("id"); //get id
//check if there is any div with data-id
if ($("[data-id =" + id + " ]").length > 0) {
$("[data-id =" + id + " ]").show() //show it
} else {
//create new menu
var clone_menu = $(".menu_copy:first").clone();
$(clone_menu).attr("data-id", $(this).attr("id"))
$(clone_menu).css("display", "block")
$(clone_menu).appendTo(".docs"); //append inside docs
}
});
//if ok is clicked
$(document).on('click', '.validate', function(event) {
//get color and name
var name = $(this).closest(".menu_copy").find("input[name='name']").val();
var color = $(this).closest(".menu_copy").find("input[name='color']").val();
var data_id = $(this).closest(".menu_copy").attr("data-id")
$("#" + data_id).text(name);//add name
$("#" + data_id).css("color", color);//apply color
$(this).closest(".menu_copy").hide(); //hide the menu
})
});
body {
width: 100vw;
height: 100vh;
background: grey;
}
.document {
position: absolute;
transform: translate(-50%, -50%);
opacity: 1;
background-color: red;
resize: both;
overflow: auto;
filter: drop-shadow(0 0 0.2rem black);
}
.menu {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="menu_copy" style="display:none">
<li><input type="text" id="name" name="name" size="10" placeholder="name"></li>
<li><input type="text" id="color" name="color" size="10" placeholder="color"></li>
<button class="validate">OK</button>
</div>
<!--added this divs new menus will go inside this -->
<div class="docs"></div>
</body>

Counting variable in JS that has been parsed from php

I got a variable that represents required number of items and counting of dropped items inside droppable area. You can view example here. So what I want is to pass a variable to javascript and then calculate the difference.
I put my variable into div:
<div id="numbr" >10</div>
And here is the js code which counts dropped items and displays the total:
var n = $(this).closest("div.proc").find(".dropClass").length -1;
$(this).closest("div.proc").find("div.dropped").text("Items Dropped: " + n + ".");
My goal is to find differences between <div class="numbr"> and n, and then display it. How can I achieve this in js?
It is just an example.In my system, the number is a php variable received from user's input. There could be more than 2 boxes: it depends on user's input.
Try the following in both the drop event and the click event:
var proc = $(this).closest("div.proc");
proc.find('.dif').text('Difference ' +(proc.find('.numbr').text() - n));
demo: https://jsfiddle.net/d1ddsj8m/2/
var itm = [];
$("#savebutton").click(function() {
LISTOBJ.saveList();
});
$("#myAccordion").accordion({
heightStyle: "content",
active: false,
collapsible: true
});
$("#myAccordion li").draggable({
appendTo: "body",
helper: "clone",
start: function(ev, ui) {
ui.helper.width($(this).width());
}
});
$(".projLeader ol").droppable({
tolerance: 'pointer',
hoverClass: 'highlight',
drop: function(ev, ui) {
var zz = ui.draggable.text()
var xyz = itm.includes(zz);
if (xyz === false) {
var item = ui.draggable;
if (!ui.draggable.closest('.placeholder').length) item = item.clone().draggable(); // if item was dragged from the source list - clone it
//this.innerHTML = ''; // clean the placeholder
item.addClass('dropClass').appendTo(this);
// append item to placeholder
//add to array
itm.push(zz);
var n = $(this).closest("div.proc").find(".dropClass").length;
$(this).closest("div.proc").find(".dropped").text("Items Dropped: " + n + ".");
$(this).closest("div.proc").find('.dif').text('Difference ' + ($(this).closest("div.proc").find('.numbr').text() - n));
} else {
alert('Name is Already Exist');
}
}
});
$(".projLeader").on('click', '.closer', function() {
var item = $(this).closest('.item');
var element = $("#myAccordion ul li").filter(function() {
return $(this).text() == item.text();
});
itm.splice(item);
var n = $(this).closest("div.proc").find(".dropClass").length - 1;
$(this).closest("div.proc").find("div.dropped").text("Items Dropped: " + n + ".");
$(this).closest("div.proc").find('.dif').text('Difference ' + ($(this).closest("div.proc").find('.numbr').text() - n));
item.fadeTo(200, 0, function() {
item.remove();
})
});
var LISTOBJ = {
saveList: function() {
var listCSV = "";
$(".projLeader li").each(function() {
if (listCSV === "") {
listCSV = $(this).text();
} else {
listCSV += ", " + $(this).text();
}
$("#output").text(listCSV);
$(".hiddenListInput").val(listCSV);
});
}
}
body {
font-family: verdana;
font-size: 12px;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
margin-bottom: 10px;
}
ol {
list-style-type: none;
}
.item {
height: 20px;
width: 180px;
margin: 5px;
padding: 5px;
border: 1px solid gray;
background-color: #cd8;
position: relative;
}
.item .closer {
position: absolute;
right: 5px;
top: 2px;
font: bold 14px arial;
color: #666;
padding: 1px 3px;
line-height: 1;
cursor: pointer;
display: none;
}
.item .closer:hover {
color: #000;
}
.placeholder {
height: 30px;
width: 195px;
margin: 5px;
background: #eee;
border: 1px dashed #999;
}
.placeholder .item {
margin: 0;
}
ol .item .closer {
display: block;
}
.highlight {
border: 1px solid red;
background: #fff;
}
.highlight .item {
opacity: 0.3;
}
.ui-draggable-dragging {
z-index: 99;
opacity: 1 !important;
}
.dropClass {
background-color: lightblue;
padding-left: 10px;
width: 180px;
border: 1px solid black;
border-radius: 8px;
margin-bottom: 5px;
}
.dropped {
display: inline;
}
.dif {
display: inline;
}
.numbr {
display: inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.0/jquery-ui.min.js" integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E=" crossorigin="anonymous"></script>
<h1 class="ui-widget-header">Products</h1>
<div id="myAccordion">
<h3>T-Shirts</h3>
<div>
<ul>
<li class="item"><span class="closer">x</span>Lolcat Shirt</li>
<li class="item"><span class="closer">x</span>Cheezeburger Shirt</li>
<li class="item"><span class="closer">x</span>Buckit Shirt</li>
</ul>
</div>
<h3>Bags</h3>
<div>
<ul>
<li class="item"><span class="closer">x</span>Zebra Striped</li>
<li class="item"><span class="closer">x</span>Black Leather</li>
<li class="item"><span class="closer">x</span>Alligator Leather</li>
</ul>
</div>
<h3>Gadgets</h3>
<div>
<ul>
<li class="item"><span class="closer">x</span>iPhone</li>
<li class="item"><span class="closer">x</span>iPod</li>
<li class="item"><span class="closer">x</span>iPad</li>
</ul>
</div>
</div>
<div class='proc'><pre>
<br /></pre>
<div class="projLeader">
<label>Box1. Required number:
<div class="numbr">10</div>.
<div class="dropped"></div>
<div class="dif">Difference:</div>
</label>
<div class="ui-widget-content">
<ol>
<li class="placeholder" name="projLeader"></li>
<input type="hidden" name="projLeader" class="hiddenListInput1" />
</ol>
</div>
</div>
</div>
<div class='proc'><pre>
<br /></pre>
<div class="projLeader">
<label>Box2. Required number:
<div class="numbr">5</div>.
<div class="dropped"></div>
<div class="dif">Difference:</div>
</label>
<div class="ui-widget-content">
<ol>
<li class="placeholder" name="projLeader"></li>
<input type="hidden" name="projLeader" class="hiddenListInput1" />
</ol>
</div>
</div>
</div>
<br/>
<input type="submit" id="savebutton" class="button" value="Save" onclick="userSubmitted = true;" />
<div id="output"></div>
It looks like you are using jQuery, which makes it really easy to manipulate the DOM dynamically.
Here is what I would do. First, add a difference div which will hold the difference of n and numbr:
<div id="numbr">10</div>
<div id="difference"></div>
And in your JS, calculate the difference and add it to the div:
var n = $(this).closest("div.proc").find(".dropClass").length - 1;
var difference = parseInt($('#numbr').text(), 10) - n;
if (difference >= 0) {
$('#difference').text('Difference ' + difference);
}
Do you mean that you can use a PHP variable in javascript. If that's the case, this is probably what you are looking for:
<?php
$myVariable = 200;
?>
<script type="text/javascript">
$(document).ready(function () {
var myvar = <?= $myVariable; ?>;
$(document).on('change', '.numbr', function () {
var number = parseInt($(this).text(), 10);
var difference = myvar - number;
$('.somediv').text($difference);
});
});
</script>
<div class="numbr">20</div>
To get the dropClass content, use the text() method. length will give you the number of nodes for the given selector, it's not what you want here.
You can get the numbr and dropClass content with the text() method.
Try this(added some html for the snippet to work):
inner = $('#innerproc').closest("div.proc");
numbr = $('#numbr').text();
n = inner.find(".dropClass").text();
inner.find("div.dropped").text("Items Dropped: " + (n - numbr) + ".");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="numbr">10</div>
<div class="proc">
<div id="innerproc"></div>
<div class="dropClass">21</div>
<div class="dropped"></div>
</div>

Jquery Drag to Delete

I am currently playing with some jquery and as i tried to create a simple todo-list I came across a problem.
So far the goal is to be able to add paragraphs by clicking the green square and remove them by clicking it once and then dragging it to the red square.
Everything works out fine except the deleting of the dragged paragraph.
Right now it only works by removing the whole class but I want to only delete the dragged one.
Here the code: https://codepen.io/anon/pen/OXXXpY
jQuery:
$(document).ready(function() {
var send = $("#send");
var dlt = $("#delete");
send.click(function() {
var input = $("input").val();
$("#container").prepend("<p class='entry'>" + input + "</p>");
});
$(document).on("click", ".entry", function() {
$(this).draggable();
$("#delete").droppable({
drop: function() {$(".entry").remove();}
});
});
});
Please don't mind my English and the real use of this project. This is just an jQuery experiment.
Use $(this) to target the dragged element
$(document).on("click", ".entry", function() {
var $this = $(this);
$(this).draggable();
$("#delete").droppable({
drop: function() {
$($this).remove();
}
});
});
$(document).ready(function() {
var send = $("#send");
var dlt = $("#delete");
send.click(function() {
var input = $("input").val();
$("#container").prepend("<p class='entry'>" + input + "</p>");
});
$(document).on("click", ".entry", function() {
var $this = $(this);
$(this).draggable();
$("#delete").droppable({
drop: function() { $($this).remove(); }
});
});
});
body {
text-align: center;
}
h1 {
font-family: Helvetica;
}
form input {
width: 500px;
font-size: 30px;
}
form input:focus {
outline: none;
}
.inline {
display: inline-block;
}
#send {
width: 40px;
height: 40px;
background-color: green;
}
#delete {
width: 40px;
height: 40px;
background-color: red;
}
.entry {
font-family: helvetica;
border: solid 1px grey;
-webkit-user-select: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<h1>ToDo</h1>
<form class="">
<div class="inline" id="delete"></div>
<input type="text" name="input" value="">
<div class="inline" id="send"></div>
</form>
<div id="container"></div>

How to delete element onclick

Playing with JavaScript, I have a search function which gets information from a database and then uses JavaScript to add the elements to my site in a box with a cross near the element. I am trying to make it so that when the user presses the X, near the element, they can remove it, if they made a mistake.
$('#addButton').on('click', function(event) {
var searchedValue = $('#search_term').val();
var divHolder = $('.selectedStuff');
$("<div>" + searchedValue + "</div>").css({
'background-color': 'yellow',
'width': '700px',
'margin-top': '10px',
'border-style': 'solid',
'border-color': '#0000ff'
}).appendTo(divHolder);
So, I tried certain methods, but I cant seem to get it to work. I have commented out the bit. Again, it's just when the user clicks on the X that element will be deleted.
You need to change your html because you can't bind click event with "::after" as it's is not html element. So rather then adding css on "::after" add span in place of that and apply CSS on it.
$(document).ready(function() {
$('.searchFunction').keyup(function(event) {
var search_term = $("#search_term").val();
$.post(document.location.href, {
search_term: search_term
}, function(data) {
$('.result').html(data);
});
});
$('.result').on('click', 'li', function(event) {
var result_value = $(this).text();
$('#search_term').val(result_value);
$('.result').html('');
});
$('#addButton').on('click', function(event) {
var searchedValue = $('#search_term').val();
var divHolder = $('.selectedStuff');
$("<div>" + searchedValue + "<span>X</span></div>").css({
'background-color': 'yellow',
'width': '700px',
'margin-top': '10px',
'border-style': 'solid',
'border-color': '#0000ff'
}).appendTo(divHolder);
$('.selectedStuff span').on("click", function(){
$(this).closest("div").remove();
});
});
});
.selectedStuff > div {
width: 300px;
}
.selectedStuff span {
font-family: Arial;
color: red;
position: relative;
float: right;
right: -20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name='search_term' id="search_term" class="searchFunction">
<input id="addButton" type="button" value="Add">
<div class="dropdown">
<ul class="result"></ul>
</div>
<div class="selectedStuff"></div>
<div id="markx"></div>
Based on your information I suggest you need use remove method:
$('.selectedStuff > div:after').on("click", function() {
$(element_to_delete).remove();
}
$('.selectedStuff > div:after').on("click", function() {
$(this).remove();
}
Check this answer: Only detect click event on pseudo-element
TL;DR You can't bind an event on pseudo-element, just insert x to the DOM (e.g. as a div) and bind event on it.
Add the x into another position, because you cannot detect events in pseudo-elements like :after.
X is put in the preferred position via css
Result: jsfiddle
$('#addButton').on('click', function( event ) {
var searchedValue = $('#search_term').val();
var divHolder = $('.selectedStuff');
$("<div ><div class='bar'>" + searchedValue + "</div><div class=\"close\">X</span></div>").css({
}).appendTo(divHolder);
$('.close').on("click", function() {
$(this).parent().remove();
});
});
});
.selectedStuff > div{
width:500px;
display: table-row;
}
.close{
display: table-cell;
font-family: Arial;
color: red;
position:relative;
right:-20px;
}
.bar{
background-color: yellow;
width: 400px;
margin-top: 10px;
border-style: solid;
border-color: #0000ff;
display: table-cell;
}

Categories