Delete certain - priorly unknown - part of a string in javascript - javascript

/**
* Created by Malal91 and Haziel
* Select multiple email by jquery.email_multiple
* **/
(function($){
$.fn.email_multiple = function(options) {
let defaults = {
reset: false,
fill: false,
data: null
};
let settings = $.extend(defaults, options);
let email = "";
return this.each(function()
{
$(this).after(
"<div class=\"all-mail\"></div>\n" +
"<input type=\"text\" name=\"email\" class=\"enter-mail-id\" placeholder=\"Enter Email ...\" />"
);
let $orig = $(this);
let $element = $('.enter-mail-id');
$element.keydown(function (e) {
$element.css('border', '');
if (e.keyCode === 13 || e.keyCode === 32) {
let getValue = $element.val();
if (/^[a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,6}$/.test(getValue)){
$('.all-mail').append('<span class="email-ids">' + getValue + '<span class="cancel-email">x</span></span>');
$(".cancel-email").attr("id", getValue);
$element.val('');
email += getValue + ','
} else {
$element.css('border', '1px solid red')
}
}
$orig.val(email.slice(0, -1))
});
$(document).on('click','.cancel-email',function(){
//crucial part
var valueToDelete = $(this).attr('id');
//alert(valueToDelete);
var current_value = $('#employee_email').val();
var new_value = current_value.replace(valueToDelete, '');
$('#employee_email').val(new_value);
$(this).parent().remove();
});
if(settings.data){
$.each(settings.data, function (x, y) {
if (/^[a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,6}$/.test(y)){
$('.all-mail').append('<span class="email-ids">' + y + '<span class="cancel-email">x</span></span>');
$element.val('');
email += y + ','
} else {
$element.css('border', '1px solid red')
}
})
$orig.val(email.slice(0, -1))
}
if(settings.reset){
$('.email-ids').remove()
}
return $orig.show()
//return $orig.hide()
});
};
})(jQuery);
span.email-ids {
float: left;
/* padding: 4px; */
border: 1px solid #ccc;
margin-right: 5px;
margin-bottom: 5px;
background: #f5f5f5;
padding: 3px 10px;
border-radius: 5px;
}
span.cancel-email {
border: 1px solid #ccc;
width: 18px;
display: block;
float: right;
text-align: center;
margin-left: 20px;
border-radius: 49%;
height: 18px;
line-height: 15px;
margin-top: 1px; cursor: pointer;
}
.email-id-row {
border: 1px solid #ccc;
}
.email-id-row input {
border: 0; outline:0;
}
span.to-input {
display: block;
float: left;
padding-right: 11px;
}
.email-id-row {
padding-top: 6px;
padding-bottom: 7px;
/*margin-top: 23px;*/
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input class="input_link" id="employee_email" type="text" placeholder="test field - see result" />
<script type="text/javascript">
//let user insert multiple emails
$(document).ready(function($){
let data = []
$("#employee_email").email_multiple({
data: data
})
});
</script>
</body>
</html>
I am currently facing some issues removing a certain part of a string of multiple emails. My current approach is to replace the value of the deleted email with an empty value; thus, I assigned each created delete button a unique id value in order to delete only this specific value. However, this does only work for the last inserted email.
The code is mainly from a js plugin which makes it easier to insert multiple emails in an input field (credits: multiple email plugin Created by Malal91 and Haziel).

Related

Keep Lines Containing

I am creating a "Keep Lines containing" project. I almost completed this task. But "Search Lines for" is working only 1 line. Multiple "Search
Lines for" is not working. I need "Search Lines for" in multiple lines.
All used HTML, CSS & javascript codes are here
I created a Codepen page for it. Please check : https://codepen.io/coderco/pen/LYGQyqr
function loadfile(fileid, loadid) {
document.getElementById(loadid).value = 'Loading...';
setTimeout(function() {
loadfile2(fileid, loadid)
}, 1000);
}
function loadfile2(fileid, loadid) {
if (!window.FileReader) {
document.getElementById(loadid).value = 'Your browser does not support HTML5 "FileReader" function required to open a file.';
} else {
fileis = document.getElementById(fileid).files[0];
var fileredr = new FileReader();
fileredr.onload = function(fle) {
var filecont = fle.target.result;
document.getElementById(loadid).value = filecont;
}
fileredr.readAsText(fileis);
}
}
function savefile(saveasid, saveid) {
if (!window.Blob) {
alert('Your browser does not support HTML5 "Blob" function required to save a file.');
} else {
var txtwrt = document.getElementById(saveid).value;
if (document.getElementById('dos').checked == true) txtwrt = txtwrt.replace(/\n/g, '\r\n');
var textblob = new Blob([txtwrt], {
type: 'text/plain'
});
var saveas = document.getElementById(saveasid).value;
var dwnlnk = document.createElement('a');
dwnlnk.download = saveas;
dwnlnk.innerHTML = "Download File";
if (window.webkitURL != null) {
dwnlnk.href = window.webkitURL.createObjectURL(textblob);
} else {
dwnlnk.href = window.URL.createObjectURL(textblob);
dwnlnk.onclick = destce;
dwnlnk.style.display = 'none';
document.body.appendChild(dwnlnk);
}
dwnlnk.click();
}
}
function destce(event) {
document.body.removeChild(event.target);
}
function cleartext() {
document.getElementById('input_output').value = '';
document.getElementById('removed').innerHTML = '';
document.getElementById('removed_box').value = '';
}
function SelectAll(id) {
document.getElementById(id).focus();
document.getElementById(id).select();
}
var fieldnum = 0;
var fieldtype = '';
var cacherem = 'no';
var enableregex = 'no';
function makeregexp() {
var regexpoutarr = new Array();
for (var x = 0; x < (fieldnum + 1); x++) {
regexpoutarr[x] = document.getElementById('addfield' + x).value.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
}
var regexpout = '';
if (fieldtype == 'AND') regexpout = '((?=.*' + regexpoutarr.join(')(?=.*') + ').*)';
if (fieldtype == 'OR') regexpout = '(' + regexpoutarr.join('|') + ')';
if (fieldtype == '') regexpout = document.getElementById('addfield0').value.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
return regexpout;
}
function removelines(whatlines) {
var textin = document.getElementById('input_output').value.replace(/\r/g, '');
var toremove = makeregexp();
var textinarr = textin.split('\n');
var textinarrcnt = textinarr.length;
var textoutarr = new Array();
var textoutarrcnt = 0;
var linesremovedcnt = 0;
var casen = 'i';
if (document.getElementById('case_sen').checked == true) casen = '';
if (enableregex == 'yes') toremove = document.getElementById('addfield0').value;
else toremove = makeregexp();
var killfun = 'no';
try {
var toremoveregx = new RegExp(toremove, casen);
} catch (err) {
alert('Something is incorrect (' + err + ') within your regular expression.\nBe sure special characters .*+?^=!:${}()|\\ used as literals have been escaped with a backslash.');
killfun = 'yes';
}
if (killfun == 'no') {
if (whatlines == 'containing' && cacherem == 'no') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == false) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else linesremovedcnt++;
}
}
if (whatlines == 'notcontaining' && cacherem == 'no') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == true) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else linesremovedcnt++;
}
}
var removedcachearr = new Array();
if (whatlines == 'containing' && cacherem == 'yes') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == false) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else {
removedcachearr[linesremovedcnt] = textinarr[x];
linesremovedcnt++;
}
}
}
if (whatlines == 'notcontaining' && cacherem == 'yes') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == true) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else {
removedcachearr[linesremovedcnt] = textinarr[x];
linesremovedcnt++;
}
}
}
var textout = textoutarr.join('\n');
document.getElementById('input_output').value = textout;
if (cacherem == 'yes') {
var removedcache = removedcachearr.join('\n');
document.getElementById('removed_box').value = removedcache;
}
document.getElementById('removed').innerHTML = '' + linesremovedcnt + ' removed / ' + textoutarrcnt + ' remain.';
}
}
function addfield(field) {
if (field == 'reset') {
document.getElementById('inputfields').innerHTML = '<input type="text" id="addfield0" value="" style="width:100%;" />'
document.getElementById('andbttn').style.display = 'inline-block';
document.getElementById('orbttn').style.display = 'inline-block';
fieldnum = 0;
fieldtype = '';
} else {
fieldnum++;
if (fieldnum == 1) {
if (field == 'andfield') {
document.getElementById('orbttn').style.display = 'none';
fieldtype = 'AND';
} else {
fieldtype = 'OR';
document.getElementById('andbttn').style.display = 'none';
}
}
var newfield = fieldtype + '<input type="text" id="addfield' + fieldnum + '" value="" style="width:100%;" />';
var newdiv = document.createElement('div');
newdiv.innerHTML = newfield;
document.getElementById('inputfields').appendChild(newdiv);
}
resizepage();
}
function disrem() {
var chkedstate = document.getElementById('dremoved').checked;
if (chkedstate == true) {
document.getElementById('removed_box').style.display = 'inline-block';
cacherem = 'yes';
} else {
cacherem = 'no';
document.getElementById('removed_box').value = '';
document.getElementById('removed_box').style.display = 'none';
}
resizepage();
}
function selectele(eleid) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(eleid));
range.select();
} else {
var range = document.createRange();
range.selectNode(document.getElementById(eleid));
window.getSelection().addRange(range);
}
}
function regexsrch() {
var chkedstate = document.getElementById('regex_srch').checked;
if (chkedstate == true) {
addfield('reset');
enableregex = 'yes';
document.getElementById('addfielddiv').innerHTML =
'<div style="padding:3px 0px 3px 0px;"><input type="checkbox" id="regex_srch" onclick="regexsrch();" CHECKED />Enable regular expression search. ' +
'Use <span id="catordog" style="color:#990000;" onclick="selectele(this.id)">(cat|dog|bird)</span> for cat OR dog OR bird. Use <span id="catanddog" style="color:#990000;" onclick="selectele(this.id)">((?=.*cat)(?=.*dog)(?=.*bird).*)</span> for cat AND dog AND bird. ' +
'Remember to escape special characters .*+?^=!:${}()|\\ with a backslash when used as literals within a regular expression. Use the <a target="_blank" href="" style="color:#0000FF;">Escape Literal Characters</a> tool. ' +
'Learn more about regular expressions visit <a rel="nofollow" target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" style="color:#0000FF;">developer.mozilla.org</a>.</div>';
} else {
document.getElementById('addfield0').value = '';
enableregex = 'no';
document.getElementById('addfielddiv').innerHTML =
'Add <input type="button" id="andbttn" value="AND" onClick="addfield(\'andfield\');" /> ' +
'<input type="button" id="orbttn" value="OR" onClick="addfield(\'orfield\');" /> search field. ' +
'<input type="button" value="Reset" onClick="addfield(\'reset\');" /> ' +
'<input type="checkbox" id="regex_srch" onclick="regexsrch();" />Enable regular expression search.';
}
resizepage();
}
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
padding: 0px;
font-family: arial;
font-size: 16px;
line-height: 1.7;
}
h1 {
display: block;
font-size: 18px;
font-weight: bold;
margin: 0px;
padding: 0px;
}
.se-for {
font-size: 27px;
font-weight: bold;
color: #b93207;
padding-top: 54px;
}
.contentt,
.wordd {
display: block;
margin: 0px;
padding: 8px 10px 8px 10px;
overflow: scroll;
font-family: arial;
font-size: 16px;
line-height: 1.7;
color: #000000;
background-color: #FFFFFF;
border: 1px solid #000000;
outline: none;
resize: none;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
border-radius: 4px 4px 4px 4px;
width: 100%;
font-size: 18px;
}
.contentt {
height: 400px;
overflow: auto;
}
.wordd {
height: 99px;
overflow: auto;
}
input {
display: inline-block;
height: 33px;
line-height: 1;
vertical-align: middle;
font-size: 16px;
outline: none;
resize: none;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
input::-moz-focus-inner {
border: 0;
padding: 0
}
input[type='radio'] {
width: 20px;
height: 20px;
vertical-align: middle;
margin: 0px;
padding: 0px;
font-size: 16px;
}
input[type='checkbox'] {
width: 20px;
height: 20px;
vertical-align: middle;
margin: 0px;
padding: 0px;
font-size: 16px;
}
input[type='text'] {
width: auto;
margin: 3px 0px 3px 0px;
padding: 0px 10px 0px 10px;
font-family: arial;
color: #000000;
background-color: #FFFFFF;
border: 1px solid #000000;
border-radius: 12px;
}
input[type='button'] {
width: auto;
margin: 3px 0px 3px 0px;
padding: 0px 10px 0px 10px;
font-family: arial;
font-weight: bold;
color: #000000;
border: 1px solid #000000;
background-color: #FFFFFF;
cursor: pointer;
border-radius: 5px;
background: #b93207;
color: #fff;
border: #b93207;
}
input[type='button']:hover {
color: #f9f900;
}
input[type='button']:hover {}
input[type='file'] {
width: 92px;
border-radius: 12px;
overflow: hidden;
padding: 0px;
margin: 0px 0px 0px -92px;
-moz-opacity: 0;
opacity: 0;
cursor: pointer;
}
input[type='file']::-webkit-file-upload-button {
cursor: pointer;
}
div {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
table {
border-collapse: collapse;
}
table,
td {
padding: 0px;
}
.buttonz {
width: 100%;
display: inline-block;
}
#menu {
position: absolute;
z-index: -1;
left: 0px;
top: 0px;
width: 0px;
height: 0%;
margin: 0px;
overflow: auto;
background-color: #E1E1D2;
border-right: 1px solid #000000;
}
div.navcat {
padding: 10px 0px 5px 12px;
font-size: 18px;
font-weight: bold;
font-style: italic;
}
div.navdiv {
height: 2px;
padding: 0px;
margin: 18px 10px 13px 10px;
background-color: #000000;
}
a.nav {
display: inline-block;
padding: 0px;
margin: 10px 0px 10px 10px;
text-decoration: underline;
color: #000000;
}
#toolpadding {
padding: 10px 10px 10px 10px;
}
#tool {
width: 1100px;
margin: 0px;
padding: 0px;
background-color: #fff;
margin: 0 auto;
}
<div id="tool">
<div id="toolpadding">
<div id="topdiv">
<div class="se-for">Search lines for:</div>
<div id="inputfields" style="padding-top:4px;">
<textarea type="text" id="addfield0" class="wordd">Three</textarea>
</div>
<div class="buttonz">
<input type="button" value="Keep Lines Containing" onClick="if(document.getElementById('addfield0').value!='') {removelines('notcontaining');}" />
<input type="checkbox" id="case_sen" />Case sensitive.
</div>
</div>
<div id="middiv" style="height:120px;">
<textarea id="input_output" class="contentt" wrap="off">
One One One One One One One One One One One One One One One
Three Three Three Three Three Three Three Three Three Three
Two Two Two Two Two Two Two Two Two Two Two Two Two Two Two
Two Two Two Two Two Two Two Two Two Two Two Two Two Two Two
Three Three Three Three Three Three Three Three Three Three
Three Three Three Three Three Three Three Three Three Three
Four Four Four Four Four Four Four Four Four Four Four Four
Five Five Five Five Five Five Five Five Five Five Five Five
Three Three Three Three Three Three Three Three Three Three
Five Five Five Five Five Five Five Five Five Five Five Five
Three Three Three Three Three Three Three Three Three Three
</textarea>
</div>
<div id="btmdiv">
<textarea id="removed_box" rows="4" style="display:none; width:100%; margin-top:10px;" wrap="off">
Removed Line Box - Removed/extracted lines will display here.</textarea>
</div>
</div>
</div>

