Javascript Creating Element - javascript

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>

Related

jQuery - Run change function on load

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()

Can't get the temperature to change from Celsius to Fahrenheit in my local weather app

User Story: I can see the weather in my current location.
User Story: I can see a different icon or background image (e.g. snowy mountain, hot desert) depending on the weather.
User Story: I can push a button to toggle between Fahrenheit and Celsius.
These are the user stories for the website. I have managed to complete 1 and 2 but I am completely stuck on 3, I have a good idea of how I would manage to do this but I can't manage to make it work with various methods(not just the one in my code) but I think I may of coded this badly but it is the only way I know because I am new. Someone suggested to me to use an if but it doesn't work as it would only be able to change the text on document load and not continuously. This is the example. Any advice on a better way about this would be greatly appreciated and sorry for the long post.
Html:
<div class="main">
<div class="title">
<h1>Weather!</h1>
<hr />
</div>
<div class="search">
<div class="row">
<div class="col-xs-6">
<input type="text" class="form-control" placeholder="City">
</div>
<div class="col-xs-3">
<button type="button" class="btn btn-default" id="searchBtn">Search</button>
</div>
<div class="col-xs-3 checkbox" id="degrees">
<label><input type="checkbox" value="" id="fCheck">View in °F</label>
</div>
</div>
<hr />
</div>
<div class="row">
<div class="col-xs-6 content" id="temp">
<h2></h2>
<h3></h3>
<h4></h4>
<p></p>
<img src="" alt="weather icon" />
</div>
<div class="col-xs-6 info">
<h2 id="humidity"></h2>
<h2 id="windspeed"></h2>
<br>
<h2 id="sunrise"></h2>
<h2 id="sunset"></h2>
</div>
</div>
</div>
Css:
html, body {
margin: 0;
padding: 0;
font-family: 'Dosis', sans-serif;
background-color: #3f3f3f;
}
.main{
position: relative;
margin: 10% auto auto auto;
width: 75%;
text-align: center;
background-color: #8E9EBC;
padding: 10px;
border-width: 3px;
border-style: solid;
border-color: black;
border-radius: 5px;
}
.main h1 h2 h3 h4{
margin: 0;
}
.main img {
width: 100px;
}
.title hr {
border-width: 2px;
}
#degrees h4 {
text-align: left;
}
#searchBtn {
width: 100%;
}
Js:
$(document).ready(function() {
var api = "secretAPIKey";
$.getJSON("http://ip-api.com/json", function(json) {
var userCity;
userCity = JSON.stringify(json.city);
userCity = userCity.replace(/\"/g,"");
makeElementsFromCity(userCity);
});
var celsius;
var name;
var faren;
function makeElementsFromCity(userCity) {
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + userCity + "&units=metric&appid=" + api, function(json) {
name = JSON.stringify(json.name + ", " + json.sys.country);
celsius = JSON.stringify(json.main.temp);
faren = celsius * 9 / 5 + 32;
var icon = JSON.stringify(json.weather[0].icon);
var type = JSON.stringify(json.weather[0].main);
var humidity = JSON.stringify(json.main.humidity)
var windS = JSON.stringify(json.wind.speed);
var sunR = JSON.stringify(json.sys.sunrise);
var sunS = JSON.stringify(json.sys.sunset);
icon = icon.replace(/\"/g,"");
type = type.replace(/\"/g,"");
celsius = Math.round(celsius);
faren = Math.round(faren);
//get sunset and sunrise unix into time
function formatSunR(date) {
var date = new Date(date*1000);
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var formattedTime = hours + ':' + minutes.substr(-2);
return formattedTime;
};
//update h2 with city, country and temperature and testing to see what weather.icon is but comes back as undefined
//updates h3 with the type of weather & city is placeholder for testing the city variable
$("#temp h3").text(type);
//display image of weather type from https://openweathermap.org/weather-conditions
$("#temp img").attr("src", "http://openweathermap.org/img/w/" + icon + ".png");
$(".info #humidity").text("Humidity: " + humidity + "%");
$(".info #windspeed").text("Wind Speed: " + windS + " MPH");
$(".info #sunrise").text("Sunrise: " + formatSunR(sunR));
$(".info #sunset").text("Sunset: " + formatSunR(sunS));
if($("#fCheck").is(":checked")) {
$("#temp h2").text("The temperature in " + name + " is " + faren + "°F");
} else {
$("#temp h2").text("The temperature in " + name + " is " + celsius + "°C");
console.log(faren);
}
});
};
});
You can try this HTML
temp
with this JS and adapt it to your situation.
var temp = 25;
var celsius = temp;
var fahr = (1.8 * temp + 32);
var switch_ = new Boolean(false);
$("#toggle").on("click", function() {
switch_ = !switch_;
var temp = switch_ == true ? celsius + " °C" : fahr + " °F";
$(this).text(temp);
});

How to apply toolbar.js in a loop

I am trying to use toolbar.js but in a loop. Here is an example from stackoverlow
Here is my code which I am trying to apply, in this code I have a main container, in which I am creating many div dynamically and in those div I trying to put tooblar. please let me know how to make it work or what I am doing wrong.P
Thanks in advance.
HTML:
<link href="https://paulkinzett.github.io/toolbar/css/documentation.css" rel="stylesheet"/> <link href="https://paulkinzett.github.io/toolbar/css/jquery.toolbar.css" rel="stylesheet"/> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://paulkinzett.github.io/toolbar/js/jquery.toolbar.min.js"></script>
<div id="container" style="width: 550px; height: 400px; margin: 0 auto">
<h1 id=aa>
</h1>
</div>
JS:
for (var id = 0; id <= 10; id++) {
var divTool = $('<div id=toolbar-options' + id + ' class="hidden"></i></i></i></div><div data-toolbar="toolbar-options" data-toolbar-animation="flip" class="btn-toolbar feature-toolbar btn-toolbar-primary text-center" data-toolbar-style="primary" id=button' + id + '><i class="fa fa-cog" style="position: relative"></i></div>');
var div = document.createElement('div'),
h = document.createElement('h3')
divId = "id" + id,
hId = "idh" + id,
container = document.getElementById("container");
div.setAttribute("id", divId);
h.setAttribute("id", hId);
container.appendChild(div);
h.innerHTML = id;
$(div).append(h);
$(div).append(divTool);
}
$('#' + 'button' + id).toolbar({
content: '#toolbar-options',
position: 'top',
style: 'primary',
event: 'click',
hideOnClick: true
})
$('#' + 'button' + id).on('toolbarItemClick',
function(event, buttonClicked) {
alert(buttonClicked.id);
}
)
Is that is what you looking for.
JS:
for (var id = 0; id <= 10; id++) {
var div=$('<div class="btn-toolbar" style="margin:5px;"></div>');
$('#container').append(div);
$(div).toolbar({
content: '#toolbar-options',
});
}
HTML:
<div id="container" style="width: 550px; margin: 0 auto">
</div>
<div id="toolbar-options" class="hidden">
<i class="fa fa-plane"></i>
<i class="fa fa-car"></i>
<i class="fa fa-bicycle"></i>
</div>
JsFiddle

Add textboxes along with text to a table (tbody) in HTML

I am stuck in a problem where I have to create text boxes dynamically into the table cell. Along with the data which I am fetching from the DB.
It should be something like:
Number of rows are dynamic and I am able to generate it using Array. I am capturing all values into the array of records for each row and pushing it into the table. But I don't know what to do to add empty text boxes.
I was thinking if I can add "textboxes" to the array and insert along with text to the table cell. I am not sure what other options available.
I am open to answer any queries to you which might help me to get the answer.
EDIT:
Below is the code which I used to generate table:
function generateTable(fundDetails){
var tbody_holder = document.getElementById("tbody_holder");
for(var row = 0; row < fundDetails.length; row++){
var tr = document.createElement("tr");
for(var col = 0; col < fundDetails[row].length; col++){
var td = document.createElement("td");
var tn = document.createTextNode(fundDetails[row][col]);
td.appendChild(tn);
tr.appendChild(td);
}
tbody_holder.appendChild(tr);
}
}
fundDetail is a 2D array. Each element in array contains all the data for the one row of table. Next array element contains data for next row. I want to insert text boxes in each rows.
TIA
I think it will be your answer for creating the records dynamically.
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Cache-control" content="no-cache">
<script src="jquery/jquery-1.10.2.js"></script>
<script src="jquery/canvasjs.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="font-awesome/css/font-awesome.css">
<script src="jquery/jquery-ui.js"></script>
<script type="text/javascript" src="jquery/html2canvas.min.js"></script>
<script type="text/javascript" src="jquery/jquery.plugin.html2canvas.js"></script>
<link rel="stylesheet" href="jquery/jquery-ui.css">
<style>
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="text"], input[type="number"] {
border: none;
}
tbody tr{
background:#f7f7f7;
}
.navbar{
border-radius:0px !important;
border:none;
}
thead{
background:#8b99a0;
color:white;
}
.navbar{
background:#323E4E;
}
table{
border-radius:4px !important;
}
a.canvasjs-chart-credit {
display: none;
}
#chartContainer{
border-bottom:1px dashed #8b99a0;
border-right:1px dashed #8b99a0;
}
.stuck{
position:fixed;
z-index:100;
width:100%;
top:0;
}
hr {
margin-top: 0px;
margin-bottom: 0px;
}
</style>
<script>
$(window).scroll(function() {
if ($(window).scrollTop() > 50) {
$("#bar").addClass('stuck');
} else {
$('#bar').removeClass('stuck');
}
});
</script>
</head>
<body>
<nav class="navbar navbar-inverse" id="bar">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img src="images/records.png" style="width:50px;height:45px;float:left;" class="navbar-logo">
<a class="navbar-brand" href="#" title="calculation">Student Records</a>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2 style="text-align:center;color: #323E4E;">Student marksheet</h2>
</div>
<div class="col-md-12" style="margin-bottom:2px;">
<div class="col-md-2">
<button class="btn btn-primary" id="addbtn" style="float:left;margin-right:10px;"><i class="fa fa-user-plus" aria-hidden="true"></i> Add Row</button>
</div>
<div class="col-md-8">
<div class="form-group">
<input type="text" class="search form-control" id="search" placeholder="What you looking for?" style="box-shadow:5px 5px 5px #f7f7f7;">
</div>
</div>
<div class="col-md-2">
<button class="btn btn-primary" id="btnExport" style="float:right;"><a style="text-decoration:none;color:#fff;"><i class="fa fa-download"></i> Download</span></a></button>
</div>
</div>
<div class="col-md-12" style="margin-bottom:30px !important;">
<div class="col-md-10">
<div id="dvData">
<table class="table table-hover" id="tblData">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Mark1</th>
<th>Mark2</th>
<th>Total</th>
<th>Average</th>
<th>Status</th>
</tr>
</thead>
<tbody id="frm">
</tbody>
</table>
</div>
</div>
<div class="col-md-2">
<label>Result Chart</label>
<hr>
<div id="chartContainer" style="width:100%;height:200px;"></div>
</div>
</div>
</div>
</div>
</body>
<script>
var aa=0, z=1, numb=1, id="ping";
var x, ab ,bc,cd,tr,ty,tg,we ,er;
var id1,id2,id0,stat="mark",num="1";
var mnc="avg",mno="total", abcd=1;
var msg="status",pa=0,fa=0, stanum;
$("#addbtn").click(function(e){
var i=aa;
var zz=z+aa;
for(i;i<zz;i++){
var head= document.createElement("TR");
ab="tear";
bc=zz;
cd=ab.concat(bc);
head.setAttribute("id",cd);
document.getElementById("frm").appendChild(head);
var did= document.createElement("TD");
var pin=id.concat(numb);
did.setAttribute("id",pin);
document.getElementById(cd).appendChild(did);
document.getElementById(pin).innerHTML=numb;
numb++;
for(var p=0;p<6;p++){
if(p<3){
var lab= document.createElement("TD");
tr="tead";
ty=p;
we=zz;
er=tr.concat(ty);
tg=er.concat(we);
lab.setAttribute("id",tg);
document.getElementById(cd).appendChild(lab);
}else if(p==3)
{
var lab= document.createElement("TD");
tr="tead";
ty=p;
we=zz;
er=tr.concat(ty);
tg=er.concat(we);
lab.setAttribute("id",tg);
var ctot=mno.concat(abcd);
lab.setAttribute("id",ctot);
document.getElementById(cd).appendChild(lab);
}else if(p==4)
{
var lab= document.createElement("TD");
tr="tead";
ty=p;
we=zz;
er=tr.concat(ty);
tg=er.concat(we);
lab.setAttribute("id",tg);
var cpo=mnc.concat(abcd);
lab.setAttribute("id",cpo);
document.getElementById(cd).appendChild(lab);
}else if(p==5)
{
var lab= document.createElement("TD");
var meg=msg.concat(i);
lab.setAttribute("id",meg);
document.getElementById(cd).appendChild(lab);
}
if(p==0)
{
x= document.createElement("INPUT");
x.setAttribute("type","text");
id0=stat.concat(num);
num++;
x.setAttribute("id",id0);
document.getElementById(tg).appendChild(x);
}else if(p==1)
{
x= document.createElement("INPUT");
x.setAttribute("type","number");
id1=stat.concat(num);
num++;
x.setAttribute("id",id1);
document.getElementById(tg).appendChild(x);
}else if(p==2)
{
x= document.createElement("INPUT");
x.setAttribute("type","number");
id2=stat.concat(num);
num++;
x.setAttribute("id",id2);
document.getElementById(tg).appendChild(x);
}
}
}
abcd++;
aa++;
});
var xx;
$("#tblData").change(function(e){
var n=1;var qq=0;xx=0;
for(var rr=1;rr<=aa;rr++){
var m0=stat.concat(n);
n++;
var m1=stat.concat(n);
n++;
var m2=stat.concat(n);
n++;
var az=document.getElementById(m0).value;
document.getElementById(m0).innerHTML=az;
var a=document.getElementById(m1).value;
document.getElementById(m1).innerHTML=a;
var b=document.getElementById(m2).value;
document.getElementById(m2).innerHTML=b;
if(a=="")
{
a=0;
}else if(b==""){
b=0;
}
else{}
var c=Number(a)+Number(b);
var d=(Number(a)+Number(b))/2;
var mp=mno.concat(rr);
document.getElementById(mp).innerHTML=c;
var cp=mnc.concat(rr);
document.getElementById(cp).innerHTML=d;
stanum=msg.concat(qq);
if((a<50)||(b<50)){
document.getElementById(stanum).innerHTML="Fail";
qq++;
}else{
document.getElementById(stanum).innerHTML="Pass";
qq++;
}
}
xx=qq;
});
$("#tblData").change(function(e){
fa=0,pa=0;
var county=$('#tblData tr').length;
for(var mob=0;mob<county-1;mob++){
var mom=msg.concat(mob);
if(document.getElementById(mom).innerHTML=="Pass"){
pa++;
}
if(document.getElementById(mom).innerHTML=="Fail"){
fa++;
}
}
var chart = new CanvasJS.Chart("chartContainer",
{
animationEnabled: true,
title:{
text: "students vs pass / fail"
},
data: [
{
type: "column", //change type to bar, line, area, pie, etc
dataPoints: [
{ label: "pass", y: pa },
{ label: "fail", y: fa }
]
}
]
});
chart.render();
});
</script>
<script type="text/javascript">
$("#resbtn").click(function(e){
html2canvas($("#tblData"), {
onrendered: function(canvas) {
theCanvas = canvas;
canvas.toBlob(function(blob) {
saveAs(blob, "pretty image.png");
});
}
});
});
</script>
<script>
$(document).ready(function()
{
$('#search').keyup(function()
{
searchTable($(this).val());
});
});
function searchTable(inputVal)
{
var table = $('#tblData');
table.find('tr').each(function(index, row)
{
var allCells = $(row).find('td');
if(allCells.length > 0)
{
var found = false;
allCells.each(function(index, td)
{
var regExp = new RegExp(inputVal, 'i');
if(regExp.test($(td).text()))
{
found = true;
return false;
}
});
if(found == true)$(row).show();else $(row).hide();
}
});
}
</script>
<Script>
$("#btnExport").click(function (e) {
var dt = new Date();
var day = dt.getDate();
var month = dt.getMonth() + 1;
var year = dt.getFullYear();
var hour = dt.getHours();
var mins = dt.getMinutes();
var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
//creating a temporary HTML link element (they support setting file names)
var a = document.createElement('a');
//getting data from our div that contains the HTML table
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('dvData');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html;
//setting the file name
a.download = 'exported_table_' + postfix + '.xls';
//triggering the function
a.click();
//just in case, prevent default behaviour
e.preventDefault();
});
</script>
</html>

How to access Kendo Grid's column menu only from outside the grid and add the filter option for specific columns in the column header

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>

Categories

Resources