Show string result from function in a label using AngularJs - javascript

What is the best way to call function that will return string and show that string in a label when using angularJs?
I have three drop downs, and when I select values in all of them I want to show a label.
Content of a label is calculated in one function so on that moment (when all 3 drop downs have some values selected) I need to call function that will return value for label as well.
All that hiding/showing label logic I have put in html like this:
<div class="col-md-2"
ng-show="newTestSessionCtrl.formData.sessionTime && newTestSessionCtrl.formData.timeZone && newTestSessionCtrl.formData.sessionCloseInterval">
<lable>Your local time</lable>
<div ng-value="convertSelectedTimeZoneToClients()"></div>
</div>
This is convertSelectedTimeZoneToClients() function code:
convertSelectedTimeZoneToClients() {
let timeZoneInfo = {
usersTimeZone: this.$rootScope.mtz.tz.guess(),
utcOffset: this.formData.timeZone.offset,
selectedDateTime: this.toJSONLocal(this.formData.sessionDate) + " " + this.formData.sessionTime
};
let utcTime = this.$rootScope.mtz.utc(timeZoneInfo.selectedDateTime).utcOffset(timeZoneInfo.utcOffset).format("YYYY-MM-DD HH:mm");
let localTime = this.$rootScope.mtz.utc(utcTime).toDate();
localTime = this.$rootScope.mtz(localTime).format("YYYY-MM-DD HH:mm");
return localTime;
}
So when values are selected I am showing label that says: Your local time
And underneath I want to show result from convertSelectedTimeZoneToClients()that will be basically string in 'YYYY-MM-DD HH:mm' format.
Can I preform something like this on the html as well or I will have to move to controller? What is the best or easiest way to accomplish this?
I have tried ng-value, but I guess I am doing wrongly. Nothing gets show, but I do not get any errors in console as well.

in your function you can check if your drop downs are selected, then calculate and return result
$scope.getData = function () {
if ($scope.ValueOfFirstDropDown != undefined && $scope.ValueOfSecondDropDown != undefined && $scope.ValueOfThirdDropDown != undefined) {
//calculate result
return result;
}
}
and in your html
<label>{{getData()}}</label>

Try this:
<div ng-bind="convertSelectedTimeZoneToClients()"></div>

You should call this function on change of selected value
<select ng-change="convertSelectedTimeZoneToClients();"></select>
<div class="col-md-2"
ng-show="newTestSessionCtrl.formData.sessionTime && newTestSessionCtrl.formData.timeZone && newTestSessionCtrl.formData.sessionCloseInterval">
<lable>Your local time</lable>
<div ng-bind="clientDateTimeZone"></div>
</div>
and reflect $scope.clientDateTimeZone = yourreturnedvalue
No need to return any thing
$scope.convertSelectedTimeZoneToClients = function() {
let timeZoneInfo = {
usersTimeZone: this.$rootScope.mtz.tz.guess(),
utcOffset: this.formData.timeZone.offset,
selectedDateTime: this.toJSONLocal(this.formData.sessionDate) + " " + this.formData.sessionTime
};
let utcTime = this.$rootScope.mtz.utc(timeZoneInfo.selectedDateTime).utcOffset(timeZoneInfo.utcOffset).format("YYYY-MM-DD HH:mm");
let localTime = this.$rootScope.mtz.utc(utcTime).toDate();
localTime = this.$rootScope.mtz(localTime).format("YYYY-MM-DD HH:mm");
//set It here
$scope.clientDateTimeZone = localTime
//return localTime;
}

Related

Get HTML input into Google sheet in a specific format

