How to replace a default date with an empty string - javascript

I have a html span that display a date using moment.js in the page:
<span data-bind="text: moment(new Date(dueDate())).format('MM/DD/YYYY')"></span>
It's working fine apart if the dueDate() property is an empty string, If it's an empty string I'm getting:
01/01/1900
How can avoid that?
This is the entire div:
<div class="col-md-8">
<ul>
<li>DATE <span data-bind="text: moment(new Date(sDate())).format('MM/DD/YYYY')"></span></li>
<li>Due date <span></span><span data-bind="text: moment(new Date(dueDate())).format('MM/DD/YYYY')"></span>
<p>Days Remaining: <span class="days-remaining" data-bind="text: daysRemaining"></span></p>
</li>
<li>Date 2 <span></span><span data-bind="text: moment(new Date(date2())).format('MM/DD/YYYY')"></span>
<p>Days Remaining: <span class="days-remaining" data-bind="text: daysRemaining"></span></p>
</li>
</ul>
</div>

You will have to add a check. If value exists, then parse value, else show blank.
this.getDateInFormat = function(str){
var d = moment(str, DEFAULT_FORMAT);
return str && d.isValid() ? d.format('MM/DD/YYYY') : '';
}
As commented before, you should move all parsing logic to your viewModel. This way your code is generic and your view is clean.
JSFiddle.

Related

Display an array with string list vertically knockoutjs

I got self.PatrolList = ko.observableArray() which contains:
//value
0: {DateAdd: 'Tuesday, 01 November 2022', sessionList: Array(2)}
1: {DateAdd: 'Wednesday, 02 November 2022', sessionList: Array(4)}
//sessionList value
Array(2)
0: "Patrol_011122168"
1: "Patrol_011122256"
Now, I want to display them. The problem is sessionList value displaying in a string:
View:
<div class="overflow-auto body-overflow" data-bind="foreach:PatrolList">
<div class="timeline-date" data-bind="text: DateAdd"><i class="fa fa-calendar text-success"></i></div>
<ul>
<li class="timeline-content" data-bind="text: sessionList"></li>
</ul>
</div>
How do I split them by (,) and display vertically. What I want to achieve :
Tuesday, 01 November 2022
-Patrol_011122168
-Patrol_011122256
If you use another loop on ul, you can use $data to get the current value.
class ViewModel {
sessionList = [
"Patrol_011122168",
"Patrol_011122256",
]
}
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: sessionList">
<li class="timeline-content" data-bind="text: $data"></li>
</ul>
Found the answer.
I just have to tweak my view a little bit:
<div class="overflow-auto body-overflow" data-bind="foreach:PatrolList">
<div class="timeline-date" data-bind="text: DateAdd"><i class="fa fa-calendar text-success"></i> 28 Dec</div>
<ul data-bind="foreach: $data.sessionList">
<li class="timeline-content" data-bind="text: $data"></li>
</ul>
</div>
Funnily, I got the solution seconds after posting this questions.

Missing a step to get value to loop

I have this section of js code that I am having an issue with. If I bind-data in my html to fields.timeStamp.value I get the correct values to display in each row on the web page. How ever if I data-bind to conTime1 I get a repeat of the first value instead of it converting each lines value.
JavaScript
records.forEach(function (record){
var fields = record.fields;
var timeStamp = fields['timeStamp'].value
var conTime = new Date(timeStamp)
conTime1 = conTime.toString();
});
HTML
<div class="two columns">
<p><span data-bind="text: fields.timeStamp.value"></span></p>
</div>
<div class="four columns">
<p><span data-bind="text: conTime1"></span></p>
</div>
I am sure it some thing simple that I am missing.
You need to access the record's conTime1, like this:
record.conTime1 = conTime.toString();

Grabbing number from selected class based on string match

I need to grab the number between [ and ] within the selected class of an li list, and store the number in a variable. I've tried the following, but I'm missing something. I'm not sure of the regex required to look between brackets and grab a string.
Javascript
var assetID = $(".selected:contains('on-air-date').find('[]');
HTML
<ul id="asset-list" class="expandable selectable normal" style="height: 671px;">
<li class="selected">
<div class="thumb">
<a href="/content/assets/750">
<img src="https://www.google.com/images/srpr/logo11w.png">
</a>
</div>
<div class="title">
<div>
<strong>Title of story</strong>
<br>
<span class="on-air-date">
On air: 10/28/14 05:30:00pm
[750]
</span>
<br>
<span class="blue radius label">Staging</span>
<span class="green radius label">Live</span>
</div>
</div>
</li>
<li>
<div class="thumb">
<a href="/content/assets/4200">
<img src="https://www.google.com/images/srpr/logo11w.png">
</a>
</div>
<div class="title">
<div>
<strong>Another story title</strong>
<br>
<span class="on-air-date">
On air: 12/10/14 02:09:18pm
[4200]
</span>
<br>
<span class="blue radius label">type label</span>
</div>
</div>
</li>
<li>
<div class="thumb">
<a href="/content/assets/4201">
<img src="https://www.google.com/images/srpr/logo11w.png">
</a>
</div>
<div class="title">
<div>
<strong>Yet another story title</strong>
<br>
<span class="on-air-date">
On air: 12/10/14 02:09:18pm
[4201]
</span>
<br>
<span class="blue radius label">type label</span>
</div>
</div>
</li>
</ul>
JSFiddle: link
Your current code is invalid, as :contains is used to look for a text value within an element, not a class. You need to use find() and text() to retrieve the value in the element. From there you can use a regular expression to extract the value in the braces. Try this:
var selectedAirDateText = $('.selected').find('.on-air-date').text();
var matches = /\[(.+)\]/gi.exec(selectedAirDateText);
console.log(matches[1]); // = '750'
Example fiddle
A regular expression can help you get the number as follows:
var num = $('.selected span.on-air-date').text().replace(/[^\[]*\[(\d+)\].*/,'$1');
Demo
:contains('on-air-date') not valid, you cannot use contains to access the child elements with the specified class. Also .find('[]') not valid. The following code worked for me:
$('.selected').click(function () {
var assetID = $(this).find('.on-air-date').text().split('[')[1].replace(']', '');
//this first splits the text into two by '['
//then we get the second half by [1]
//finally we remove the last character ']' by using .replace
alert(assetID);
})
Demo: https://jsfiddle.net/k3keq3vL/1/
You'll need to first get the single item you need or run an $.each to get all in the page.
//run the each statement
$(".on-air-date").each(function(index,value) {
//set the string (str) variable to the value's text which is inside the <span>
var str = $(value).text();
// match the string with [ ] with anything inside. and then remove the last ]. Then take the substring of the content after the [
var value = str.match(/\[(.*?)\]/g)[0].replace(/\]/g,'').substring(1,str.length-1));
});
http://jsfiddle.net/k3keq3vL/8/
Open your console to see the list of numbers returned in the console.log of the string match and substring

