add a class to one particular li element - javascript

I have an unordered list which is dynamically created, and I need to add a class called 'selected' to one particular -li-.
The -ul- is a list of the Days of the Week, and the -li- that needs to be selected is the current day. Unfortunately I can't figure out how to add this class to just the one element, and the entire list disappears whenever I try to add this class. Here's my code:
var weekday = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var today = day.getDay();
for(var x=0;x<=6;x++){
$('ul').append(
$('<li>')
.toggleClass(function(){
if(today == x){ return 'selected'; }
else{ return ''; };
});
.append( $('' + weekday[x] + ''));
);
$('li:last').addClass('last-child');
Can someone help me figure out how to add this class to just the current day's -li-?

if(today = x)
= assign
== compares
Another way of doing it:
var weekday = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var lis = [];
var today = new Date().getDay();
jQuery.map( weekday,
function( day, ind ){
var cls = ind===today ? " class='selected'" : "";
lis.push( "<li><a" + cls +" href='#" + day.toLowerCase() + "'>"+ day + "</a></li>" );
}
);
$("ul").html( lis.join("") );

Following the advice from the other comments and fixing some errors fixed the code:
var weekday = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
today = new Date().getDay(),
list = $('ul');
for(var x=0;x<=6;x++){
list.append(
$('<li></li>', {
html : '' + weekday[x] + ''
}).toggleClass(function(){
if(today == x){
return 'selected';
}
}).bind('click', function(e){
e.preventDefault();
$(this).parent().children('li').removeClass('selected');
$(this).addClass('selected');
})
);
}
$('li:last').addClass('last-child');

Is day defined as new Date?
var day = new Date();
or var today = new Date().getDay();

Try that:
var weekday = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var d = new Date();
var today = d.getDay();
for(var x=0;x<=6;x++){
$('ul').append(
$('<li>' + weekday[x] + '')
);
$('li:last-child').addClass('last-child');
if(x == today)
{
$('li:gt('+(x - 1)+')').toggleClass('selected');
}
}

Related

Deleting an object from an array on click of a button

I am trying to create my own small Twitter.
It is all working fine but I cannot find a way to delete specific tweet on click of a button. I have tried splice() but it deletes the first object of an array always.
Here is my code:
var tweets = []
function postNewTweet() {
var today = new Date();
var date = today.getDate() + '-' + (today.getMonth() + 1) + '-' + today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes();
var id = tweets.length + 1;
var li = document.createElement('li');
var inputValue = document.getElementById('newTweet').value;
var finalValue = id + ' ' + inputValue + ' ' + date + ' ' + time;
var t = document.createTextNode(finalValue);
li.appendChild(t);
tweets.push({
id: id,
content: inputValue,
date: date + ' ' + time
});
document.getElementById('list').appendChild(li);
document.getElementById('newTweet').value = "";
console.log(tweets);
var buttonDelete = document.createElement("button");
buttonDelete.innerHTML = '<i class="far fa-trash-alt"></i>';
buttonDelete.onclick = deleteItem;
function deleteItem(e) {
var ul = document.getElementById('list');
ul.removeChild(li);
var list = document.getElementById('list');
list.addEventListener('click', function(e) {
var index = e.target.getAttribute('value');
tweets.splice(index, 1);
console.log(tweets)
});
}
li.appendChild(buttonDelete);
}
<div id='post'>
<textarea maxlength="160" id='newTweet'></textarea>
<button id='postIt' onclick="postNewTweet()">Post</button>
</div>
<ul id='list'>
</ul>
So it deletes it in HTML, but not in array correctly.
The second part of your deleteItem function's body seems useless. While there are couple of ways to resolve it, I suggest the following:
function deleteItem(e) {
var ul = document.getElementById('list');
ul.removeChild(li);
var foundIndex = tweets.findIndex(function (tweet) {
return tweet.id == id;
});
if (foundIndex > -1) {
tweets.splice(foundIndex, 1);
}
}
There are two issues:
If you just take the length of the array as the id you will get duplicate entries, if you delete an entry. Perhaps go to a timestamp - i just used the one you already had there but added seconds
You retrieve the value-attribute but for splice you need the index of the element. I just added the timestampt as an attribute to the button and used it for removal.
Probably not my best code but I hope it gives you the right hints.
var tweets = []
function postNewTweet() {
var today = new Date();
var date = today.getDate() + '-' + (today.getMonth() + 1) + '-' + today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
var id = tweets.length + 1;
var li = document.createElement('li');
var inputValue = document.getElementById('newTweet').value;
var finalValue = id + ' ' + inputValue + ' ' + date + ' ' + time;
var t = document.createTextNode(finalValue);
li.appendChild(t);
tweets.push({
id: id,
content: inputValue,
date: date + ' ' + time
});
document.getElementById('list').appendChild(li);
document.getElementById('newTweet').value = "";
console.log(tweets);
var buttonDelete = document.createElement("button");
buttonDelete.innerHTML = '<i class="far fa-trash-alt" del-date="'+date + ' ' + time +'">del</i>';
buttonDelete.onclick = deleteItem;
function deleteItem(e) {
var ul = document.getElementById('list');
ul.removeChild(li);
var list = document.getElementById('list');
list.addEventListener('click', function(e) {
var delDate = e.target.getAttribute('del-date');
let index = tweets.map((item) => item.date).indexOf(delDate);
console.log(index);
tweets.splice(index, 1);
console.log(tweets)
});
}
li.appendChild(buttonDelete);
}
<div id='post'>
<textarea maxlength="160" id='newTweet'></textarea>
<button id='postIt' onclick="postNewTweet()">Post</button>
</div>
<ul id='list'>
</ul>
As you have access to li in your delete function, you have access to all the other data too. You can use them to find out the element to remove from the tweets array.
For example, in your current code, you can use the id:
tweets.splice(id - 1, 1)
Or you can use filter with any of the data that you store in tweets.And I don't see any use for this part:
var list = document.getElementById('list');
list.addEventListener('click', function(e) {
var index = e.target.getAttribute('value');
tweets.splice(index, 1);
console.log(tweets)
});
You can just remove the tweet under the ul.removeChild

Amchart4 not shown till end of Datatime From json file in parseend event

I looking for solution to shown all my data in amcharts4 , My data not shown exact and just sme out before them is shown , what is soltion for them ?
chart.dataSource.url ="/static/json/{{ Post.Datasource|safe }}.json";
chart.dataSource.parser = new am4core.JSONParser();
chart.dataSource.reloadFrequency = 5000;
chart.dateFormatter.inputDateFormat = "i";
var title = chart.titles.create();
//Funtion Date From and to
chart.dataSource.events.on("parseended", function(ev) {
var data = ev.target.data;
for (var i = 0; i < data.length; i++) {
var startdate = new Date(data[0]["DATETIME"]).toISOString().replace("T"," ").replace("Z","").replace(".000","");
var enddate = new Date(data[data.length -1]["DATETIME"]).toISOString().replace("T"," ").replace("Z","").replace(".000","");
}
title.html = (
"Data from :" + '<span class="colors"> ' +
startdate+ '</span> ' +
" to " + '<span class="colors">' +
enddate + '</span>'
);
});
Text shown less than exact lenght of data, also my title not refreshed
Moment library can convert data easy
starttime = moment(starttime).format("YYYY-MM-DD HH:mm:ss");

Jquery Clone method increment name tag

Hello I am trying to add increment in my all form fields from zero to the number whenever I add new clone it assigns the next number to the name tag, I tried all the ways but no any methods works for me.
Here is my fiddle
https://jsfiddle.net/o5wam5r2/
and here is my JS code
var formItem;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name="txtSchedule"]').val();
cloneForm.find('[name="txtSchedule"]').val(addOneMonth(date));
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var year = parseInt(date.split("-")[0]);
var month = parseInt(date.split("-")[1]) + 1;
var day = parseInt(date.split("-")[2]);
if(month > 12) {
month = month - 12;
year++
}
return year + "-" + month + "-" + day;
}
I fixed it by changing a little piece of code
var formItem;
var counter = 0;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
formItem.find('[name^=txtSchedule]')[0].name = "txtSchedule" + counter;
formItem.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + counter;
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var lens = counter++;
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name^="txtSchedule"]').val();
cloneForm.find('[name^="txtSchedule"]').val(addOneMonth(date));
cloneForm.find('[name^=txtSchedule]')[0].name = "txtSchedule" + (lens+1);
cloneForm.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + (lens+1);
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var d = new Date( date );
d.setMonth( d.getMonth( ) + 1 );
return d.getFullYear() + '-' + ("0" + ((d.getMonth() + 1))).slice(-2) + '-' + ("0" + (d.getDate())).slice(-2);
}