The code snippet below is part of a larger script that collects user input from an HTML file and store these user input into my Google sheet. The type of input fields from the line
formObject.firmenp all the way to the line formObject.zielplanung in my HTML file is date and have each their own specific ID. I want to get these dates in format day/month/year into my sheet.
Any idea or recommendation how to achieve that?
Thank you so much in advance for your help :).
function getFormValues(formObject){
if(formObject.RecId && checkID(formObject.RecId)){
var values = [[formObject.RecId.toString(),
formObject.name,
formObject.unternehmen,
formObject.rufnummer,
formObject.email,
formObject.firmenp,
formObject.onboarding,
formObject.selbsttraining,
formObject.crmm,
formObject.tblock1,
formObject.fdtblock,
formObject.wochentraining,
formObject.zielplanung,
formObject.changestatus]];
}else{
var values = [[new Date().getTime().toString(),
formObject.name,
formObject.unternehmen,
formObject.rufnummer,
formObject.email,
formObject.firmenp,
formObject.onboarding,
formObject.selbsttraining,
formObject.crmm,
formObject.tblock1,
formObject.fdtblock,
formObject.wochentraining,
formObject.zielplanung,
formObject.changestatus]];
}
return values;
}
You can make a function like the below and convert all your data using it. Use this function on your script page.
//2021-11-05
var getDate = document.getElementById("date").value;
console.log("Inputted data: " + getDate);
function getNewDateFormat(value){
var dateValue = new Date(value);
var monthPart = dateValue.getMonth() + 1;
var dayPart = dateValue.getDate();
var yearPart = dateValue.getFullYear();
var newFormat = dayPart + "/" + monthPart + "/" + yearPart;
return newFormat
}
console.log("Expected data: " + getNewDateFormat(getDate));
//dummy input
<input type="text" id="date" value="2021-11-05" />

Passing a date between two pages

Ok, so I have an MVC webapp. I've tried for hours to pass one simple variable from TransactionsDatePicker.cshtml to Transactions display.
I have an input with an id of 'transactionlookupdate'. I want to intercept it (input type is date).
I've managed to append the date to the link like this:
<script>
document.getElementById("buttoncontinue").addEventListener("click", function () {
dateSelected = document.getElementById("transactionlookupdate").value;
document.location.href = 'TransactionsDisplay' + '/' + dateSelected;
});
</script>
Now, what do I do in TransactionsDisplay (where I want to get the date) to store it in usable variable?!
So far I've tried like a 100 different ways, one that got me the closest was:
(top of TransactionsDisplay.cshtml)
#{
ViewBag.Title = "TransactionsDisplay";
Layout = "~/Views/Shared/_Layout.cshtml";
var dateSelected = Request.Url.Segments.Last();
}
and awful try at populating alert with dateSelected:
<script>
function myFunction() {
alert(dateSelected);
}
</script>
Any help would be appreciated!
Pass the date as url parameter in TransactionsDatePicker.cshtm
document.location.href = 'TransactionsDisplay' + '?date=' + dateSelected;
and extract in TransactionsDisplay at the end of the <body> element:
<script>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const myDate = urlParams.get('date');
alert(myDate); // test alert
</script>

UI Datepicker: choosing date overwrites existing settings