Count specific characters within a class (and apply text truncate logics to each instance of that class)

I have HTML like
<a href="/blabla" class="matchupLink">
<span class="teams"> USA</span>
<strong> -0 </strong>
<span class="teams">Netherlands</span>
<span class="pull-right dateOrScore"><strong>15 Jul</strong> : 3:00pm CST</span>
</a>
<a href="/blabla2" class="matchupLink">
<span class="teams"> USA</span>
<strong> -0 </strong>
<span class="teams">Netherlands</span>
<span class="pull-right dateOrScore"><strong>15 Jul</strong> : 3:00pm CST</span>
</a>
<a href="/blabla3" class="matchupLink">
<span class="teams"> USA</span>
<strong> -0 </strong>
<span class="teams">Netherlands</span>
<span class="pull-right dateOrScore"><strong>15 Jul</strong> : 3:00pm CST</span>
</a>
I want to count the number of characters that's inside each "matchupLink" class, but without counting the characters inside the "dateOrScore" class.
My goal is to then cut the text and put ellipses after char 20 if char count is over 20 characters, while keeping the date (dateOrScore) element there.
I tried something like
$('.matchupLink .teams').each(function () {
console.log($(this).html())
});
But that returns every teams element individually, can't really use the ellipses logics that way.
Any ideas?
Thanks
Ps: I also tried taking all text, and excluding 'dateOrScore' (using not()) but that also failed.
Is this what you want?
var ellipses = 20;
$('.matchupLink').children().not('.dateOrScore').each(function() {
var text = $(this).text();
if(text.length > ellipses)
$(this).text(text.substr(0, ellipses) + '...');
});

If I can only use javascript, how can I filter list by date?

I have this list structure:
<ul class="pol list">
<li>
<div class="tekst">
<h2><span class="name"></span></h2>
<p class="description"></p>
<div class="commentsBar1">
<div class="commentsBarL1">
<h5>
<strong class="category">
<span style="display:none;"></span>
<span class="d">27.12.2011</span>
</strong>
</h5>
<h5><strong></strong></h5>
</div>
</div>
</div>
</li>
<li>
<div class="tekst">
<h2><span class="name"></span></h2>
<p class="description"></p>
<div class="commentsBar1">
<div class="commentsBarL1">
<h5>
<strong class="category">
<span style="display:none;"></span>
<span class="d">03.03.2012</span>
</strong>
</h5>
<h5><strong></strong></h5>
</div>
</div>
</div>
</li>
</ul>
I need js that will hide all list tags which contain a date outside of a certain range. The date range is given by user and both start and end dates are given in same way as dates in the list (dd.mm.yyyy).
<input id="Date1" name="Date1">
<input id="Date2" name="Date2">
I have this date comparison code:
var dControl = document.getElementsByClassName("d");
var d1Control = document.getElementById("Date1");
var d2Control = document.getElementById("Date2");
var arrD = dControl.value.split(".");
var dd0 = new Date(arrStartDate[2], arrStartDate[1], arrStartDate[0]);
var arrD1 = d1Control.value.split(".");
var dd1 = new Date(arrStartDate[2], arrStartDate[1], arrStartDate[0]);
var arrD2 = d2Control.value.split(".");
var dd2 = new Date(arrStartDate[2], arrStartDate[1], arrStartDate[0]);
if((dd0 <= dd2 && dd0 >= dd1)) {
return true;
}
return false;
And one more thing... The number of list elements varies from page to page so I also need to get some idea about the list size, but that I assume is easy to do with "length".
Any ideas how can I achieve this?
You will need to write javascript to build the dom based on the dates you have. I suggest using a templating framework such as mustache or handlebars to keep your code tidy.
just run through the elements with class "d" and check if they meet your date criteria if not then set that li to display "none". you will have to find the li in the DOM node tree which appears to be 8 levels higher that your date.

Categories