Unable to Loading jquery datepicker on google maps

I am unable to load the datepicker on google maps
Here is the code
JS
function CreateMapTopControl(controlDiv, controlElement, controlId, map, event, response) {
controlDiv.style.padding = '5px';
var controlUI = document.createElement(controlElement);
controlUI.id = controlId;
controlDiv.appendChild(controlUI);
google.maps.event.addDomListener(controlUI, event, function() {
response();
return false;
});
return controlUI;
}
$(document).ready(function() {
maplct.initialize(document.getElementById('mapDiv'));
var dateDiv = document.createElement('div');
dateSel = new CreateMapTopControl(dateDiv, "input", "dateId", maplct.mapObject, "change", getMapRoute);
dateDiv.index = 2;
maplct.mapObject.controls[google.maps.ControlPosition.TOP].push(dateDiv);
$(dateSel).attr("type", "text")
$(dateSel).attr("style", "height:15px;width:100px;");
var curDate = new Date();
var d = curDate.getUTCDate();
var dd = (d < 10) ? "0" + d : d;
var m = curDate.getUTCMonth() + 1;
var mm = (m < 10) ? "0" + m : m;
var YYYY = curDate.getUTCFullYear();
var formattedDate = YYYY + "-" + mm + "-" + dd;
$(dateSel).val(formattedDate);
$(dateSel).datepicker({dateFormat: 'yy-mm-dd'});
$(dateSel).datepicker( "refresh" );
});
Map is getting loaded at the end of the file, it looks like css is not applied.

