only first value is changed when iterating through express-handlebars each - javascript

I am using express-handlebars in my node application. In one of my forms I am storing data in the format 2018-12-01 (YYYY MM DD) as a string. I am also storing time as string in 24 hour format 13:45:00
I have defined a script to use moment for changing the date format:
<script type="text/javascript">
(function () {
var NowMoment = $('#displayMoment').val();
var Date = moment(NowMoment);
var eDisplayMoment = document.getElementById('output');
// display output in the preferred format
eDisplayMoment.innerHTML = Date.format('MMM Do YYYY');
})();
</script>
in my .handlebars template I am displaying the data received using the following code:
{{#each tasks}}
<input id="displayMoment" value="{{taskDate}}" hidden>
<p>{{taskName}} {{taskDate}} {{taskTime}} {{taskStatus}} <span id="output"></span>
<a class="btn u-btn-primary g-rounded-50 g-py-5" href="/starttask/{{id}}">
<i class="fa fa-edit g-mr-5"></i> start task
</a>
</p>
{{/each}}
as you can see I have a hidden input which is assigned the {{taskDate}}, I fetch its value in the script and format it to display in the span tag.
The Problem is:
Only the first task is formatting the date and showing it, the second or consecutive tasks do not show the formatted date.

The id cannot be the same. The HTML specification requires it to be unique. So can lets remove the id attribute from your span and input elements and instead give them an appropriate class attribute definition instead:
<span class="output"></span>
<input class="displayMoment" value="{{taskDate}}" hidden>
Then lets use getElementsByClassName(...) instead of document.getElementById(...) since according to the documentation, getElementById() returns a single element object representing the element whose id property matches the specified string. Assuming a 1 to 1 relationship between input values and the spans we are trying to change the value for we can do something along the lines of this:
<script type="text/javascript">
(function () {
var inputEles = document.getElementsByClassName("displayMoment");
var spanEles = document.getElementsByClassName("output");
for(var i=0; i<spanEles.length; i++) {
var Date = moment(inputEles[i].value);
spanEles[i].innerHTML = Date.format('MMM Do YYYY');
}
})();
</script>
Hopefully that helps!

Related

Change the return value for a particular field

I have a few JavaScript functions like the one below...
<input type="text" id="myField">
<script>
$("#myField").val("10:20:30");
function doNotEditIt(fieldId){ // this function can't be edited!
var myVar = $("#" + fieldId).val(); // it's 10:20:30, i want 10.2030
// ... code which converts the value
}
</script>
...which I can't edit or change them, because they are universal for all of my previous fields. I want add new fields to my page (like myField; see below) and use functions which are not customised specifically for them.
Is it possible to change the format of a returning value? For example...
$("#myField").changeReturningFormat(function(){
// ... code which change format
});
...or change the display format? For example...
$("#myField").val('10.2030'); // a user will see 10:20:30
Check the below sample, you just need to use replace():
var str = "10:20:30";
str = str.replace(/:/, '.');
console.log(str.replace(/:/, ''))

Is it possible to get a value from append/html function

Html Code
<div id="price-tag"><i class="fa fa-inr"></i> <span id="price"></span></strong></div>
have a java script function that append value to a span
$("#price").html(Price);
Now I want to get the price value -
java script code
document.getElementById('price-tag').onclick = function(e){
alert(document.getElementById('price').value);
}
its returning undefined.
is there any way to get the value?
span is not an input, hence it haves no value. You should work with it's innerText as you are dealing with element's text content:
$("#price").text(Price);
var price = $("#price").text();
// Or
document.getElementById('price').innerText = Price;
var price = document.getElementById('price').innerText;

How to get the text with in span tag using jquery?

I want get text within this span tag using its class:
<span id="prizevalue_g12" class="pull-right grid_val">£12</span>
I want to get 12. I tried the below code:
var ex_price = $(".grid_val").html();
and
ex_price = $(".grid_val").html();
You can use replace() to remove £.
$(document).ready(function(){
var ex_price = $(".grid_val").html();
ex_price = $(".grid_val").html();
var ans=ex_price.replace('£', '') ;
alert(ans);
});
This is just a tought, but I think this would be a perfect place to use some custom data-attributes, like data-value. It would work nice especially if you have a lot of these values to get.
The outcome would be smthn like this:
<!-- HTML -->
<span class="grid_val" data-value="12">£12</span>
<span class="grid_val" data-value="15">£15</span>
<span class="grid_val" data-value="13">£13</span>
<span class="grid_val" data-value="1">£1</span>
<script>
$(".grid_val").each(function(){
var value = $(this).attr("data-value");
//do something with it
});
</script>

parse text using regex using jquery/javascript

txt = '<a class="info" href="/some/link" original-title="hello world <br/> Monday <br/> 2 days <br/> Test"> 10 </a>';
var pattern = /\s\d+/;
var parsed_data = parseInt((txt.match(pattern)||['0'])[0]);
Got this regex pattern from some example. I am trying to parse the text i.e. value 10 from the anchor tag. But the value obtained is 2.
EDIT:
I am using datatables to populate the tables.
And problem is the string i.e. txt is a row element, extracted from table using loop and need to add these values e.g.
var parsed_data += parseInt((txt.match(pattern)||['0'])[0]);
It is a very bad idea to parse a html content with regex, in this case use jQuery to fix it
var txt = '<a class="info" href="/some/link" original-title="hello world <br/> Monday <br/> 2 days <br/> Test"> 10 </a>';
var parsed_data = parseInt($(txt).text(), 10);
console.log(parsed_data)
Demo: Fiddle
You could have something like that:
var txt = '<a class="info" href="/some/link" original-title="hello world <br/> Monday <br/> 2 days <br/> Test"> 10 </a>';
var pattern = /.*>\s*(\d+)/;
var matches = txt.match(pattern);
var parsed = matches ? +matches[1] : 0;
However, this regexp takes just the last digit inside a tag (>): if you want to have something more precise, you should parse the HTML using the DOM – that is more expensive. It's really depends by what is your data, if you always have such format, you don't need the DOM.

Prefix article keyword with date(Y-m-d)

In the CMS I am building, record names have to be unique (they are URL keywords). In order to achieve this with blog posts, I am attempting to prefix blog post titles with date("Y-m-d") in PHP.
I have a "title" input text field, in which the title is entered, a "keyword" text field which automatically "slugs" the title in order to turn it into a URL keyword.
I'm having trouble figuring out how to prefix the slugged title with the date.
Here's the code:
<input name="title" type="text" id="title" />
<input name="keyword" type="text" id="slug" />
<script type="text/javascript">
$(document).ready(function(){
$("#title").slug();
});
</script>
This part works. The title successfully turns into a keyword with dashes for spaces, eliminating special characters, etc.
I tried including the date by adding a hidden field with the date as the value and accessing its value with the getElementById function. I attempted to rework the javascript to concatenate the slugged title with the date:
<input type = "hidden" id = "postdate" value = "<?php echo date("Y-m-d"); ?>-" />
<script type="text/javascript">
$(document).ready(function(){
var getDate = document.getElementById('postdate');
var doSlug = $("#title").val();
var slugString = getDate + doSlug;
$("slugString").slug();
});
</script>
But I'm obviously not working properly with the javascript.
The output I'm after would be: "2013-10-09-title-of-this-blog-post"
Where am I going wrong?
Working Fiddle
I suggest you to do a little tweak to the plugin to be able to do what you want.
As you can see in the feedle above i add two new configuration parameters
prepend: null, // String to be prepended the sluged string
append: null // String to be appended the sluged string
and on the makeSlug function i just add this two conditionals
if(typeof settings.append === 'string')
slug = slug + '-' + settings.append;
if(typeof settings.prepend === 'string')
slug = settings.prepend + '-' + slug;
Now you can prepend or append a string to the slugfy version of your string
$("#title").slug({
prepend: '2010-10-13',
append: 'YAYY'
});
If you decide to use this approach, here is how to use with your html
$(document).ready(function(){
$("#title").slug({
prepend: $('#postdate').val()
});
});
How about:
$(document).ready(function(){
var getDate = $('#postdate').val(); // get the value of the postdate id, not the element.
var doSlug = $("#title").val();
var slugString = getDate + "-" + doSlug;
$('#title').val(slugString);
$('#title').slug(); // if needed.
});
The jQuery slug() function is changing the input value to be "slugged". You can't set it to "slugString", because that's a variable, not a dom element. If necessary, you can "reslug" the input value after setting it with val().
Edited to fix the getDate variable issue that #Oswaldo Acauan picked up

Categories