I am trying to write a custom datepicker, where the default drop downs for months and year ranges (enabled through changeMonth and changeYear options) are replaced by custom drop downs. It is something like this:
Fiddle: http://jsfiddle.net/gGV3v/
$("#myId").datepicker({
...default settings...
beforeShow: function() {
...here I replace the default dropdowns by custom dropdowns...
...something like...
$(".ui-datepicker-month").replaceWith("#custom-html-block");
$(".ui-datepicker-year").replaceWith("#another-custom-html-block");
}
});
On choosing either month or year from the custom dropdowns, I want to change the date in the view accordingly. So I construct the date string from the current month and year (the date for the new month/year combo defaults to 1 here), and I call
$("#custom-html-block .custom-dropdown-option").on("click",function() {
...construct newDateString...
$("#myId").datepicker("setDate",newDateString)
});
$("#another-custom-html-block .custom-dropdown-option").on("click",function() {
...construct newDateString...
$("#myId").datepicker("setDate",newDateString)
});
I want the span with text foo to remain intact when setting the new date programmatically on clicking it.
The problem is: it wipes off the custom drop downs and the default ones come again. I tried to do things like this:
$("#myId").datepicker($.extend({setDate: newDateString},oldSettings))
But it still doesn't work. How do I make this work?
You can set the value of the function $.datepicker._generateMonthYearHeader, the downside it that will be global for all datepicker in the page.
The sample is below:
$.datepicker._generateMonthYearHeader = function(inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort) {
var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
changeMonth = this._get(inst, "changeMonth"),
changeYear = this._get(inst, "changeYear"),
showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
html = "<div class='ui-datepicker-title'>",
monthHtml = "";
// year selection
if ( !inst.yearshtml ) {
inst.yearshtml = "";
if (secondary || !changeYear) {
html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
} else {
// determine range of years to display
years = this._get(inst, "yearRange").split(":");
thisYear = new Date().getFullYear();
determineYear = function(value) {
var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
(value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
parseInt(value, 10)));
return (isNaN(year) ? thisYear : year);
};
year = determineYear(years[0]);
endYear = Math.max(year, determineYear(years[1] || ""));
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
inst.yearshtml += "<span class = 'dummy'>Foo</span> <select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>"
for (; year <= endYear; year++) {
inst.yearshtml += "<option value='" + year + "'" +
(year === drawYear ? " selected='selected'" : "") +
">" + year + "</option>";
}
inst.yearshtml += "</select>";
html += inst.yearshtml;
inst.yearshtml = null;
}
}
And your fiddle: http://jsfiddle.net/gGV3v/2/
UPDATE:
Without the buttons, and using a better approach, now you have control of all generated HTML:
var oldGenerateHTML = $.datepicker._generateHTML;
function newGenerateHTML(inst) {
var html = oldGenerateHTML.call(this, inst);
var $html = $(html);
$html.find('[data-handler=prev]').remove();
$html.find('[data-handler=next]').remove();
$html.find('[data-handler=selectMonth]').replaceWith('<span class="dummy">Foo</span>');
return $html;
}
$.datepicker._generateHTML = newGenerateHTML;
Fiddle also updated: http://jsfiddle.net/gGV3v/4/
In general this is why extend sucks. The parent (in your case datepicker) doesn't know anything about childs (your custom html). Everytime it refresh the view, your changes are lost. This problem is usually solved using composition. The goal is to create your own widget (I think that was the term in jQuery) that have datepicker as a local variable and to control _generateMonthYearHeader function calls. It's easy to say in theory but in practice (specially case with jQuery) is hard to achive. Easier solution will be to proxy the function.
//preserve _generateHTML because after it finish, html is visible and .ui-datepicker-month and .ui-datepicker-year are in dom tree
fn = $.datepicker._generateHTML; //preserve original function
$.datepicker._generateHTML = function(inst) {
//call original function
fn.call(this, inst);
//do custom changes
//you'll need better selectors in case of multiple datepicker instances
$(".ui-datepicker-month").replaceWith("#custom-html-block");
$(".ui-datepicker-year").replaceWith("#another-custom-html-block");
}
Personally I dislike this approach (I prefer composition as I said) but in your case it'll be easier to implement. The reason its easier is because generateMonthYearHeader is called from many different functions.
P.S. Not tested

Javascript: Simple currency converter with previous conversions