javascript change textbox value onchange

I have a StartDate and an ExpiryDate textbox. Both take values in the forms of 10/12/2013.
What I would like to be able to do is, when you change the StartDate textbox (whether from empty or just updating the date) the ExpiryDate textbox needs to add 1 year onto the date.
Example:
If StartDate = 10/12/2013 then ExpiryDate will automatically change to 10/12/2014.
How to do that with JS?
function MyFunc() {
MyTextBox = document.getElementById("<%= TextBox1.ClientID %>");
MyTextBox2 = document.getElementById("<%= TextBox2.ClientID %>");
var date = new Date(MyTextBox.value);
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear() + 1;
MyTextBox2.value = day + "/" + month + "/" + year;
}
Try this, call the setExpiryDate() function whenever you need to set the expiration date.
function setExpiryDate() {
var txtStartDate = document.getElementById("ctrl1");
var txtExpiryDate = document.getElementById("ctrl2");
var dt = new Date(txtStartDate.value);
if (!isNaN(dt)) {
dt = dt.setYear(dt.getYear() + 1);
txtExpiryDate.value = padStr(temp.getDate()) + '/' + padStr(temp.getMonth() + 1) + '/' + temp.getFullYear().toString();
}
}
function padStr(i) {
return (i < 10) ? "0" + i : "" + i;
}
How about this:
function updateInput(value){
document.getElementsById('Yourelement').Value = value;
}
Other than that, all you need is some date parsing/string manipulation to find the correct year.

Categories

Resources