Delete Row in table

My program basically displays books and other information about it. It also should be able to delete said book from the library and also the array in which it is stored. This is where my problem lies, I can't seem to delete that exact book from the display and the array. I tried using array.pop() and deleteRow(), but they only delete from the bottom. Thanks in advance for the help.
let myLibrary = [];
function book(name, author, pages, hasRead) {
this.name = name;
this.author = author;
this.pages = pages;
this.read = hasRead;
}
const Book1 = new book('Harry Potter', 'J. K. Rowling', 322, 'Yes');
const Book2 = new book('Great Expectations', 'Charles Dickens', 234, 'Yes');
const Book3 = new book('To Kill a Mockingbird', 'Harper Lee', 312, 'No')
const Book4 = new book('The Great Gatsby', 'F Scott Fitzgerald', 421, 'Yes');
const Book5 = new book('Ulysses', 'James Joyce', 267, 'Yes');
myLibrary.push(Book1, Book2, Book3, Book4, Book5);
function tableHeader() {
var html = "<table id=myTable1>";
html += "<tr>";
html += "<th class=top1>" + 'BOOK NAME'+ "</th>";
html += "<th class=top2>" + 'AUTHOR' + "</th>";
html += "<th class=top3>" + 'PAGES' + "</th>";
html += "<th class=top4>" + 'READ?' + "</th>";
html += "</tr>";
html += "</table>";
document.getElementById("top").innerHTML = html
}
tableHeader();
function viewLibrary() {
var html = "<table id=myTable>";
for (i = 0; i < myLibrary.length; i++) {
html += "<tr>";
html += "<td>" + [i+1] + "</td>";
html += "<td class=box1>" + myLibrary[i].name + "</td>";
html += "<td class=box2>" + myLibrary[i].author + "</td>";
html += "<td class=box3>" + myLibrary[i].pages + "</td>";
html += "<td class=box4>" + myLibrary[i].read + "</td>";
html += "<td class=del>" + 'X' + "</td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("box").innerHTML = html;
}
viewLibrary();
function deleteBook() {
var button = document.querySelectorAll('.del');
var table = document.getElementById('myTable');
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
button[i].addEventListener('click', function () {
table.deleteRow(this);
console.log(event);
myLibrary.pop();
})
}
}
deleteBook();
function addModal() {
var btn = document.getElementById("new-book");
var modal = document.getElementById("myModal");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function () {
modal.style.display = "block";
}
span.onclick = function () {
modal.style.display = "none";
}
}
addModal();
function addBookToLibrary() {
let name = document.getElementById('name').value;
let author = document.getElementById('author').value;
let pages = document.getElementById('pages').value;
let read = document.getElementById('dropdown').value;
var submit = document.getElementById("submit");
var modal = document.getElementById("myModal");
if (name === '' || author === '' || pages === '' || read === '') {
alert("Fill out all values.")
return false;
} else {
submit.onclick = function () {
modal.style.display = "none";
}
const NewBook = new book(name, author, pages, read);
myLibrary.push(NewBook);
console.log(NewBook);
viewLibrary();
document.getElementById('name').value = '';
document.getElementById('author').value = '';
document.getElementById('pages').value = '';
document.getElementById('dropdown').value = '';
deleteBook();
}
}
let x = document.querySelectorAll('button');
x.forEach(button => {
button.addEventListener('click', () => {
let selection = button.innerHTML;
switch (selection) {
case "Submit":
addBookToLibrary();
break;
}
})
})
body {
background-color: #edc4b3;
}
/* The Modal (background) */
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
}
/* Modal Content/Box */
.modal-content {
background-color: #eddcd2;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 40%;
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
table {
margin-left: 14.5%;
margin-top: 5%;
width: 70%;
background-color: #edddd4;
border: 5px solid #8d99ae;
border-collapse: collapse;
margin-top: 2%;
}
#top {
color: #9d6b53;
}
#box {
margin-top: -1.5%;
}
.line {
color: #774936;
}
td {
padding-bottom: 10px;
padding-top: 10px;
padding-left: 10px;
}
h1 {
text-align: center;
text-transform: uppercase;
font-family: 'Notable', sans-serif;
}
h2 {
text-align: center;
text-decoration: underline;
}
#new-book {
margin-left: 79%;
background-color: #888;
cursor: pointer;
margin-top: 2%;
padding: 5px 5px;
font-weight: bold;
}
/*tr:first-child { font-weight: bold }*/
#name, #author, #pages {
width: 60%;
border: 0;
border-bottom: 1px solid black;
font-size: 1rem;
color: black;
background-color: #eddcd2;
font-family: 'Times New Roman', Times, serif;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 2px;
padding-right: 2px;
}
td {
font-family: 'Source Code Pro', monospace;
}
#author {
width: 58.5%;
}
#pages {
width: 61.3%;
}
#dropdown {
width: 28%;
background-color: #edddd4;
font-size: 17px;
cursor: pointer;
box-sizing: border-box;
margin: 0;
border: 1px solid black;
padding-top: 5px;
padding-bottom: 5px;
}
#submit {
background-color: black;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
width: 30%;
margin-left: 35%;
}
input:focus,
select:focus,
textarea:focus,
button:focus {
outline: none;
}
.del {
color: red;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Library</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<button id='new-book'>Add Book</button>
<section id="top"></section>
<section id="box"></section>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<h2>Add a new book</h2>
<label for="name">Name of the Book:</label>
<input type="text" id="name" name="fname" required><br><br>
<label for="author">Name of the Author:</label>
<input type="text" id="author" name="lname" required><br><br>
<label for="pages">Number of Pages:</label>
<input type="number" id="pages" name="pname" required><br><br>
<p>Have you read this book?</p>
<select id="dropdown" required>
<option value="" disabled selected>Select your option</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select><br><br>
<button id="submit">Submit</button>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
I would suggest a different approach. Instead of creating your new elements through string concatenation and .innerHTML (which has performance and security implications), use the DOM API to create your new elements and then just attach an event handler to the dynamically created cells that contain the X.
See additional comments inline below:
let headers = ["name", "author", "pages", "read"];
// Get your DOM references just once, not every time
// your event handlers execute and make sure to always
// reference the DOM element, rather than a property
// of the DOM element. That way, if you ever decide
// that you need a different property value, you won't
// have to scan the DOM for the element reference again.
let box = document.getElementById("box");
var btn = document.getElementById("new-book");
var modal = document.getElementById("myModal");
let closeModal = document.querySelector("span.close");
let name = document.getElementById('name');
let author = document.getElementById('author');
let pages = document.getElementById('pages');
let read = document.getElementById('dropdown');
var submit = document.getElementById("submit");
var modal = document.getElementById("myModal");
// DO NOT USE GETELEMENTSBYCLASSNAME and especially
// pass an idex to the first element within it:
// var span = document.getElementsByClassName("close")[0];
// Read this for details: https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474
// Instead, use .querySelector()
var span = document.querySelector(".close");
// Bind the "buttons" that show/hide the modal
// to a common function that does that.
btn.addEventListener('click', showHideModal);
closeModal.addEventListener('click', showHideModal);
function showHideModal(){
// No need for if/then. Just toggle the use of
// the .hidden CSS class
modal.classList.toggle("hidden");
}
submit.addEventListener('click', addBookToLibrary);
function book(name, author, pages, hasRead) {
this.name = name;
this.author = author;
this.pages = pages;
this.read = hasRead;
}
// No need to create variables to store new book references,
// and then push them into the Array. Just put the new books
// directly into the new Array.
let myLibrary = [
new book('Harry Potter', 'J. K. Rowling', 322, 'Yes'),
new book('Great Expectations', 'Charles Dickens', 234, 'Yes'),
new book('To Kill a Mockingbird', 'Harper Lee', 312, 'No'),
new book('The Great Gatsby', 'F Scott Fitzgerald', 421, 'Yes') ,
new book('Ulysses', 'James Joyce', 267, 'Yes')
];
function makeLibrary() {
// Get rid of the prior table (if exists)
if(document.getElementById("myTable")){
document.getElementById("myTable").remove();
}
// Instead of creating concatenated strings of HTML, which gets
// messy and hard to maintain, create DOM objects and set their
// propeties.
let tbl = document.createElement("table");
tbl.id = "myTable";
for (i = 0; i < myLibrary.length; i++) {
let row = document.createElement("tr");
let numCell = document.createElement("td");
numCell.textContent = i + 1;
row.appendChild(numCell);
// Loop over the headers array to build the row cells
headers.forEach(function(header, index){
let cell = document.createElement("td");
cell.textContent = myLibrary[i][header];
cell.classList.add("box" + (index + 1));
row.appendChild(cell); // Add the cell to the row
});
let delCell = document.createElement("td");
delCell.textContent = "X";
delCell.classList.add("del");
// Because the elements are now being created as elements
// and not strings, you can set up even binding on them.
delCell.addEventListener("click", function(){
myLibrary.splice(i, 1); // Remove book from library
this.closest("tr").remove(); // Remove row
});
row.appendChild(delCell); // Add cell to row
tbl.appendChild(row); // Add row to table
box.appendChild(tbl); // Add table to section
}
}
makeLibrary();
function addBookToLibrary() {
if (name.value === '' || author.value === '' || pages.value === '' || read.value === '') {
alert("Fill out all values.")
return false;
} else {
myLibrary.push(new book(name.value, author.value, pages.value, read.value));
makeLibrary();
name.value = '';
author.value = '';
pages.value = '';
dropdown.value = '';
showHideModal();
}
}
body {
background-color: #edc4b3;
}
/* Added classes */
h1.addBook { font-size: 1em; }
.hidden { display:none; }
/* The Modal (background) */
.modal {
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
}
/* Modal Content/Box */
.modal-content {
background-color: #eddcd2;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 40%;
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
table {
margin-left: 14.5%;
margin-top: 5%;
width: 70%;
background-color: #edddd4;
border: 5px solid #8d99ae;
border-collapse: collapse;
margin-top: 2%;
}
#top {
color: #9d6b53;
}
#box {
margin-top: -1.5%;
}
.line {
color: #774936;
}
td {
padding-bottom: 10px;
padding-top: 10px;
padding-left: 10px;
}
h1 {
text-align: center;
text-transform: uppercase;
font-family: 'Notable', sans-serif;
}
h2 {
text-align: center;
text-decoration: underline;
}
#new-book {
margin-left: 79%;
background-color: #888;
cursor: pointer;
margin-top: 2%;
padding: 5px 5px;
font-weight: bold;
}
/*tr:first-child { font-weight: bold }*/
#name, #author, #pages {
width: 60%;
border: 0;
border-bottom: 1px solid black;
font-size: 1rem;
color: black;
background-color: #eddcd2;
font-family: 'Times New Roman', Times, serif;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 2px;
padding-right: 2px;
}
td {
font-family: 'Source Code Pro', monospace;
}
#author {
width: 58.5%;
}
#pages {
width: 61.3%;
}
#dropdown {
width: 28%;
background-color: #edddd4;
font-size: 17px;
cursor: pointer;
box-sizing: border-box;
margin: 0;
border: 1px solid black;
padding-top: 5px;
padding-bottom: 5px;
}
#submit {
background-color: black;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
width: 30%;
margin-left: 35%;
}
input:focus,
select:focus,
textarea:focus,
button:focus {
outline: none;
}
.del {
color: red;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Library</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<button id='new-book'>Add Book</button>
<section id="top">
<!-- If you have static bits of HTML, don't create them
dynamically in JavaScript, go ahead and hard-code them
into the HTML. This will reduce the amount of JavaScript
and improve the speed of the page load. -->
<table id="myTable1">
<tr>
<th class="top1">BOOK NAME</th>
<th class=top2>AUTHOR</th>
<th class=top3>PAGES</th>
<th class=top4>READ?</th>
</tr>
</table>
</section>
<section id="box"></section>
<div id="myModal" class="modal hidden">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<!-- You can't have an H2 if it's not a child of an H1.
Don't choose a heading because of how it looks, pick
it because it represents the right heading level and
then style it with CSS. -->
<h1 class="addBook">Add a new book</h1>
<label for="name">Name of the Book:</label>
<input type="text" id="name" name="fname" required><br><br>
<label for="author">Name of the Author:</label>
<input type="text" id="author" name="lname" required><br><br>
<label for="pages">Number of Pages:</label>
<input type="number" id="pages" name="pname" required><br><br>
<p>Have you read this book?</p>
<select id="dropdown" required>
<option value="" disabled selected>Select your option</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select><br><br>
<button id="submit">Submit</button>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
function deleteBook() {
var button = document.querySelectorAll('.del');
var table = document.getElementById('myTable');
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
button[i].addEventListener('click', function () {
table.deleteRow(i);
// I think pop will delete only the last element.
myLibrary.splice(i, 1);
})
}
}
this in table.deleteRow(this) refers to a HTMLTableCellElement.
According to this doc : https://www.w3schools.com/jsreF/met_table_deleterow.asp
You'll need to pass an index instead.
Edit :
What about adding a data-row attribute to your rows where you put the index, and then getting this index by using element.dataset.row
E.G :
var html = "<table id=myTable1>";
html += "<tr data-row=" + $yourIndex + ">";
html += "<th class=top1>" + 'BOOK NAME'+ "</th>";
html += "<th class=top2>" + 'AUTHOR' + "</th>";
html += "<th class=top3>" + 'PAGES' + "</th>";
html += "<th class=top4>" + 'READ?' + "</th>";
html += "</tr>";
html += "</table>";
Use Splice to remove the element from the array. Use this link for your reference.
your way of explanation is a little bit vague to understand.

