In the wishlist ui function, I append items to the wishlist by checking the .wish-btn. I want to simulate items already added to the list so I need to run the function on load so that all of the items have been checked.
How do I run the function on load so that all of the items are:
Already checked
Appended to the list
var wish = {
items: []
};
var update_product = function(product) {};
$(function() {
//Add to wish
var addToWish = function(product, qty) {
qty = qty || 1;
var wish = getWish();
var indexOfId = wish.items.findIndex(x => x.id == product.id);
if (indexOfId === -1) {
wish.items.push({
id: product.id,
img: product.img,
name: product.name
});
$parent = $("#" + product.id).closest(".product");
$parent
.find(".wish-icon")
.addClass("active")
.attr("data-prefix", "fas");
} else {
wish.items[indexOfId].qty++;
wish.items[indexOfId].stock = Number(product.stock);
}
//Update popup wish
updateWish(wish);
};
//Remove from wish on id
var removeFromWish = function(id) {
var wish = getWish();
var wishIndex = wish.items.findIndex(x => x.id == id);
wish.items.splice(wishIndex, 1);
$parent = $("#" + id).closest(".product");
$parent
.find(".wish-icon")
.first()
.removeClass("active")
.attr("data-prefix", "far");
//Update popup wish
updateWish(wish);
};
var getProductValues = function(element) {
var productId = $(element)
.closest(".product")
.find(".item__title")
.attr("id");
var productImg = $(element)
.closest(".product")
.find(".item__img")
.attr("src");
var productName = $(element)
.closest(".product")
.find(".item__title")
.html();
return {
id: productId,
img: productImg,
name: productName
};
};
$(".my-wish-add").on("change", function() {
var product = getProductValues(this);
if ($(this).is(":checked")) {
addToWish({
id: product.id,
img: product.img,
name: product.name
});
} else {
removeFromWish(product.id);
}
});
//Update wish html to reflect changes
var updateWish = function(wish) {
//Add to shopping wish dropdown
$(".wishlist__items").html("");
for (var i = 0; i < wish.items.length; i++) {
$(".wishlist__items").append(
"<li class='wish__item'>" +
'<div class="wish__thumb">' +
"<img src='" +
wish.items[i].img +
"' />" +
"</div>" +
'<div class="wish__info">' +
'<div class="wish-name">' +
wish.items[i].name +
"</div>" +
"</div>" +
'<div class="wish__remove">' +
'<label class="wish__label">' +
'<input type="checkbox" id="my-wish-remove' +
i +
'" class="my-wish-remove" aria-hidden="true">' +
"<i class='fas fa-heart'></i>" +
"</div>" +
"</div>"
);
(function() {
var currentIndex = i;
$("#my-wish-remove" + currentIndex).on("change", function() {
$(this)
.closest("li")
.hide(400);
setTimeout(function() {
wish.items[currentIndex].stock = "";
update_product(wish.items[currentIndex]);
$("#" + wish.items[currentIndex].id).parents().find($(".wish-btn > input")).prop("checked", false);
removeFromWish(wish.items[currentIndex].id);
}, 400);
});
})();
}
};
//Get Wish
var getWish = function() {
var myWish = wish;
return myWish;
};
});
img {
width: 50px;
}
.my-wish-add {
font-family: "Font Awesome\ 5 Pro";
font-weight: 900;
}
.wish-btn {
position: relative;
}
.wish-btn input {
position: absolute;
opacity: 0;
top: 0;
left: 0;
right: 0;
bottom: 0;
cursor: pointer;
}
.wishlist__list {
right: 0;
width: 320px;
position: absolute;
padding: 20px;
}
<script src="https://pro.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-id="wishlist">
<div class="wishlist__list">
<ul class="wishlist__items">
</ul>
</div>
</div>
<div class='products'>
<div class="product">
<div id='headphones' class='item__title'>Item 1</div>
<img class="item__img" src="https://www.iconasys.com/wp-content/uploads/2017/06/360-Product-Photography-White-Background-Acrylic-Riser-08.jpg">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'>
<i class="wish-icon far fa-heart"></i>
</input>
</label>
</div>
<div class="product">
<div class="items__cart">
<div id='backpack' class='item__title'>Item 2</div>
<img class="item__img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqpSgkG4AQDQOe33jI1NiW3GW2JSB-_v36aREsVyFQH55JFOJ">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'>
<i class="wish-icon far fa-heart"></i>
</input>
</label>
</div>
</div>
<div class="product">
<div class="items__cart">
<div id='handbag' class='item__title'>Item 3</div>
<img class="item__img" src="https://qph.fs.quoracdn.net/main-qimg-de7d9680c4460296e461af9720a77d64">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'>
<i class="wish-icon far fa-heart"></i>
</input>
</label>
</div>
</div>
</div>
`
Follow charlietfl's answer, then you will get an error:
TypeError: getWish is not a function
Then you have to move your change event handler to the bottom below getWish and updateWish function, because they need to be declared first to be used by the event handler.
var wish = {
items: []
};
var update_product = function(product) {};
$(function() {
//Add to wish
var addToWish = function(product, qty) {
qty = qty || 1;
var wish = getWish();
var indexOfId = wish.items.findIndex(x => x.id == product.id);
if (indexOfId === -1) {
wish.items.push({
id: product.id,
img: product.img,
name: product.name
});
$parent = $("#" + product.id).closest(".product");
$parent
.find(".wish-icon")
.addClass("active")
.attr("data-prefix", "fas");
} else {
wish.items[indexOfId].qty++;
wish.items[indexOfId].stock = Number(product.stock);
}
//Update popup wish
updateWish(wish);
};
//Remove from wish on id
var removeFromWish = function(id) {
var wish = getWish();
var wishIndex = wish.items.findIndex(x => x.id == id);
wish.items.splice(wishIndex, 1);
$parent = $("#" + id).closest(".product");
$parent
.find(".wish-icon")
.first()
.removeClass("active")
.attr("data-prefix", "far");
//Update popup wish
updateWish(wish);
};
var getProductValues = function(element) {
var productId = $(element)
.closest(".product")
.find(".item__title")
.attr("id");
var productImg = $(element)
.closest(".product")
.find(".item__img")
.attr("src");
var productName = $(element)
.closest(".product")
.find(".item__title")
.html();
return {
id: productId,
img: productImg,
name: productName
};
};
//Update wish html to reflect changes
var updateWish = function(wish) {
//Add to shopping wish dropdown
$(".wishlist__items").html("");
for (var i = 0; i < wish.items.length; i++) {
$(".wishlist__items").append(
"<li class='wish__item'>" +
'<div class="wish__thumb">' +
"<img src='" +
wish.items[i].img +
"' />" +
"</div>" +
'<div class="wish__info">' +
'<div class="wish-name">' +
wish.items[i].name +
"</div>" +
"</div>" +
'<div class="wish__remove">' +
'<label class="wish__label">' +
'<input type="checkbox" id="my-wish-remove' +
i +
'" class="my-wish-remove" aria-hidden="true">' +
"<i class='fas fa-heart'></i>" +
"</div>" +
"</div>"
);
(function() {
var currentIndex = i;
$("#my-wish-remove" + currentIndex).on("change", function() {
$(this)
.closest("li")
.hide(400);
setTimeout(function() {
wish.items[currentIndex].stock = "";
update_product(wish.items[currentIndex]);
$("#" + wish.items[currentIndex].id).parents().find($(".wish-btn > input")).prop("checked", false);
removeFromWish(wish.items[currentIndex].id);
}, 400);
});
})();
}
};
//Get Wish
var getWish = function() {
var myWish = wish;
return myWish;
};
// Move this block to the bottom after you have defined all functions
$(".my-wish-add").on("change", function() {
var product = getProductValues(this);
if ($(this).is(":checked")) {
addToWish({
id: product.id,
img: product.img,
name: product.name
});
} else {
removeFromWish(product.id);
}
}).prop('checked', true).change();
});
img {
width: 50px;
}
.my-wish-add {
font-family: "Font Awesome\ 5 Pro";
font-weight: 900;
}
.wish-btn {
position: relative;
}
.wish-btn input {
position: absolute;
opacity: 0;
top: 0;
left: 0;
right: 0;
bottom: 0;
cursor: pointer;
}
.wishlist__list {
right: 0;
width: 320px;
position: absolute;
padding: 20px;
}
<script src="https://pro.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-id="wishlist">
<div class="wishlist__list">
<ul class="wishlist__items">
</ul>
</div>
</div>
<div class='products'>
<div class="product">
<div id='headphones' class='item__title'>Item 1</div>
<img class="item__img" src="https://www.iconasys.com/wp-content/uploads/2017/06/360-Product-Photography-White-Background-Acrylic-Riser-08.jpg">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'/>
<i class="wish-icon far fa-heart">click to wish</i>
</label>
</div>
<div class="product">
<div class="items__cart">
<div id='backpack' class='item__title'>Item 2</div>
<img class="item__img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqpSgkG4AQDQOe33jI1NiW3GW2JSB-_v36aREsVyFQH55JFOJ">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'/>
<i class="wish-icon far fa-heart">click to wish</i>
</label>
</div>
</div>
<div class="product">
<div class="items__cart">
<div id='handbag' class='item__title'>Item 3</div>
<img class="item__img" src="https://qph.fs.quoracdn.net/main-qimg-de7d9680c4460296e461af9720a77d64">
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'/>
<i class="wish-icon far fa-heart">click to wish</i>
</label>
</div>
</div>
</div>
You can trigger a change right after you create a change event listener by chaining change() with no arguments to it.
Using prop('checked', true) will check them and you can chain that as well
$(selector).on('change', function(evt){
// do stuff when change occurs
// now check it and trigger change
}).prop('checked', true).change()
Related
I have an input in which, through the onclick function, new inputs are added via innerhtml, but when I delete 1 object, it goes out of the list. How to do it please help
var x = 0;
function addInputIIN() {
if (x < 4 ){
var profile = document.getElementById('formDriverInputs');
var div = document.createElement('div');
idX = 'driverIdInput' + [x + 1]
NameX = 'driverNameInput' + [x + 1]
div.id = 'inputDriverBlock' + ++x;
const numDriver = x + 1
div.innerHTML = '<div class="inputContainer d-flex align-items-start"><div class="input-group- prepend"><div class="input-group-text">'+numDriver+'</div></div><input type="text" class="form-control form__iin mb-3 position-relative" id='+ idX +' name='+ NameX +' aria-describedby="driver" placeholder="Введите иин" ><img src="https://w7.pngwing.com/pngs/185/104/png-transparent-emblem-icon-icons-matt-minus-symbol.png" alt="" class="form__img-add" alt="" onclick="delInputIIN()"> <a href=""> </div>';
console.log(div)
profile.appendChild(div);
console.log(x)
}else{
var toastBody = document.querySelector('.toast-body')
toastBody.innerHTML = 'Не может быть больше 5 водителей на 1 машину'
BsAlert.show();
}
}
function delInputIIN() {
var inputs = document.querySelectorAll('.inputIcon')
var div = document.getElementById('input' + x);
var parent = event.target.parentNode.parentNode
parent.remove();
--x
console.log(x)
}
.form__img-add{
width:32px;
}
<div class="form-group text-start" id="formDriverInputs">
<div id="inputDriverBlock0">
<div class="inputContainer">
<div class="input-group-prepend">
<div class="input-group-text">1</div>
<input type="text" id="driverIdInput0" name="driverNameInput0"placeholder="Введите иин" '> <img src="https://image.emojipng.com/610/1872610.jpg" alt="" class="form__img-add" onclick="addInputIIN()">
</div>
</div>
</div>
</div>
How to make sure that when deleting all the numbering goes in order from 1 to 5
If you delegate and clone you have a much easier time
Note how I hide the first minus
window.addEventListener("DOMContentLoaded", () => {
const container = document.getElementById("formDriverInputs");
const toastBody = document.querySelector(".toast-body")
const tmp = document.getElementById("tmp")
const maxEntries = 5;
const renum = () => {
container.querySelectorAll(".input-group-text").forEach((txt,i) => txt.textContent = (i+1));
}
const addContent = () => {
container.append(tmp.content.cloneNode(true));
renum();
}
container.addEventListener("click", (e) => {
const tgt = e.target;
if (tgt.matches(".form__img-remove")) {
tgt.closest(".inputDriverBlock").remove();
renum();
return;
}
if (tgt.matches(".form__img-add")) {
if (container.children.length === maxEntries) {
toastBody.innerHTML = 'Не может быть больше 5 водителей на 1 машину'
// BsAlert.show(); // I do not have that plugin
return;
}
addContent();
}
});
addContent(); // add the first
});
.form__img-add {
width: 32px;
height: 22px;
}
.form__img-remove {
height: 22px;
}
#formDriverInputs > div:nth-child(1) .form__img-remove { display: none }
<div class="form-group text-start" id="formDriverInputs"></div>
<div class="toast-body"></div>
<template id="tmp">
<div class="inputDriverBlock">
<div class="inputContainer d-flex align-items-start">
<div class="input-group-prepend">
<div class="input-group-text"></div>
<input type="text" class="form-control form__iin mb-3 position-relative" name="" aria-describedby="driver" placeholder="Введите иин" /> <img src="https://image.emojipng.com/610/1872610.jpg" alt="" class="form__img-add">
<img src="https://w7.pngwing.com/pngs/185/104/png-transparent-emblem-icon-icons-matt-minus-symbol.png" alt="" class="form__img-remove" />
</div>
</div>
</div>
</template>
I Am on that script for 2 days and I think I lost in somewhere... First Click is ok , second click is ok but after second click the main idea is lost...
What I want is after click "EKLE" Button add new with The input Value..
But after second click "first element add new tags..
I want only "Yeni İstasyon Ekleyin" button adds new elements..
I hope I told what I meant... :/
$("#istasyonismispan").click(function() {
document.getElementById("istasyonismispan").innerHTML = "";
id = document.getElementById("istasyonismispan").id;
divareastn = document.getElementById(id);
divareastn.style.height = "100px";
divareastn.style.paddingTop = "10px";
divareastn.style.backgroundColor = "#D8C7B4";
input = '<input type="text" id="inputid' + id + '" style="width:260px;height: 35px;padding-left: 1rem" class="form-control form-control-sm" placeholder="İstasyon İsmi Giriniz...">';
newbutton = '<button type="text" id="buttonid' + id + '" style="width:260px;height: 35px;margin-top: -2rem" class="addstation btn btn-sm btn-primary bi bi-plus-square" onclick="eklebutton(this.id)"> EKLE...</button>';
divareastn.innerHTML = input + "<br>" + newbutton;
document.getElementById("inputid" + id).focus();
});
function eklebutton(id) {
mainid = id.substr(8);
id = id.replace(/\s/g, '');
inputid = "inputid" + mainid;
mainid = document.getElementById(inputid).value;
buttonid = "buttonid" + mainid;
stationid = document.getElementById(inputid).value;
stationidcheck = stationid.replace(/\s/g, '');
istasyonismispan = "istasyonismispan" + stationidcheck;
if (stationidcheck != "") {
document.getElementById("istasyonismispan").innerHTML = "";
headerofstation = '<h4><span class="float-md-start text-dark" > ' + stationid + '</span></h4>';
newinnerhtml = headerofstation + '<p id="" style="width:260px;height: 35px;margin-top: 1rem" class="float-md-start bi bi-plus-square" > YENİ GÖREV EKLE...</p>'
document.getElementById("istasyonismispan").innerHTML = newinnerhtml;
document.getElementById("istasyonismispan").id = istasyonismispan;
divarea = document.getElementById("kanbanrow");
newtag = document.createElement("A");
newtag.style.width = "310px";
newtag.innerHTML =
'<a style="width:300px;height: 40px;line-height: 40px;padding-left: 20px;" id="istasyonismispan" class="float-md-start hoverback " ><span class="bi bi-plus-square"></span> Yeni İstasyon Ekleyin</a>';
divarea.appendChild(newtag);
} else {
alert("LÜTFEN İSTASYON BAŞLIĞI GİRİNİZ");
}
};
div.scrollmenu {
white-space: nowrap;
}
div.scrollmenu a {
display: inline-block;
}
.hoverback {
background: rgba(113, 199, 230, 1);
}
.hoverback:hover {
background: rgba(113, 199, 230, 0.7);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<body>
<div class="scrollmenu ">
<div class=" float-md-start " id="kanbanrow">
<a style="width:300px;height: 40px;line-height: 40px;padding-left: 20px;" id="istasyonismispan" class="hoverback text-white "><span class="bi bi-plus-square"></span> Yeni İstasyon Ekleyin</a>
</div>
</div>
</body>
I'm using jquery ui for dragging items, so I have an array similar to:
var animals = ['cat', 'dog', 'monkey'];
var output = [];
for (var i = 0; i < animals.length; i++) {
output.push('<p>' + animals[i] + '</p>');
}
$('#list').html(output.join(""));
So I get this on the page, what I want to do is if I drag "cat" to dragging zone, I would like to remove it from the array automatically. New array should have only "dog" and "monkey" in it and that should be showed on the page.
<div class="col-xs-2">
<a href="#">
<img id="drag-cat" class="drag-img" src="images/cat.png" alt="" />
</a>
</div>
That is my html part, so when I drag it and this item is showed in that drag div, I would like to update array.
Any suggestions?
Thanks.
EDIT:
JS Fiddle
Use Array#splice to remove item from array by specifying the index
Use String#split to get name from id attribute as there is no other reference
Re-bind the output array considering removed item
$(function() {
$(".drag-main img").draggable({
revert: "invalid",
refreshPositions: true,
drag: function(event, ui) {
ui.helper.addClass("draggable");
},
stop: function(event, ui) {
ui.helper.removeClass("draggable");
var image = this.src.split("/")[this.src.split("/").length - 1];
}
});
$(".animals-box").droppable({
drop: function(event, ui) {
if ($(".animals-box img").length == 0) {
$(".animals-box").html("");
}
ui.draggable.addClass("dropped");
var elem = ui.draggable[0].getAttribute('id').split('-')[1];
animals.splice(animals.indexOf(elem), 1);
var output = [];
for (var i = 0; i < animals.length; i++) {
output.push('<p>' + animals[i] + '</p>');
}
$('#list').html(output.join(""));
$(".animals-box").append(ui.draggable);
}
});
});
var animals = ['cat', 'dog', 'monkey'];
var output = [];
for (var i = 0; i < animals.length; i++) {
output.push('<p>' + animals[i] + '</p>');
}
$('#list').html(output.join(""));
.drag-main img {
width: 75px;
}
.animals-box {
background-color: gray;
height: 100px;
width: 100%;
}
.animals-box img {
float: left;
}
.draggable {
filter: alpha(opacity=80);
opacity: 0.8;
}
.dropped {
position: static;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<div class="drag-main">
<div class="row">
<div class="col-xs-2">
<a href="#">
<img id="drag-cat" class="drag-img" src="http://i.amz.mshcdn.com/KRUEW_Zm_0UvTD97QnKID9MUqmk=/150x150/2012%2F12%2F04%2Fd0%2Fcat.c4A" alt="" />
</a>
</div>
<div class="col-xs-2">
<a href="#">
<img id="drag-dog" class="drag-img" src=" http://www.dogisto.com/wp-content/uploads/2016/03/dog-abandoned-150x150.jpg" alt="" />
</a>
</div>
</div>
</div>
<div class="animals-box"></div>
<hr>
<div id="list">
</div>
Fiddle Demo
Using data-* attribute
$(function() {
$(".drag-main img").draggable({
revert: "invalid",
refreshPositions: true,
drag: function(event, ui) {
ui.helper.addClass("draggable");
},
stop: function(event, ui) {
ui.helper.removeClass("draggable");
var image = this.src.split("/")[this.src.split("/").length - 1];
}
});
$(".animals-box").droppable({
drop: function(event, ui) {
if ($(".animals-box img").length == 0) {
$(".animals-box").html("");
}
ui.draggable.addClass("dropped");
var elem = ui.draggable[0].dataset.name;
animals.splice(animals.indexOf(elem), 1);
var output = [];
for (var i = 0; i < animals.length; i++) {
output.push('<p>' + animals[i] + '</p>');
}
$('#list').html(output.join(""));
$(".animals-box").append(ui.draggable);
}
});
});
var animals = ['cat', 'dog', 'monkey'];
var output = [];
for (var i = 0; i < animals.length; i++) {
output.push('<p>' + animals[i] + '</p>');
}
$('#list').html(output.join(""));
.drag-main img {
width: 75px;
}
.animals-box {
background-color: gray;
height: 100px;
width: 100%;
}
.animals-box img {
float: left;
}
.draggable {
filter: alpha(opacity=80);
opacity: 0.8;
}
.dropped {
position: static;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<div class="drag-main">
<div class="row">
<div class="col-xs-2">
<a href="#">
<img id="drag-cat" data-name="cat" class="drag-img" src="http://i.amz.mshcdn.com/KRUEW_Zm_0UvTD97QnKID9MUqmk=/150x150/2012%2F12%2F04%2Fd0%2Fcat.c4A" alt="" />
</a>
</div>
<div class="col-xs-2">
<a href="#">
<img id="drag-dog" data-name="dog" class="drag-img" src=" http://www.dogisto.com/wp-content/uploads/2016/03/dog-abandoned-150x150.jpg" alt="" />
</a>
</div>
</div>
</div>
<div class="animals-box"></div>
<hr>
<div id="list">
</div>
You can get the dropped elemenent id and remove it from the array in the drop event like:
var index = animals.indexOf( ui.draggable.attr("id").replace('drag-',''));
animals.splice(index, 1);
Demo: https://jsfiddle.net/th01sw16/2/
I want to automatically adjust the number list that was created using .append(). Example, if there are 4 items added on the list which will numbered from 2-4 respectively and if I removed item number 3, the item number 4 will automatically be number 3 and if I add a new item, it will be the last on the list. Here's my code below.
$('#display').click(function() {
$('#show').show();
});
var c = 1;
$('#append').click(function() {
var cnt = $('.cnt').val();
for (var i = 0; i < cnt; i++) {
c++;
$('#inputs').append("<div id='inputs' name='" + c + "'>" + c + ".)<button id='remove' name='" + c + "'>X</button></div>");
}
});
$(document).on('click', '#inputs #remove', function() {
var nm = $(this).attr('name');
$('div[name="' + nm + '"]').remove();
c--;
});
#show {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<button id='display'>Display</button>
<div id='show'>
<br>
<input type='text' class='cnt' value='1' placeholder="num of append" />
<button id='append'>+</button>
<br>
<div id='inputs'>
1.)
</div>
</div>
Here is the jsfiddle of the code.
here is your answer
Fiddle Here
$('#display').click(function() {
$('#show').show();
});
var c = 1;
$('#append').click(function() {
var cnt = $('.cnt').val();
for (var i = 0; i < cnt; i++) {
c++;
$('#inputs').append("<div class='inputs' name='" + c + "'><span class='number'>" +c + "</span>.)<button class='remove' name='" + c + "'>X</button></div>");
}
});
$(document).on('click', '#inputs .remove', function() {
var nm = $(this).attr('name');
$('div[name="' + nm + '"]').remove();
c--;
resetCount();
});
function resetCount(){
$('#inputs div.inputs').each(function(i){
$('.number', $(this)).text(i+2);
$('input', $(this)).attr('name', i+2);
});
}
#remain,
#total {
background-color: #333;
width: 60px;
height: 20px;
color: #fff;
padding: 0 10px;
}
input:focus {
background-color: #000;
color: #fff;
}
input {
background-color: #ccc;
}
#show {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id='display'>Display</button>
<div id='show'>
<br>
<input type='text' class='cnt' value='1' placeholder="num of append" />
<button id='append'>+</button>
<br>
<div id='inputs'>
1.)
</div>
</div>
You should not be using the same ID for different elements
Also the way you could do this is by creating a function that resets the elements counting after each add/delete event
When creating and appending elements in jQuery its better to use this syntax:
$('<ELEMENT TAG/>',{
ATTRIBUTE: VALUE
});
When looping through elements in jQuery its better to use $.each
$('#append').on('click', function(){
$('<div/>', {
'class': 'inputs',
html: '<span class="count"></span><input type="text" class="time" name="0" value="00:00:00"/><button>X</button>'
}).appendTo('#inputs');
resetInputsCount();
});
$('#inputs').on('click', '.inputs button', function(){
var $this = $(this);
$this.parent().remove();
resetInputsCount();
});
//The function that resets the count span text and the name value based on the current count of elements
function resetInputsCount(){
//looping through elements
$('#inputs div.inputs').each(function(i){
//caching the current element in a var named $this
var $this = $(this);
//changing the count span text to i+2 the 2 is added because the index starts at 0 and there is already one element 1.)
$('.count', this).text((i+2) + '.) ');
//change the value of the input name
$('input', $this).attr('name', i+2);
});
}
Demo on JSFiddle
I know theres an answer already but since I did the work I might as well post it.
Here's the fiddle for the example
here's the code:
Html
<div id='button'>
<span>Add</span>
</div>
<div id='content'></div>
CSS
#button span {
padding: 5px 15px;
background: #ccc;
cursor: pointer;
}
#button {
margin: 5px 0;
}
.delete {
cursor: pointer;
padding: 0 5px;
border: 1px solid gray;
}
jQuery
$(document).ready(function() {
var index = 1;
$('#button').on('click', function() {
var add = '<div class="new"><span class="number">' + index + '</span><input type="text"/><span class="delete">x</span></div>';
$('#content').append(add);
index++;
});
$(document).on('click', '.delete', function() {
index--;
$(this).parent().remove();
var index2 = 1;
var newelement = $('.new');
$(newelement).each(function() {
$(this).find('.number').text(index2);
index2++;
});
});
});
Using your html structure and adding some input fields (to be sure we maintain values)
Here is my approach:
(Also fixed duplicate id and names you have)
$('#display').click(function() {
$('#show').show();
});
var c = 1;
var inputs = [];
$('#append').click(function() {
var cnt = $('.cnt').val();
for (var i=0; i<cnt; i++) {
c++;
$div = $("<div id='input"+c+"' />").data('index', c);
$span = $("<span />").text(c+".)");
$button = $("<button class='input_remove' />").text("X");
$input = $("<input type='text' class='small' />").attr("name","input"+c);
$div.append($div).append($span).append($input).append($button);
$('#inputs').append($div);
}
});
$(document).on('click', '.input_remove', function() {
index = $(this).parent().data('index');
$("#inputs").find('#input'+index).remove();
c = 1;
$("#inputs").find('div').each(function(index,ele){
c++;
$(ele).attr('id',"input"+c).data('index',c)
.find("span").text(c+".)").end()
.find("input").attr("name","input"+c);
});
});
#show {
display: none;
}
.small { width:100px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<button id='display'>Display</button>
<div id='show'>
<br>
<input type='text' class='cnt' value='1' placeholder="num of append" />
<button id='append'>+</button>
<br>
<div id='inputs'>
1.)
</div>
</div>
I am new to Kendo Grid and trying to use the columnMenu option. I need to access the column Menu function (only the ability to show/hide columns from a button outside the grid. This link allows me to do that and it is working fine.
How to show Kendo Grid's columnMenu using script
But this still retains the columnMenu option in the column headers which I do not need. So after looking into it further, I was able to remove the column headers on the load using
defaultGrid.thead.find("[data-field=Address]>.k-header-column-menu").remove();
where Address is one of the columns in the grid. I still do need to have atleast one column with the columnMenu option, or else the solution in the above url does not work.
Using the solution in the link above, it also removes the filter option on the columns. What I need to achieve is remove the Column Menu from all the column headers (and access the show/hide column option from outside the grid) and also have the filter option available to specific columns of the grid
Is this possible and how do I go about doing it? Please help
Not sure I got all requirements right, but something like this should work:
JS:
var grid = $("#grid").kendoGrid({
dataSource: [{
foo: "foo",
bar: "bar"
}],
filterable: true,
columnMenu: true
}).getKendoGrid();
function showMenu() {
var offset = $(this).offset();
var fieldName = $(this).data("field");
var th = $(grid.thead).find("th[data-field='" + fieldName + "']");
$(th).find(".k-header-column-menu:first").click();
$(".k-column-menu").parent().css({
top: offset.top + $(this).outerHeight(),
left: offset.left
});
}
$(document).on("click", ".grid-menu", showMenu);
CSS:
.k-header-column-menu {
visibility: hidden
}
HTML:
<div id='grid'></div>
<div>
<button class='grid-menu' data-field="foo">Show foo menu</button>
<button class='grid-menu' data-field="bar">Show bar menu</button>
</div>
(demo)
Another approach for just showing a menu with checkboxes while keeping the filter menu in the grid header:
Grid:
var grid = $("#grid").kendoGrid({
dataSource: [{
foo: "foo",
bar: "bar"
}],
filterable: true,
columnMenu: false
}).getKendoGrid();
Create menu entries from grid.columns:
var ds = [];
for (var i = 0, max = grid.columns.length; i < max; i++) {
ds.push({
encoded: false,
text: "<label><input type='checkbox' checked='checked' " +
" class='check' data-field='" + grid.columns[i].field +
"'/>" + grid.columns[i].field + "</label>"
});
}
Menu:
$("#menu").kendoMenu({
dataSource: [{
text: "Menu",
items: ds
}],
openOnClick: true,
closeOnClick: false,
open: function () {
var selector;
// deselect hidden columns
$.each(grid.columns, function () {
if (this.hidden) {
selector = "input[data-field='" + this.field + "']";
$(selector).prop("checked", false);
}
});
},
select: function (e) {
// ignore click on top-level menu button
if ($(e.item).parent().filter("div").length) return;
var input = $(e.item).find("input.check");
var field = $(input).data("field");
if ($(input).is(":checked")) {
grid.showColumn(field);
} else {
grid.hideColumn(field);
}
}
});
(demo)
This is a pretty old thread, but after searching for similar things I found a post in the Terlerik forum where a user makes reference to "kendoColumnMenu". For as much as I can tell this is undocumented.
It also shows how to add additional options to the menu that is created for saving grid state or other configuration options of your choice.
Here is the link to the post which also contains a link to the DOJO with working code: Click Here
Hopefully this will help someone else searching for this.
I made the kendo column menu include filter settings and it is worked for me,
// column settings dropdown maker
function GridGorunumAyarlaMenu(GridName) {
var ColumnMenuListHTML = "";
var CheckBoxType = "";
var LockSignType = "";
var Col_uid = "";
var GridColumns = $("#" + GridName).data("kendoGrid").columns;
// column setting area
$("#" + GridName + " .k-header").each(function(i, item) {
for (var i = 0; i < GridColumns.length; i++) {
if (GridColumns[i].uid == $(item).attr("id") && GridColumns[i].title != undefined) {
if (GridColumns[i].hidden == true) {
CheckBoxType = '<div onclick=' + "ShowHideColumnSet('" + GridColumns[i].uid + "','" + GridName + "')" + ' class="checkbox checkbox-success input-group"><input class="form-check-input" type="checkbox" id="Ch' + GridColumns[i].uid + '">';
} else {
CheckBoxType = '<div onclick=' + "ShowHideColumnSet('" + GridColumns[i].uid + "','" + GridName + "')" + ' class="checkbox checkbox-success input-group"><input class="form-check-input" type="checkbox" id="Ch' + GridColumns[i].uid + '" checked>';
}
var ColumnDiv = $(item).parent().closest("div");
if (ColumnDiv.hasClass("k-grid-header-locked")) {
LockSignType = '<i onclick=' + "LockUnlockColumn('" + GridColumns[i].uid + "','" + GridName + "')" + ' class="cLocked fa fa-lock pull-right"></i>';
} else {
LockSignType = '<i onclick=' + "LockUnlockColumn('" + GridColumns[i].uid + "','" + GridName + "')" + ' class="cLocked fa fa-unlock pull-right"></i>';
}
Col_uid = GridColumns[i].uid;
ColumnMenuListHTML += '<li id="li' + Col_uid + '" class="d-flex justify-content-between"><a class="dropdown-item dropdown-toggle">' + CheckBoxType + '<label>' + $(item).text() + '</label></div></a>' + LockSignType + '</li>';
}
}
});
// send html inside the ul element
$("#ColumnSettingsList").html(ColumnMenuListHTML);
// Grid filter areas
var FilterColumnDropdown = "";
$("." + PageName + " #" + GridName + " .k-header").each(function(i, item) {
for (var i = 0; i < GridColumns.length; i++) {
if (GridColumns[i].uid == $(item).attr("id") && GridColumns[i].title != undefined) {
FilterColumnDropdown += '<option value="' + GridColumns[i].field + '">' + GridColumns[i].title + '</option>';
}
}
});
$("#SutunBilsisiList").html(FilterColumnDropdown);
}
// Open/close column settings
function ShowColumnSettingDropdown(id) {
var ColumnSetFirsDD = $("#ColumSettingsFirsDD");
if (ColumnSetFirsDD.hasClass("MenuShow")) {
ColumnSetFirsDD.removeClass('MenuShow');
$("#ColumnSettingsList").removeClass('MenuShow');
$("#FiltreSettingsList").removeClass('MenuShow');
} else {
ColumnSetFirsDD.addClass('MenuShow');
}
}
// Show/hide show/hide settings
function ShowColumShowSetting() {
var ColumnShowSet = $("#ColumnSettingsList");
if (ColumnShowSet.hasClass("MenuShow")) {
ColumnShowSet.removeClass('MenuShow');
} else {
ColumnShowSet.addClass('MenuShow');
$("#FiltreSettingsList").removeClass('MenuShow');
}
}
// Show/hide filter settings
function ShowFilterSetting() {
var Liste = $("#FiltreSettingsList");
if (Liste.hasClass("MenuShow")) {
Liste.removeClass('MenuShow');
} else {
Liste.addClass('MenuShow');
$("#ColumnSettingsList").removeClass('MenuShow');
}
}
// Clear filter areas
function ColumnMenuFiltreTemizle() {
$("#FiltreBirinciAlan").val("");
$("#FiltreIkinciAlan").val("");
}
// Column Menu grid filtering
function ColumnMenuFiltrele() {
// Grid value
var grid = $("#Grid_SipHareketleri_" + SiparisKaydet_SiparisUstIDOku()).data("kendoGrid");
var gridDataSource = grid.dataSource;
var SelectedRow = $("#SutunBilsisiList").val();
var BirinciAlan = $("#FiltreBirinciAlan").val();
var IkinciAlan = $("#FiltreIkinciAlan").val();
var Con1 = $("#ColumnFiltreCond1").val();
var Con2 = $("#ColumnFiltreCond2").val();
var filter = {
logic: Con1,
filters: []
};
var FilterField = SelectedRow;
var filterOperator = Con2;
filter.filters.push({
field: FilterField,
operator: filterOperator,
value: BirinciAlan,
});
filter.filters.push({
field: FilterField,
operator: filterOperator,
value: IkinciAlan,
});
if (BirinciAlan == "" || IkinciAlan == "") {
gridDataSource.filter([]);
} else {
gridDataSource.filter(filter);
}
}
// Lock/unclock Column
function LockUnlockColumn(ColumnID, GridName) {
// ID of Li element
var Li_id = "#li" + ColumnID;
// Grid value
var grid = $("#" + GridName).data("kendoGrid");
// i element that show lock/unlock
var i_el = $(Li_id).children().closest('i');
// Lock or unlock
if (i_el.hasClass("fa-lock")) {
grid.unlockColumn($("#" + ColumnID).data("field"));
i_el.removeClass("fa-lock");
i_el.addClass("fa-unlock");
} else {
grid.lockColumn($("#" + ColumnID).data("field"));
i_el.removeClass("fa-unlock");
i_el.addClass("fa-lock");
}
}
// Show/Hide Column
function ShowHideColumnSet(ColumnID, GridName) {
// Column th element
var id = "#Ch" + ColumnID
// Grid Value
var grid = $("#" + GridName).data("kendoGrid");
// CheckBox
var CheckBoxVal = $(id);
// CheckBox show/hide
if (CheckBoxVal.is(':checked')) {
CheckBoxVal.removeAttr("checked");
// Seçilen satırı gizleme işlemi
grid.hideColumn($("#" + ColumnID).data("field"));
} else {
CheckBoxVal.attr('checked', 'checked');
grid.showColumn($("#" + ColumnID).data("field"));
}
}
.ColMenuDropDown {
position: relative;
display: inline-block;
}
#ColumSettingsFirsDD {
display: none;
position: absolute;
z-index: 999;
background-color: #f1f1f1;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
min-width: 110px;
}
#ColumnSettingsList {
position: absolute;
min-width: 250px;
height: 290px;
overflow-y: scroll;
overflow-x: scroll;
right: -253px;
top: 6px;
}
.dropdown-toggle::after {
display: none;
}
.ColumnMenuFiltre {
width: 300px;
padding: 0.5em;
}
.MenuShow {
display: block !important;
}
.cLocked {
font-size: 16pt;
padding: 6px;
}
<script src="https://kendo.cdn.telerik.com/2022.3.913/js/kendo.all.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<link href="https://kendo.cdn.telerik.com/2022.3.913/styles/kendo.default-v2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ColMenuDropDown">
<button id="GorunumAyarlaBtn" type="button" title="Görünüm Ayarla" name="GorunumAyarla" class="btn-primary btn btn-xs btn-default" style="margin-left:2px;" onclick="ShowColumnSettingDropdown();">
<i class="fa fa-clone"></i> Column Menu
</button>
<ul id="ColumSettingsFirsDD">
<li class="dropdown-submenu">
<a id="GorunumColumnMenuBtn" class="dropdown-item dropdown-toggle" href="#" onclick="ShowColumShowSetting();">Columns</a>
<ul id="ColumnSettingsList" class="dropdown-menu">
</ul>
</li>
<li class="dropdown-submenu">
<a id="GorunumFiltreMenuBtn" class="dropdown-item dropdown-toggle" href="#" onclick="ShowFilterSetting();">Filter</a>
<ul id="FiltreSettingsList" class="dropdown-menu">
<li>
<div class="ColumnMenuFiltre">
<span class="text-center"><b>show variables between this and this</b></span>
<div class="row mt-2">
<div class="col-sm-12">
<label>Filtered Column</label>
<select id="SutunBilsisiList" class="form-select">
</select>
</div>
</div>
<div class="row mt-2">
<div class="col-sm-12">
<label>1. Value</label>
<input id="FiltreBirinciAlan" class="form-control form-group-sm" type="text" />
</div>
</div>
<div class="row mt-2">
<div class="col-sm-4">
<select id="ColumnFiltreCond1" class="form-select">
<option value="and">and</option>
<option value="or">or</option>
</select>
</div>
<div class="col-sm-8">
<select id="ColumnFiltreCond2" class="form-select">
<option value="eq">Equal</option>
<option value="neq">Not Equal</option>
<option value="startswith">Starts With</option>
<option value="endswith">Ends With</option>
<option value="contains">Contains</option>
<option value="doesnotcontain">Not Contains</option>
<option value="isnull">Is Null</option>
<option value="isnotnull">Is Not Null</option>
<option value="isempty">Is Empty</option>
<option value="isnotempty">Is Not Empty</option>
<option value="hasnovalue">Has No Value</option>
<option value="hasvalue">Has Value</option>
</select>
</div>
</div>
<div class="row mt-2">
<div class="col-sm-12">
<label>2. Value</label>
<input id="FiltreIkinciAlan" class="form-control form-group-sm" type="text" />
</div>
</div>
<div class="row mt-2 d-flex justify-content-around">
<div class="col-sm-4">
<button type="button" onclick="ColumnMenuFiltrele();" class="btn btn-danger">Filter</button>
</div>
<div class="col-sm-4">
<button type="button" onclick="ColumnMenuFiltreTemizle();" class="btn btn-secondary">Clear</button>
</div>
</div>
</div>
</li>
</ul>
</li>
</ul>
</div>