what i aim to do is a very simple currency converter. Basically, you type in a number, and press a button, a text is displayed that says "x dollars is y euros". Press the button again, a new text is displayed where the old one was, and the old one is displayed under the new one.
I've come so far that when something is entered in the field, it pops up below, and if you press the button again (with the same or a different value) it becomes a list of text.
To clarify what it is i'm saying here, take a look at this jsfiddle: http://jsfiddle.net/w8KAS/5/
Now i want to make it so that only numbers work, and so that number(x) is converted when the button is pressed and displayed below next to some fitting text (like "x dollars is y euros")
This is my js code, check the jsfiddle full code (html, js, css)
Any suggestions?
var count = 0;
function validate() {
var amount = document.querySelector("#amount");
if(amount.value.length > 0) {
amount.className = 'correct';
}
else {
amount.className = 'empty';
}
if (document.querySelector('.empty')) {
alert('Något är fel');
}
else {
addconvert(amount.value);
}
}
function addconvert(amount) {
var table = document.querySelector('#tbody');
var tr = document.createElement('tr');
var amountTd = document.createElement('td');
var amountTextNode = document.createTextNode(amount);
amountTd.appendChild(amountTextNode)
tr.appendChild(amountTd);
table.insertBefore(tr, table.firstChild);
count++;
}
var button = document.querySelector(".button");
button.onclick = validate;
Your number validation is failing. Change the first part of your validation to this:
function validate() {
var amount = document.querySelector("#amount");
var amountNum = parseFloat(amount.value); //This is the numeric value, use it for calculations
if(amount.value.length > 0 && !isNaN(amountNum) ) {
amount.className = 'correct';
amount.value = amountNum;
}
...
Working here: http://jsfiddle.net/edgarinvillegas/w8KAS/6/
Cheers
You need a conversion rate (there are APIs for that), and then you can just add them together in a string
var convRate = 1.3;
var amountTextNode = document.createTextNode(amount + " dollars is " + amount*convRate + " euros");
Regarding the API, Yahoo will tell you what you need without even the need to sign-in
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDEUR%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="
}).done(function(data) {
convRate = data.query.results.rate.Rate
});
To make sure that only numbers work, you can test the variable amount.value using the isNaN function. This will return true if the user's input is Not-a-Number, so if it returns false, you can proceed with your conversion.
if (!isNaN(amount.value)){
addconvert(+amount.value) // the plus symbol converts to a number
} else {
// display error here
}
Inside your addconvert function, you can add code to will multiply your input amount by an exchange rate to get a rough conversion.
function addconvert(){
// ...
var euros = 0.74 * amount
var text = amount + ' dollars is ' + euros + ' euros'
var amountTextNode = document.createTextNode(text);

getting jquery to trigger onclick off a class

I do apologize if this is an easy fix, I'm a tad new to jquery. To start I don't think that it is my initial call that is messing up because if I put a simple alert function in than it will work fine onclick, basically when this <li> is clicked on, jquery trigers an ajax to php function sending the class of the <li> to a php script and back, opening an alert with the result. As far as I can tell it should be working, but again my knowledge is rather limited. Any change anyone can take a look at what I have and see if you can clean it up at all, currently nothing happens onclick, no errors even appear in the console. But I imagine that even my ajax call is wrong. Any ideas why nothing happens on click?
HTML:
<li title = "Previous Month" id = "changeMonthBack" class = "<?php echo date('n'); ?>"><img src="images/leftArrow.gif" width="54" height="45" alt="previous month"></li>
jQuery/javascript:
//javascript document
$(document).ready(function(){
//need to do an onclick for getting the new month(previous)
$(".changeMonthBack").click(function(){
function calendar(){
//set the id for php
var identifier = 1;
//get the class to use for month
var str = document.getElementById("changeMonthBack").class;
//get the month number
//if the month is 1, we obviously need it to be 12
if str == 1{
var month = 12;
}
else{
var month = str - 1;
}
$.post("redraw.php"),{
identifier: identifier,
month: month
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
};
})//end function 1
});
There are multiple problems with the script.
1. As Aesthete suggested the selector should be an id selector #changeMonthBack
2. You are creating a closure method called calendar but never called it
3. There were multiple syntax error (Use a javascript editor like spket)
You are creating a function called calendar but never calls it.
$(document).ready(function() {
// need to do an onclick for getting the new month(previous)
$("#changeMonthBack").click(function() {
// set the id for php
var identifier = 1;
// get the class to use for month
var str = parseInt($(this).attr('class'),10);
// get the month number
// if the month is 1, we obviously need it to be 12
if (str == 1) {
var month = 12;
} else {
var month = str - 1;
}
$.post("redraw.php", {
identifier : identifier,
month : month
},
function(data, status) {
alert("Data: " + data + "\nStatus: "
+ status);
});
});
});

Categories