How can I send form_id to javascript function as a parameter?

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Başlıksız Belge</title>
<style>
body
{
font-family: Open sans, Helvetica;
background: #111;
color: white;
font-size: 16px;
}
h1
{
font-weight: lighter;
}
small
{
color: firebrick;
}
div.checkbox_select
{
width: 200px;
}
.checkbox_select_anchor
{
display: block;
background: firebrick;
color: white;
cursor: pointer;
padding: 10px 5px 5px;
position: relative;
}
.checkbox_select_anchor:after
{
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 10px solid darkred;
content: "";
position: absolute;
right: 10px;
top: 15px;
}
.expanded .checkbox_select_anchor:after
{
border-top: 0;
border-bottom: 10px solid firebrick;
}
.checkbox_select_anchor:hover
{
background: #FF3030 !important;
}
.expanded .checkbox_select_anchor
{
background: #7C1818;
}
div.checkbox_select .select_input
{
width: 100%;
cursor: pointer;
}
.checkbox_select_dropdown
{
display: none;
background: whitesmoke;
}
.checkbox_select_dropdown.show
{
display: block;
}
.checkbox_select_dropdown ul
{
max-height: 150px;
overflow-y: scroll;
overflow-x: hidden;
padding: 0;
margin: 0;
border: 1px solid #999;
border-top: 0;
border-bottom: 0;
}
.checkbox_select_dropdown ul li
{
list-style: none;
position: relative;
color: #666;
}
.checkbox_select_dropdown ul li label
{
position: relative;
padding: 10px 5px 5px 40px;
display: block;
cursor: pointer;
}
.checkbox_select_dropdown ul li label:hover
{
background: #cbcbcb;
color: white;
}
.checkbox_select_dropdown ul li input:checked + label
{
background: #bbb;
color: white;
text-shadow: 0px 1px 1px rgba(150, 150, 150, 1);
}
.checkbox_select_dropdown ul li input
{
position: absolute;
left:0;
z-index:1;
display: inline-block;
height: 100%;
width: 30px;
}
.checkbox_select_search
{
width: 200px;
padding: 10px 5px 5px;
border: 1px solid #999;
border-top: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.checkbox_select_submit
{
background: #00A600;
color: white;
padding: 10px 5px 5px;
border: 0;
width: 100%;
font-size: 14px;
cursor: pointer;
}
.hide
{
display: none;
}
</style>
</head>
<body>
<h1>multiselect</h1>
//here I have an form id and it is used javascript function
<form id="make_checkbox_select">
<select name="Cinsiyet">
<option data-count="(2)" value="Kadin">Kadın </option>
<option data-count="(23)" value="erkek">Erkek </option>
</select>
<input type="submit" />
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(function()
{
var mySelectCheckbox = new checkbox_select(
{
selector : "#make_checkbox_select",
selected_translation : "seçildi",
all_translation : "Tamamı Seçildi",
not_found : "Bulunamadı",
// Event during initialization
onApply : function(e)
{
alert("Custom Event: " + e.selected);
}
});
});
// variable_names
// functionNames
// CONSTANT_VARIABLE_NAMES
// $_my_jquery_selected_element
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function()
{
return this.replace(/^\s+|\s+$/g, '');
}
}
var checkbox_select = function(params)
{
// Error handling first
// ----------------------------------------------------------------------------------------------------
var error = false;
// If the selector is not given
if(!params.selector) { console.error("selector needs to be defined"); error = true; }
// If the selector is not a string
if(typeof params.selector != "string") { console.error("selector needs to be a string"); error = true; }
// If the element is not a form
if(!$(params.selector).is("form")) { console.error("Element needs to be a form"); error = true; }
// If the element doesn't contain a select
if($(params.selector).find("select").length < 1) { console.error("Element needs to have a select in it"); error = true; }
// If the element doesn't contain option elements
if($(params.selector).find("option").length < 1) { console.error("Select element needs to have an option in it"); error = true; }
// If the select element doesn't have a name attribute
if($(params.selector).find('select').attr('name') == undefined) { console.error("Select element needs to have a name attribute"); error = true; }
// If there was an error at all, dont continue in the code.
if(error)
return false;
// ----------------------------------------------------------------------------------------------------
var that = this,
$_native_form = $(params.selector),
$_native_select = $_native_form.find('select'),
// Variables
selector = params.selector,
select_name = $_native_select.attr('name').charAt(0).toUpperCase() + $_native_select.attr('name').substr(1),
selected_translation = params.selected_translation ? params.selected_translation : "selected",
all_translation = params.all_translation ? params.all_translation : "All " + select_name + "s",
not_found_text = params.not_found ? params.not_found : "No " + select_name + "s found.",
currently_selected = [],
// Create the elements needed for the checkbox select
$_parent_div = $("<div />") .addClass("checkbox_select"),
$_select_anchor = $("<a />") .addClass("checkbox_select_anchor") .text( select_name ),
$_search = $("<input />") .addClass("checkbox_select_search"),
$_submit = $("<input />") .addClass("checkbox_select_submit") .val("Apply") .attr('type','submit') .data("selected", ""),
$_dropdown_div = $("<div />") .addClass("checkbox_select_dropdown"),
$_not_found = $("<span />") .addClass("not_found hide") .text(not_found_text),
$_ul = $("<ul />"),
updateCurrentlySelected = function()
{
var selected = [];
$_ul.find("input:checked").each(
function()
{
selected.push($(this).val());
}
);
currently_selected = selected;
if(selected.length == 0)
{
$_select_anchor.text( select_name )
}
else if(selected.length == 1)
{
$_select_anchor.text( selected[0] + " " + selected_translation );
}
else if(selected.length == $_ul.find("input[type=checkbox]").length)
{
$_select_anchor.text( all_translation );
}
else
{
$_select_anchor.text( selected.length + " " + selected_translation );
}
},
// Template for the li, will be used in a loop.
createItem = function(name, value, count)
{
var uID = 'checkbox_select_' + select_name + "_" + name.replace(" ", "_"),
$_li = $("<li />"),
$_checkbox = $("<input />").attr(
{
'name' : name,
'id' : uID,
'type' : "checkbox",
'value' : value
}
)
.click(
function()
{
updateCurrentlySelected();
}
),
$_label = $("<label />").attr('for', uID),
$_name_span = $("<span />").text(name).prependTo($_label),
$_count_span = $("<span />").text(count).appendTo($_label);
return $_li.append( $_checkbox.after( $_label ) );
},
apply = function()
{
$_dropdown_div.toggleClass("show");
$_parent_div.toggleClass("expanded");
if(!$_parent_div.hasClass("expanded"))
{
// Only do the Apply event if its different
if(currently_selected != $_submit.data("selected"))
{
$_submit.data("selected" , currently_selected);
that.onApply(
{
selected : $_submit.data("selected")
}
);
}
}
};
// Event of this instance
that.onApply = typeof params.onApply == "function" ?
params.onApply :
function(e)
{
//e.selected is accessible
};
that.update = function()
{
$_ul.empty();
$_native_select.find("option").each(
function(i)
{
$_ul.append( createItem( $(this).text(), $(this).val(), $(this).data("count") ) );
}
);
updateCurrentlySelected();
}
that.check = function(checkbox_name, checked)
{
//$_ul.find("input[type=checkbox][name=" + trim(checkbox_name) + "]").attr('checked', checked ? checked : false);
$_ul.find("input[type=checkbox]").each(function()
{
// If this elements name is equal to the one sent in the function
if($(this).attr('name') == checkbox_name)
{
// Apply the checked state to this checkbox
$(this).attr('checked', checked ? checked : false);
// Break out of each loop
return false;
}
});
updateCurrentlySelected();
}
// Build mark up before pushing into page
$_dropdown_div .prepend($_search);
$_dropdown_div .append($_ul);
$_dropdown_div .append($_not_found);
$_dropdown_div .append($_submit);
$_dropdown_div .appendTo($_parent_div);
$_select_anchor .prependTo($_parent_div);
// Iterate through option elements
that.update();
// Events
// Actual dropdown action
$_select_anchor.click(
function()
{
apply();
}
);
// Filters the checkboxes by search on keyup
$_search.keyup(
function()
{
var search = $(this).val().toLowerCase().trim();
if( search.length == 1 )
{
$_ul.find("label").each(
function()
{
if($(this).text().toLowerCase().charAt(0) == search.charAt(0))
{
if($(this).parent().hasClass("hide"))
$(this).parent().removeClass("hide");
if(!$_not_found.hasClass("hide"))
$_not_found.addClass("hide");
}
else
{
if(!$(this).parent().hasClass("hide"))
$(this).parent().addClass("hide");
if($_not_found.hasClass("hide"))
$_not_found.removeClass("hide");
}
}
);
}
else
{
// If it doesn't contain
if($_ul.text().toLowerCase().indexOf(search) == -1)
{
if($_not_found.hasClass("hide"))
$_not_found.removeClass("hide");
}
else
{
if(!$_not_found.hasClass("hide"))
$_not_found.addClass("hide");
}
$_ul.find("label").each(
function()
{
if($(this).text().toLowerCase().indexOf(search) > -1)
{
if($(this).parent().hasClass("hide"))
$(this).parent().removeClass("hide");
}
else
{
if(!$(this).parent().hasClass("hide"))
$(this).parent().addClass("hide");
}
}
);
}
}
);
$_submit.click(
function(e)
{
e.preventDefault();
apply();
}
);
// Delete the original form submit
$(params.selector).find('input[type=submit]').remove();
// Put finalized markup into page.
$_native_select.after($_parent_div);
// Hide the original element
$_native_select.hide();
};
</script>
</html>
/I want to use more than one form_id so I will send different paramaters to function. In the function we have selector:"#make_checkbox_select" it takes form id with # sign. And I want to send a parameter to it. I tried to
fucntion(id)
{selector: id,
.........
}
but it doesn't work.
How I can use this function for using 3 multiselect checkbox?/
This is the simple example - how you can pass parameter to the form submit handler:
var onFormSubmit = function(formId) {
alert('submit: id = ' + formId);
}
<form id="form1" onsubmit="onFormSubmit('form1')">
<input type="text" name="inputText" value="text1"/>
<button type="submit">Submit form1</button>
</form>
<form id="form2" onsubmit="onFormSubmit('form2')">
<input type="text" name="inputText" value="text2"/>
<button type="submit">Submit form2</button>
</form>

