I am trying to select an attribute in a parent div, but no luck so far.
The HTML:
<div class="build">
<div class="items">
<div class="craft shop" qnt="1"></div>
<div class="craft shop" qnt="5"></div>
</div>
</div>
The JS:
var ITEMS = [
{
"item":"shop",
"prefix":"custom",
"icon": "shop",
"type": "shop"}];
for (var i = 0; i < ITEMS.length; i++)
{
var items = ITEMS[i];
var quantity = $(".craft." + items['item']).attr("qnt");
$(".craft." + items['item']).html
('<a class="item-block item-' + items['type'] + '" href="' + items['prefix'] + '-' + items['item'] + '.html">'+
'<i class="' + items['icon'] + '"></i>' +
'<span class="name" data-i18n="' + items['item'] + '">' + items['item'] + '</span>'+
'<span class="qnt">x' + quantity +'</span>'+
'</a>')};
So when I use <div class="craft shop" qnt="1"></div> it generates this:
<div class="craft shop" qnt="1">
<a class="item-block item-shop" href="custom-shop.html">
<i class="shop"></i><span class="name" data-i18n="shop">shop</span>
<span class="qnt">x1</span>
</a>
</div>
<div class="craft shop" qnt="5">
<a class="item-block item-shop" href="custom-shop.html">
<i class="shop"></i><span class="name" data-i18n="shop">shop</span>
<span class="qnt">x5</span>
</a>
</div>
I am trying to display the quantity from the attribute "qnt", but I am having problems to select it.
See how the second block uses the same qunatity of the first one?
I already tried:
var quantity = $(this).parent().parent().attr("qnt");
and it didn't worked.
Example in codepen: https://codepen.io/RHenri/pen/BWNVpw
Basically you need a another loop to select a particular instance at time. So that you can apply quantity and other values based on that particular div.
You are using $(".craft." + items['item']).attr("qty") to get value of qty attribute from a div which always return first div that match that class name. And then you again using that name to set html to all div which added same html content to all matching div with that particular name.
To get valve from each div and add html accordingly you need another loop to go through all element that are selected by a particular class name.
For this i am using $.each()
Try this.
var ITEMS = [{
"item": "shop",
"prefix": "custom",
"icon": "shop",
"type": "shop"
}];
for (var i = 0; i < ITEMS.length; i++) {
var items = ITEMS[i];
var quantity = $(".craft." + items['item']).data("qnt");
$(".craft." + items['item']).each(function(i, v) {
var quantity = $(this).data("qnt");
$(this).html('<a class="item-block item-' + items['type'] + '" href="' + items['prefix'] + '-' + items['item'] + '.html">' +
'<i class="' + items['icon'] + '"></i>' +
'<span class="name" data-i18n="' + items['item'] + '">' + items['item'] + '</span>' +
'<span class="qnt">x' + quantity + '</span>' +
'</a>')
});
};
.item-list .item-block,
.build .item-block {
display: block;
color: #fff;
margin: 0px;
padding: 0px;
box-shadow: 0 0 6px rgba(0, 0, 0, 0.50);
cursor: pointer;
min-width: 220px;
text-align: center;
width: 300px;
}
.item-list .items .item-block i,
.build .items .item-block i {
width: 32px;
height: 32px;
background-size: contain;
float: left;
}
.item-list .item-block .name,
.build .item-block .name {
display: inline-block;
font-family: 'Roboto', Microsoft YaHei;
font-size: 12px;
line-height: 32px;
color: #fff;
padding: 0 5px;
width: 135px;
text-align: center;
}
.item-list .items .item-block i,
.build .items .item-block i {
width: 32px;
height: 32px;
background-size: contain;
float: left;
}
.none {
display: none;
}
.item-list .item-block .qnt,
.build .item-block .qnt {
line-height: 32px;
display: inline-block;
color: #ffffff;
font-family: 'Roboto', Microsoft YaHei;
font-weight: 400;
padding: 0px 10px 0px 0px;
float: right;
}
.item-shop {
background-color: #1e7ea9;
}
.shop {
background-image: url(http://icons.iconarchive.com/icons/paomedia/small-n-flat/64/shop-icon.png);
background-color: #25a9ae;
}
.craft {
background-image: none;
display: inline-block;
width: 300px;
margin: 0 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="build">
<div class="items">
<div class="craft shop" data-qnt="1"></div>
<div class="craft shop" data-qnt="5"></div>
</div>
</div>
Related
Im making an user generated music playlist. The user drops files / adds files with the button.
However, whenever more files are dropped / added, the previously added files are replaced.
How to modify code to append the files with the previously added files?
PS:
I have used jquery to build the app. I have used jquery, cos i want to work with audio time duration(to find total playtime of the playlist, etc) and its a bit difficult to accomplish that with vanillaJS.
var dropZoneId = "drop-zone";
var buttonId = "clickHere";
var mouseOverClass = "mouse-over";
var dropZone = $("#" + dropZoneId);
var inputFile = dropZone.find("input");
var finalFiles = {};
var objectUrl;
// Function
$(function() {
var ooleft = dropZone.offset().left;
var ooright = dropZone.outerWidth() + ooleft;
var ootop = dropZone.offset().top;
var oobottom = dropZone.outerHeight() + ootop;
document.getElementById(dropZoneId).addEventListener("dragover", function(e) {
e.preventDefault();
e.stopPropagation();
dropZone.addClass(mouseOverClass);
var x = e.pageX;
var y = e.pageY;
if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
inputFile.offset({
top: y - 15,
left: x - 100
});
} else {
inputFile.offset({
top: -400,
left: -400
});
}
}, true);
if (buttonId != "") {
var clickZone = $("#" + buttonId);
var oleft = clickZone.offset().left;
var oright = clickZone.outerWidth() + oleft;
var otop = clickZone.offset().top;
var obottom = clickZone.outerHeight() + otop;
$("#" + buttonId).mousemove(function(e) {
var x = e.pageX;
var y = e.pageY;
if (!(x < oleft || x > oright || y < otop || y > obottom)) {
inputFile.offset({
top: y - 15,
left: x - 160
});
} else {
inputFile.offset({
top: -400,
left: -400
});
}
});
}
document.getElementById(dropZoneId).addEventListener("drop", function(e) {
$("#" + dropZoneId).removeClass(mouseOverClass);
}, true);
// FILE
inputFile.on('change', function(e) {
finalFiles = {};
$('#filename').html("");
var fileNum = this.files.length,
initial = 0,
counter = 0;
$.each(this.files, function(idx, elm) {
finalFiles[idx] = elm;
});
for (initial; initial < fileNum; initial++) {
counter = counter + 1;
// Object URL
var file = e.currentTarget.files[initial];
objectUrl = URL.createObjectURL(file);
$("#filename").prop("src", objectUrl);
//console.log('Object URL: ', objectUrl);
//console.log('FILE: ', file);
// Object URL End
//$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + ' <span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span></div>');
//$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + ' <span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span></div>');
$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file-audio-o"></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + '</strong></span> ' + '<audio controls controlsList="nodownload noplaybackrate" preload="auto" id="audioFiles" >' + '<source src="' + objectUrl + '" type="audio/mpeg" />' + '</audio>' + '<span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span> ' + this.files[initial].name + '</div>');
//$('#filename').append('<div class="playlist draggable" id="file_' + initial + '">' + '<audio controls id="audioFiles" >' + '<source src="' + objectUrl + '/' + this.files[initial].name + '" type="audio/mpeg" />' + '</audio>' + '</div>');
console.log('NAME: ', this.files[initial].name);
//console.log('INITIAL: ', this.files[initial]);
// Audio Duration
var Duration;
$(audioFiles).on("canplay", function() {
console.log('THIS DURATION: ', this.duration);
Duration = this.duration;
});
// Audio Duration End
}
// Total File Count
var count = $('#filename').children().length;
console.log('Number of files: ', count);
$('#totalFiles').css("display", "initial");
$('#totalFiles').html('<font style="color:#06a7e5">Files Uploaded: ' + '<b>' + count + '</b>' + '</font>');
// End Total File Count
});
})
function removeLine(obj) {
inputFile.val('');
var jqObj = $(obj);
var container = jqObj.closest('div');
var index = container.attr("id").split('_')[1];
container.remove();
delete finalFiles[index];
//console.log(finalFiles);
URL.revokeObjectURL(objectUrl);
// Total Files
var count = $('#filename').children().length;
console.log('Number of files: ', count);
$('#totalFiles').html('<font style="color:#06a7e5">Files Uploaded: ' + '<b>' + count + '</b>' + '</font>');
if (count == 0) {
$('#totalFiles').css("display", "none");
} else {}
}
// Draggable Items
$(function() {
$('.draggable, .droppable').sortable({
connectWith: '.playlists'
});
});
#import url('https://fonts.googleapis.com/css?family=Source+Code+Pro');
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
overflow-x: hidden;
overflow-y: visible;
font-family: 'Source Code Pro', monospace;
}
.dropper {
padding: 10px;
}
#drop-zone {
width: 100%;
min-height: 150px;
border: 3px dashed rgba(0, 0, 0, .3);
border-radius: 5px;
font-family: 'Source Code Pro', monospace;
text-align: center;
position: relative;
font-size: 20px;
color: #7E7E7E;
}
#drop-zone input {
position: absolute;
cursor: pointer;
left: 0px;
top: 0px;
opacity: 0;
}
/*Important*/
#drop-zone.mouse-over {
border: 3px dashed rgba(0, 0, 0, .3);
color: #7E7E7E;
}
/*If you dont want the button*/
#clickHere {
display: inline-block;
cursor: pointer;
color: white;
font-size: 1rem;
width: 200px;
border-radius: 0px;
background-color: #000000;
padding: 10px;
}
#clickHere:hover {
background-color: #376199;
}
.uploadedFiles {
padding: 0;
margin: 10px 50px;
}
#filename {
margin-top: 10px;
margin-bottom: 10px;
padding: 10px;
font-size: 14px;
line-height: 1.5em;
border: 1px solid;
min-height: 200px;
max-height: 400px;
overflow-y: scroll;
color: #240aff;
}
#filename span {
font-size: 1.5rem;
line-height: 1.2rem;
height: 1.5rem;
width: 1.5rem;
}
/* File Info */
#totalFiles {
border: 1px solid #06a7e5;
padding: 5px;
display: none;
}
.file-preview {
background: rgb(99, 8, 8);
border: 5px solid #fff;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
display: inline-block;
width: 60px;
height: 60px;
text-align: center;
font-size: 14px;
margin-top: 5px;
}
.closeBtn {
color: black;
display: inline-block;
vertical-align: -20%!important;
}
.closeBtn:hover {
color: red;
display: inline-block;
cursor: pointer;
}
.playlist {
border: 1px solid black;
padding: 10px;
margin: 5px;
background: #e9eaf9;
}
.playlist:hover {
cursor: move;
}
/* AUDIO CONTROLS */
#audioFiles {
vertical-align: middle;
margin: 0px 10px 0px 0px;
}
audio {
/*
filter: sepia(20%) saturate(70%) grayscale(1) contrast(99%) invert(12%);
*/
width: 25%;
height: 35px;
}
audio::-webkit-media-controls-enclosure {
border-radius: 5px;
background-color: #cfcfcf;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Upload & Draggable</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="./images/favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="./style.css">
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js" integrity="sha256-xH4q8N0pEzrZMaRmd7gQVcTZiFei+HfRTBPJ1OGXC0k=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
</head>
<body>
<div class="dropper">
<div id="drop-zone">
<p>Drop files here</p>
<div id="clickHere">or click here <i class="fa fa-upload"></i>
<input type="file" name="file" id="file" multiple accept="audio/*" />
</div>
</div>
</div>
<div class="uploadedFiles">
<p>Uploaded Files are Draggable. <span id="totalFiles"></span></p>
<div id="filename" class="playlists droppable"></div>
</div>
<!--
<audio id="audio2"></audio>
<p>
<label>File Size:</label>
<span id="filesize"></span>
<input type="hidden" id="size" name="size" value="" />
</p>
<p>
<label>Total Duration:</label>
<span id="duration"></span>
<input type="hidden" id="timelength" name="time" value="" />
</p>
-->
<script src="./script.js" async defer></script>
</body>
</html>
It worked well when i removed the following line of jquery code:
$('#filename').html("");
can someone take a look at the code here is the problem screenshot
enter image description here
when clicking on sidebar user a popup appears after clicking on popup header it will go down and then if someone will click on the same user from sidebar a duplicate instance is created and click on the head will make the first one appear and 2nd one to go down.
I want to stop that duplication when someone clicks on sidebar user again then the already generated popup will toggle.
https://jsfiddle.net/hamzasgd/Lqyajokp/4/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facebook like chat popup layout</title>
</head>
<body>
<div id="chat-sidebar">
<div id="sidebar-user-box" class="100">
<img src="user.png" />
<span id="slider-username">User 1</span>
</div>
<div id="sidebar-user-box" class="200">
<img src="user.png" />
<span id="slider-username">User 2</span>
</div>
</div>
</body>
</html>
$(document).ready(function(){
var arr = []; // List of users
$(document).on('click', '.msg_head', function() {
var chatbox = $(this).parents().attr("rel") ;
$('[rel="'+chatbox+'"] .msg_wrap').slideToggle('slow');
return false;
});
$(document).on('click', '.close', function() {
var chatbox = $(this).parents().parents().attr("rel") ;
$('[rel="'+chatbox+'"]').hide();
arr.splice($.inArray(chatbox, arr), 1);
displayChatBox();
return false;
});
$(document).on('click', '#sidebar-user-box', function() {
var userID = $(this).attr("class");
var username = $(this).children().text() ;
if ($.inArray(userID, arr) != -1)
{
arr.splice($.inArray(userID, arr), 1);
}
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="'+ userID+'">'+
'<div class="msg_head">'+username +
'<div class="close">x</div> </div>'+
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>'+
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>' ;
$("body").append( chatPopup );
displayChatBox();
});
$(document).on('keypress', 'textarea' , function(e) {
if (e.keyCode == 13 ) {
var msg = $(this).val();
$(this).val('');
if(msg.trim().length != 0){
var chatbox = $(this).parents().parents().parents().attr("rel") ;
$('<div class="msg-right">'+msg+'</div>').insertBefore('[rel="'+chatbox+'"] .msg_push');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
}
});
function displayChatBox(){
i = 270 ; // start position
j = 260; //next position
$.each( arr, function( index, value ) {
if(index < 4){
$('[rel="'+value+'"]').css("right",i);
$('[rel="'+value+'"]').show();
i = i+j;
}
else{
$('[rel="'+value+'"]').hide();
}
});
}
});
I've added a check that will look if you already have a chatbox with that userID:
var exist = $('.msg_box[rel="' + userID + '"]').length;
if (exist == 0) {
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="' + userID + '">' +
'<div class="msg_head">' + username +
'<div class="close">x</div> </div>' +
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>' +
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>';
$("body").append(chatPopup);
displayChatBox();
}
Please note that you have some invalid html. You are not allowed, to have the id on multiple element.
Demo
$(document).ready(function() {
var arr = []; // List of users
$(document).on('click', '.msg_head', function() {
var chatbox = $(this).parents().attr("rel");
$('[rel="' + chatbox + '"] .msg_wrap').slideToggle('slow');
return false;
});
$(document).on('click', '.close', function() {
var chatbox = $(this).parents().parents().attr("rel");
$('[rel="' + chatbox + '"]').hide();
arr.splice($.inArray(chatbox, arr), 1);
displayChatBox();
return false;
});
$(document).on('click', '#sidebar-user-box', function() {
var userID = $(this).attr("class");
var username = $(this).children().text();
if ($.inArray(userID, arr) != -1) {
arr.splice($.inArray(userID, arr), 1);
}
var exist = $('.msg_box[rel="' + userID + '"]').length;
if (exist == 0) {
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="' + userID + '">' +
'<div class="msg_head">' + username +
'<div class="close">x</div> </div>' +
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>' +
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>';
$("body").append(chatPopup);
displayChatBox();
} else {
$('.msg_box[rel="' + userID + '"] .msg_wrap').slideToggle('slow');
}
});
$(document).on('keypress', 'textarea', function(e) {
if (e.keyCode == 13) {
var msg = $(this).val();
$(this).val('');
if (msg.trim().length != 0) {
var chatbox = $(this).parents().parents().parents().attr("rel");
$('<div class="msg-right">' + msg + '</div>').insertBefore('[rel="' + chatbox + '"] .msg_push');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
}
});
function displayChatBox() {
i = 270; // start position
j = 260; //next position
$.each(arr, function(index, value) {
if (index < 4) {
$('[rel="' + value + '"]').css("right", i);
$('[rel="' + value + '"]').show();
i = i + j;
} else {
$('[rel="' + value + '"]').hide();
}
});
}
});
/**** Chat Popup Layout******/
body {
background: #e5e5e5;
font-family: sans-serif;
}
.msg_box {
position: fixed;
bottom: -5px;
width: 250px;
background: white;
border-radius: 5px 5px 0px 0px;
}
.msg_head {
background: black;
color: white;
padding: 8px;
font-weight: bold;
cursor: pointer;
border-radius: 5px 5px 0px 0px;
}
.msg_body {
background: white;
height: 200px;
font-size: 12px;
padding: 15px;
overflow: auto;
overflow-x: hidden;
}
.msg_input {
width: 100%;
height: 55px;
border: 1px solid white;
border-top: 1px solid #DDDDDD;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.close {
float: right;
cursor: pointer;
}
.minimize {
float: right;
cursor: pointer;
padding-right: 5px;
}
.msg-left {
position: relative;
background: #e2e2e2;
padding: 5px;
min-height: 10px;
margin-bottom: 5px;
margin-right: 10px;
border-radius: 5px;
word-break: break-all;
}
.msg-right {
background: #d4e7fa;
padding: 5px;
min-height: 15px;
margin-bottom: 5px;
position: relative;
margin-left: 10px;
border-radius: 5px;
word-break: break-all;
}
/**** Slider Layout Popup *********/
#chat-sidebar {
width: 250px;
position: fixed;
height: 100%;
right: 0px;
top: 0px;
padding-top: 10px;
padding-bottom: 10px;
border: 1px solid #b2b2b2;
}
#sidebar-user-box {
padding: 4px;
margin-bottom: 4px;
font-size: 15px;
font-family: Calibri;
font-weight: bold;
cursor: pointer;
}
#sidebar-user-box:hover {
background-color: #999999;
}
#sidebar-user-box:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
img {
width: 35px;
height: 35px;
border-radius: 50%;
float: left;
}
#slider-username {
float: left;
line-height: 30px;
margin-left: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chat-sidebar">
<div id="sidebar-user-box" class="100">
<img src="user.png" />
<span id="slider-username">User 1</span>
</div>
<div id="sidebar-user-box" class="200">
<img src="user.png" />
<span id="slider-username">User 2</span>
</div>
</div>
I was playing around jQuery and wanted to add div element with append but it doesn't seem to work, it does absolutely nothing when I click on button.
$(document).ready(function() {
$('#main').on('click', '#btn', function() {
var value = $('#main input').val();
var html = '<div id="cont4><p>' + value + '</p></div>';
$('#main').append(html);
})
})
#cont4 {
width: 290px;
height: 600px;
background: rgb(30, 33, 33, 0.85);
margin-top: 15vh;
margin-left: 17vh;
border-radius: 25px;
transition: 0.35s;
color: white;
text-align: center;
box-shadow: 5px 10px #0c0921;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<div id="cont1">
<h1>Basic</h1>
<p>Buy <span>Basic</span> packet and get:</p>
<p>300 Minutes Talk</p>
<p>500 SMS</p>
<p>5GB NET More info</p>
<button>Buy Now !</button>
</div>
<input>asd
<button id="btn">add</button>
</div>
You have a small typo error in your code ;).
closing " is missing in your append function
$(document).ready(function() {
$('#main').on('click', '#btn', function() {
var value = $('#main input').val();
var html = '<div id="cont4"><p>' + value + '</p></div>';
$('#main').append(html);
})
})
#main {
background: red;
padding: 10px;
cursor: pointer;
}
#cont4 {
background: green;
padding: 10px;
}
#btn {
background: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="main"><input type="text"></input>This is the main container<button id="btn">Button</button></div>
you missed double quotes for id="cont4" in this line, so use the below line in your js
var html = '<div id="cont4"><p>' + value +'</p></div>';
Working code here
$(document).ready(function() {
$('#main').on('click', '#btn', function() {
var value = $('#main input').val();
var html = '<div id="cont4"><p>' + value + '</p></div>';
$('#main').append(html);
})
})
#cont4 {
width: 290px;
height: 600px;
background: rgb(30, 33, 33, 0.85);
margin-top: 15vh;
margin-left: 17vh;
border-radius: 25px;
transition: 0.35s;
color: white;
text-align: center;
box-shadow: 5px 10px #0c0921;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<div id="cont1">
<h1>Basic</h1>
<p>Buy <span>Basic</span> packet and get:</p>
<p>300 Minutes Talk</p>
<p>500 SMS</p>
<p>5GB NET More info</p>
<button>Buy Now !</button>
</div>
<input>asd
<button id="btn">add</button>
</div>
You need to create a jQuery element for append function.
Change this
'<div id="cont4"><p>' + value +'</p></div>'
to
$('<div id="cont4"><p>' + value +'</p></div>');
that means you are creating a element from that string. then append that to another element.
$(document).ready(function() {
$('#main').on('click', '#btn', function(){
var value = $('#main input').val();
var html = $('<div id="cont4"><p>' + value +'</p></div>');
$('#main').append(html);
})
})
I have created a Wikipedia finder web app that accesses the Wikipedia API. However, to append the JSON data to HTML I used the append() function:
$('.results').append('<a class="linksa" href=' + testCheck[key].fullurl +'> <div class="entryOne"><h1>'+ testCheck[key].title + '</h1>'+testCheck[key].extract+'</p></div></a>');
The problem is when a user wants to search a new term to search bar. The new results go under the previous results because of the append(). The codepen to my app is https://codepen.io/mrsalami/pen/NwrGjj
You have to clear .result before appending new content, with snippet below
$(document).ready(function(){
$(".button").on("click", function(){
var value = $('#searchItem').val();
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=info%7Cextracts&list=&generator=search&utf8=1&inprop=url&exsentences=2&exintro=1&gsrsearch=" + value + "&gsrlimit=10&origin=*"
$.getJSON(url, function(x) {
var testCheck = x.query.pages;
// Clear the div before appending current result
$('.results').html("");
for (var key in testCheck) {
if (testCheck.hasOwnProperty(key)) {
console.log(testCheck[key].title);
console.log(testCheck[key].fullurl);
console.log(testCheck[key].extract);
$('.results').append('<a class="linksa" href=' + testCheck[key].fullurl +'> <div class="entryOne"><h1>'+ testCheck[key].title + '</h1>'+testCheck[key].extract+'</p></div></a>');
}
}
});
});
});
header {
text-align: center;
margin-bottom: 40px;
}
.entryOne {
background-color: white;
border: 6px solid red;
min-height: 90px;
padding: 10px;
margin-bottom: 30px;
}
.linksa {
text-decoration: none !important;
color: black;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<h1>Jafar Wikipedia Search</h1>
<input type="text" name="searchItem" class="searchItem" id="searchItem" placeholder="Search">
<a class="button">Button</a>
</header>
<div class="results"></div>
If you really want JQuery:
$('.results').html('<a class="linksa" href=' + testCheck[key].fullurl +'> <div class="entryOne"><h1>'+ testCheck[key].title + '</h1>'+testCheck[key].extract+'</p></div></a>');
or just use vanilla javascript:
document.querySelector(".results").innerHTML = '<a class="linksa" href=' + testCheck[key].fullurl +'> <div class="entryOne"><h1>'+ testCheck[key].title + '</h1>'+testCheck[key].extract+'</p></div></a>';
I am creating an HTML table dynamically from JSON objects. I am trying to create a filter for one of the table columns. It works fine but I cannot make it work with a multiselect function.
I tried adding this line:
$('.One1').multiselect();
in my script, in different places and it did not work.
var data = {"headers":["One","Two","Three","Four","Five","Six","Seven","Number1","Number2"],"rows":[["One1","Two1","Three1","Four1","Five1","Six1","Seven1",11,1000],["One1","Two1","Three2","Four1","Five1","Six1","Seven1", 22, 2000],["One2","Two1","Three1","Four2","Five1","Six1","Seven1", 77, 99]]};
//////First table - Three1 for Views
var table1 = '<div class = "filter_box"></div><div class="row"><div class="col-lg-6" style="background-color: #e90649; width: 117px;"> </div><div class="col-lg-6" style="max-width: 100px; padding-left: 10px; font-size: 2vw;">Table<br/><br/><span style="font-size: 1vw;">One1, Three1, Five1</span></div><div class="col-lg-6"><div class="container"><table><thead><tr></tr><tr><th>One</th><th>Two</th><th>Three</th><th>Four</th><th>Five</th><th>Six</th><th>Seven</th><th>Number1</th><th>Number2</th></tr></thead><tbody>';
var One = '<div class = "filter"><select class="One1" data-col="0"><option value="a">' + "One" + '</option>';
for (i = 0; i < data.rows.length; i++)
{
table1 +="<tr><td>" + data.rows[i][0] + "</td><td>" + data.rows[i][1] + "</td><td>" + data.rows[i][2] + "</td><td>" + data.rows[i][3] + "</td><td>" + data.rows[i][4] + "</td><td>" + data.rows[i][5] + "</td><td>" + data.rows[i][6] + "</td><td>" + data.rows[i][7].toLocaleString() + "</td><td>" + data.rows[i][8].toLocaleString() + "</td><td>" + "</td></tr>";
// Interactive filters
One +='<option value="' + i + '">' + data.rows[i][0] + '</option>';
}
table1 += '</tbody></table></div></div></div>';
One +='</select></div>';
$("#one").html(table1);
$(".filter_box").html(One);
////First table - Filter
$('.One1').change(function () {
var values = [];
$('.One1').each(function () {
var colIdx = $(this).data('col');
$(this).find('option:selected').each(function () {
if ($(this).val() != "") values.push({
text: $(this).text(),
colId: colIdx
});
});
});
One1('#one table > tbody > tr', values);
});
function One1(selector, values) {
$(selector).each(function () {
var sel = $(this);
var txt = sel.find('td:eq(0)').text().trim();
var hwMatches = values.filter(function(ele, idx) {
return ele.text == txt;
}).length;
sel.toggle(hwMatches > 0 || values.length == 0);
});
};
//$('.One1').multiselect();
#import url('https://fonts.googleapis.com/css?family=Roboto');
body, * {
margin: 0;
color:#fff;
font-family: Roboto;
text-transform:capitalize;
}
.row {
display: table;
width: 100%;
height: 241px;
background-color:#454545;
}
.row > .col-lg-6 {
display: table-cell;
vertical-align: middle;
}
.container {
/*display: flex;*/
flex-wrap: wrap;
}
.container > div {
padding: 15px;
margin: 5px;
flex: 0 0 calc(100% - 20px);
text-align: left;
}
/*img {
padding-left: 7%;
max-height:55px;
width:auto;
}*/
td{
padding: 2px 2px;
text-align: center;
margin: 6px 0;
border: none;
}
table{
width: 100%;
background-color:#454545;
font-weight:500;
border-collapse: separate;
border-spacing:0.3em 1.1em;
color: #fff;
border: 0;
}
tr{
font-size: 1.1em;
}
th {
color: #CCC;
font-size: 0.7em;
}
#one,#two,#three,#four{
padding-top:2%;
}
.filter
{
margin:1px;
width:20%;
text-align:center;
display:inline-block;
}
.filter_box
{
text-align:center;
display:inline-block;
width:100%;
}
.filter select, .multiselect dropdown-toggle btn btn-default {
min-width:120px;
-webkit-appearance: button;
-webkit-border-radius: 2px;
-webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1);
-webkit-padding-end: 20px;
-webkit-padding-start: 2px;
-webkit-user-select: none;
background-image: url(http://i62.tinypic.com/15xvbd5.png), -webkit-linear-gradient(#FAFAFA, #F4F4F4 40%, #E5E5E5);
background-position: 97% center;
background-repeat: no-repeat;
border: 1px solid #AAA;
color: #000;
font-size: inherit;
margin: 3px;
overflow: hidden;
padding: 1px 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
/*
tr th:nth-child(5) {
background: red;
display:none;
}
tr td:nth-child(5) {
background: red;
display:none;
}
*/
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<div id="one"></div>
When you declare your select, you can specify it is multiple:
var One = '<div class = "filter"><select class="One1" data-col="0"><option value="a">' + "One" + '</option>';
Change it to:
var One = '<div class = "filter"><select multiselect class="One1" data-col="0"><option value="a">' + "One" + '</option>';
Result:
var data = {"headers":["One","Two","Three","Four","Five","Six","Seven","Number1","Number2"],"rows":[["One1","Two1","Three1","Four1","Five1","Six1","Seven1",11,1000],["One1","Two1","Three2","Four1","Five1","Six1","Seven1", 22, 2000],["One2","Two1","Three1","Four2","Five1","Six1","Seven1", 77, 99]]};
//////First table - Three1 for Views
var table1 = '<div class = "filter_box"></div><div class="row"><div class="col-lg-6" style="background-color: #e90649; width: 117px;"> </div><div class="col-lg-6" style="max-width: 100px; padding-left: 10px; font-size: 2vw;">Table<br/><br/><span style="font-size: 1vw;">One1, Three1, Five1</span></div><div class="col-lg-6"><div class="container"><table><thead><tr></tr><tr><th>One</th><th>Two</th><th>Three</th><th>Four</th><th>Five</th><th>Six</th><th>Seven</th><th>Number1</th><th>Number2</th></tr></thead><tbody>';
var One = '<div class = "filter"><select multiple class="One1" data-col="0"><option value="a">' + "One" + '</option>';
for (i = 0; i < data.rows.length; i++)
{
table1 +="<tr><td>" + data.rows[i][0] + "</td><td>" + data.rows[i][1] + "</td><td>" + data.rows[i][2] + "</td><td>" + data.rows[i][3] + "</td><td>" + data.rows[i][4] + "</td><td>" + data.rows[i][5] + "</td><td>" + data.rows[i][6] + "</td><td>" + data.rows[i][7].toLocaleString() + "</td><td>" + data.rows[i][8].toLocaleString() + "</td><td>" + "</td></tr>";
// Interactive filters
One +='<option value="' + i + '">' + data.rows[i][0] + '</option>';
}
table1 += '</tbody></table></div></div></div>';
One +='</select></div>';
$("#one").html(table1);
$(".filter_box").html(One);
////First table - Filter
$('.One1').change(function () {
var values = [];
$('.One1').each(function () {
var colIdx = $(this).data('col');
$(this).find('option:selected').each(function () {
if ($(this).val() != "") values.push({
text: $(this).text(),
colId: colIdx
});
});
});
One1('#one table > tbody > tr', values);
});
function One1(selector, values) {
$(selector).each(function () {
var sel = $(this);
var txt = sel.find('td:eq(0)').text().trim();
var hwMatches = values.filter(function(ele, idx) {
return ele.text == txt;
}).length;
sel.toggle(hwMatches > 0 || values.length == 0);
});
};
//$('.One1').multiselect();
#import url('https://fonts.googleapis.com/css?family=Roboto');
body, * {
margin: 0;
color:#fff;
font-family: Roboto;
text-transform:capitalize;
}
.row {
display: table;
width: 100%;
height: 241px;
background-color:#454545;
}
.row > .col-lg-6 {
display: table-cell;
vertical-align: middle;
}
.container {
/*display: flex;*/
flex-wrap: wrap;
}
.container > div {
padding: 15px;
margin: 5px;
flex: 0 0 calc(100% - 20px);
text-align: left;
}
/*img {
padding-left: 7%;
max-height:55px;
width:auto;
}*/
td{
padding: 2px 2px;
text-align: center;
margin: 6px 0;
border: none;
}
table{
width: 100%;
background-color:#454545;
font-weight:500;
border-collapse: separate;
border-spacing:0.3em 1.1em;
color: #fff;
border: 0;
}
tr{
font-size: 1.1em;
}
th {
color: #CCC;
font-size: 0.7em;
}
#one,#two,#three,#four{
padding-top:2%;
}
.filter
{
margin:1px;
width:20%;
text-align:center;
display:inline-block;
}
.filter_box
{
text-align:center;
display:inline-block;
width:100%;
}
.filter select, .multiselect dropdown-toggle btn btn-default {
min-width:120px;
-webkit-appearance: button;
-webkit-border-radius: 2px;
-webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1);
-webkit-padding-end: 20px;
-webkit-padding-start: 2px;
-webkit-user-select: none;
background-image: url(http://i62.tinypic.com/15xvbd5.png), -webkit-linear-gradient(#FAFAFA, #F4F4F4 40%, #E5E5E5);
background-position: 97% center;
background-repeat: no-repeat;
border: 1px solid #AAA;
color: #000;
font-size: inherit;
margin: 3px;
overflow: hidden;
padding: 1px 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
/*
tr th:nth-child(5) {
background: red;
display:none;
}
tr td:nth-child(5) {
background: red;
display:none;
}
*/
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<div id="one"></div>
For example if you want to filter "One1" in a table, you can simply use something like: $('td:contains("One1")').parent().hide(); and $('td:contains("One1")').parent().show(); as a filter.
If you want to filter specific column, combine something like this with your selector: $('table tr > td:nth-child(yourColumnNumberShouldBeFiltered), table tr > th:nth-child(yourColumnNumberShouldBeFiltered)'). These expressions may be used in a function binded to 'change' event of your multiselect.
UPDATE: Above method, because of using :contains(), filter all of "One1", "One12", and so on! For exact match filteration you can use something like this:
$('table tr > td:nth-child(yourColumnNumberShouldBeFiltered)').filter(function() {
return $(this).text() == "yourExactTextToFilter";
}).parent().hide();
$('table tr > td:nth-child(yourColumnNumberShouldBeFiltered)').filter(function() {
return $(this).text() == "yourExactTextToFilter";
}).parent().show();
or for better performance of getting exact matches, see this link: Select element by exact match of its content