How do I call a class function from an event listener internally?

I'm trying to build up my JavaScript knowledge base and am having difficulty with calling a function within my class when an event is fired from the class object's textbox. I think this is going to be related to a scope issue, but I'm not entirely sure. Doing this in C# was much, much easier.
class FilterableDropdown {
constructor(containerID) {
this.ContainerID = containerID;
this.Container = document.getElementById(containerID);
this.Container.innerHTML += '<input type="text" id="txt-' + containerID + '-dropdown" />'
// Add sub-controls.
this.Textbox = document.getElementById("txt-" + containerID + "-dropdown");
// Add events to sub-controls.
this.Textbox.addEventListener("keyup", this.Filter);
}
Filter() {
alert(this.ContainerID);
}
}
var dropdown = new FilterableDropdown("fd-test");
.filterable-dropdown > input[type=text] {
padding: 5px;
border: none;
border-bottom: 2px solid #333;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
background-color: #3332;
color: #eee;
}
.filterable-dropdown > input[type=text]:focus { background-color: #3338; }
*:focus { outline: none; }
<div id="fd-test" class="filterable-dropdown"></div>
In order to replicate the issue, simply type any character into the textbox to raise the keyup event. This will cause an alert to display undefined.
Why is this.ContainerID returning as undefined here?
I believe this is due to a scoping issue.
How do I call a function within my class on a sub-control's event?
You need to bind the this to the Filter method. The this should point to the class instance.
That can be achieved by using Array.prototype.bind(thisContext) where the thisContext would be your class FilterableDropdown instance:
class FilterableDropdown {
constructor(containerID) {
this.ContainerID = containerID;
this.Container = document.getElementById(containerID);
this.Container.innerHTML += '<input type="text" id="txt-' + containerID + '-dropdown" />'
// Add sub-controls.
this.Textbox = document.getElementById("txt-" + containerID + "-dropdown");
// Bind this to the Filter method
this.Textbox.addEventListener("keyup", this.Filter.bind(this));
}
Filter() {
alert(this.ContainerID);
}
}
var dropdown = new FilterableDropdown("fd-test");
.filterable-dropdown > input[type=text] {
padding: 5px;
border: none;
border-bottom: 2px solid #333;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
background-color: #3332;
color: #eee;
}
.filterable-dropdown > input[type=text]:focus { background-color: #3338; }
*:focus { outline: none; }
<div id="fd-test" class="filterable-dropdown"></div>
What you will want to do is bind the method to the class using
this.Textbox.addEventListener("keyup", this.Filter.bind(this));
class FilterableDropdown {
constructor(containerID) {
this.ContainerID = containerID;
this.Container = document.getElementById(containerID);
this.Container.innerHTML += '<input type="text" id="txt-' + containerID + '-dropdown" />'
// Add sub-controls.
this.Textbox = document.getElementById("txt-" + containerID + "-dropdown");
// Add events to sub-controls.
this.Textbox.addEventListener("keyup", this.Filter.bind(this));
}
Filter() {
alert(this.ContainerID);
}
}
var dropdown = new FilterableDropdown("fd-test");
.filterable-dropdown > input[type=text] {
padding: 5px;
border: none;
border-bottom: 2px solid #333;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
background-color: #3332;
color: #eee;
}
.filterable-dropdown > input[type=text]:focus { background-color: #3338; }
*:focus { outline: none; }
<div id="fd-test" class="filterable-dropdown"></div>

Why Append in JQuery does repeat in span? i want no repeat for tags

i want to no repeat the tags that i will writing in field i try but the console appears the span value repeat like this in image how can i fix that to not repeat the tags. i used JQuery
s://i.stack.imgur.com/dIVP1.jpg
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="add-tags" type="text" placeholder="Type Your Tags">
<div class="tags"></div>
</div>
<script>
$('.add-tags').on('keyup', function(e) {
var tagsKey = e.keyCode || e.which;
if (tagsKey === 188) {
var thisValue = $(this).val().slice(0, -1); //remove last letter
$('.tags').append('<span class="tags-span"><i class="fa fa-times"></i>' + thisValue + '</span>');
var spanvalue = $('.tags-span').text();
console.log(spanvalue);
if (thisValue === spanvalue) {
console.log('good');
} else {
console.log('bad');
}
$(this).val('');
}
$('.tags').on('click', '.tags-span i', function() {
$(this).parent('.tags-span').remove();
});
});
</script>
Voila!
I have a gift for you, but first I would like to point out, that next time you should invest more time into the preparation of your question. Don't cry, don't beg, start from doing your homework first and get as much information as you can. Stackoverflow is not a place were people will do you job for you.
Right now, one can only guess what you are really trying to achieve.
After some harsh treatment let's go to the good parts:
In the following example (https://jsfiddle.net/mkbctrlll/xb6ar2n1/95/)
I have made a simple input that creates a tag on a SPACE key hit. Each tag could be easily removable if X is clicked.
HTML:
<form class="wrapper">
<label for="test">
<span id="tags">
Tags:
</span>
<input id="test" type="text" >
</label>
</form>
JS:
var tagsCollection = []
document.body.onkeyup = function(e){
if(e.keyCode == 32){
var content = getContent('#test')
console.log(tagsCollection.indexOf(content))
if(tagsCollection.indexOf(content) === -1) {
console.log('Spacebar hit! Creating tag')
createTag(content)
tagsCollection.push(content)
console.log(tagsCollection)
} else {
console.log('We already have this one sir!')
displayError('Whoops! Looks like this tag already exists... )')
}
}
}
$('.wrapper').on('click', function(event) {
$(event.target).closest('.tag').remove()
})
function displayError(content) {
var error = document.createElement('p')
error.classList.add('error')
error.innerHTML = content
document.querySelector('.wrapper').append(error)
}
function getContent(target) {
var value = $(target).val().replace(/\W/g, '')
$(target).val("")
return value
}
function createTag(content) {
var $tags = $('#tags')
var tag = document.createElement('span')
var closeIcon = '×'
var iconHTML = document.createElement('span')
iconHTML.classList.add('remove')
iconHTML.innerHTML = closeIcon
tag.classList.add('tag')
tag.append(iconHTML)
tag.append(content)
$tags.append(tag)
}
function removeTag(target) {
target.remove()
}
CSS:
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
.wrapper {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
#tags {
display: block;
margin-bottom: 10px;
font-size: 14px;
}
#test {
display: block;
width: 100%;
}
.tag {
border-radius: 16px;
background-color: #ccc;
color: white;
font-size: 12px;
padding: 4px 6px 4px 16px;
position: relative;
}
.tag:not(:last-child) {
margin-right: 4px;
}
.remove {
font-weight: 600;
position: absolute;
top: 50%;
left: 6px;
cursor: pointer;
transform: translateY(-50%);
}
.remove:hover {
color: red;
}
It is just a quick and dirty example, not a production lvl code.

Categories