I tried to show some text into javascript but unable to do
First of all, here is the code
$('.example').each(function() {
var $t = $(this),
$w = $t.find('.widget.Text');
if ($w != undefined) {
months = $(this).text().replace($w, 'months');
days = $(this).text().replace($w, 'days');
months != false && $t.find('#example-done').text(months);
days != false ? days = Number(days) : days = 7;
}
});
// up to so...............on
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="example">
<div class="widget Text">
months=(Accept) days=(20)
</div>
</div>
Here in the above code months and days data shows I tried to implement this data in javascript
months=(Accept) its value should be Accept in Js
days=(20) its value should be 20 Accept in Js
I tried the above method but not working
is there any method available to insert the above HTML format data in my Javascript
I think .split() function will resolve this problem please provide any guide (like we have to split both data with help of js and Text Trim)
Any help is highly appreciated
I just want to show months and days values into my javascript code, Please provide any code to fix this issue. I tried hard but I am unable to fix it. Like months=(Accept) and days=(20), Now how to show that value (20 and accept) into javascript? Please leave other code which I provide above Just guide me on how to show this HTML format data into js
Use .text() to get the contents of the DIV. Then you can use a regular expression to match the contents and extract the values.
$('.example').each(function() {
var $t = $(this),
$w = $t.find('.widget.Text').text();
if ($w) {
var match = $w.match(/months=\(([^)]*)\)\s+days=\((\d+)\)/);
if (match) {
var months = match[1];
var days = Number(match[2]);
console.log(`Months = ${months}, Days = ${days}`);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="example">
<div class="widget Text">
months=(Accept) days=(20)
</div>
</div>
See Reference - What does this regex mean? for explanations of the regular expression details.
Change
months = $(this).text().replace($w, 'months');
days = $(this).text().replace($w, 'days');
months != false && $t.find('#example-done').text(months);
days != false ? days = Number(days) : days = 7;
to
let a = $t.text().match(/months=\(([^(]*)\)\s+days=\(([^(]*)\)/);
months = a[1]; days = a[2];
days = days === '' ? 7 : +days;
Related
I have found lots of topics about the (jQuery) Datepicker but not the specific ACF way I am looking for.
The following is a perfectly working code to set max selected dates in the past and in the future within ACF but I need 2 more functions but can't figure out how to implement them.
How do I:
Disable specific future dates?
Disable specific week days (f.i. Sundays)?
within the example code below?
function yl_date_picker_customizations() {
?>
<script type="text/javascript">
(function($) {
// JS here
acf.add_filter('date_picker_args', function( args, $field ){
// do something to args
args['minDate'] = '0'; //For example, "+1m +7d" represents one month and seven days from today.
args['maxDate'] = '30';
return args;
});
})(jQuery);
</script>
<?php
}
add_action('acf/input/admin_footer', 'yl_date_picker_customizations');
Here's the working code :)
// Customization to reservation dates via datepicker
function yl_datepicker_customizations() {
?>
<script type="text/javascript">
(function($) {
var arrDisabledDates = {};
arrDisabledDates[new Date('06/19/2020')] = new Date('06/19/2020');
arrDisabledDates[new Date('06/30/2020')] = new Date('06/30/2020');
acf.add_filter('date_picker_args', function( args, $field ){
// do something to args
args['minDate'] = '0'; //For example, "+1m +7d" represents one month and seven days from today.
args['maxDate'] = '60';
args['beforeShowDay'] = function (date) {
var day = date.getDay(),
bDisable = arrDisabledDates[date];
if (bDisable) return [false, '', '']
else return [(day != 4) && (day != 2)]
}
return args;
});
})(jQuery);
</script>
<?php
}
add_action('acf/input/admin_footer', 'yl_datepicker_customizations');
my problem is the following . Im using Duda widget Builder to build my own Widgets. In one application there is a Date and by default its depicted as ISO .
Now converting that isnt too hard, I tried the following :
if (document.getElementById("date") !== null) {
let date = document.getElementById("date").toString();
let dater = date.substring(0, 10);
document.getElementById("date").innerHTML.replace(date, dater);
console.log('Test');
}
<div class="Wrapper shadow">
<h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>
Now it doesnt throw any errors and it console.logs the "Test". But the date stays in ISO.
The widget works with jQuery I believe it has something to do with that.
The widget interface where you write down the javascript is encapsulated by this: function(element,data,api){ 'my js code from above'}
Please help.
The issue is because you never update the content of the element after working with the content. Also note that you don't need to use replace(). Try this:
let el = document.getElementById("date");
if (el) {
el.textContent = el.textContent.substring(0, 10);
}
<div class="Wrapper shadow">
<h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>
That being said, you're just getting the first 10 characters of the date string, which is not infallible. If the locale changes your code will break. To fix this you can create a Date object from the string and output the format you require explicitly:
let el = document.getElementById("date");
if (el) {
let date = new Date(el.textContent);
let year = date.getFullYear();
let month = ("00" + (date.getMonth() + 1)).slice(-2);
let day = ("00" + date.getDate()).slice(-2);
el.textContent = `${year}-${month}-${day}`;
}
<div class="Wrapper shadow">
<h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>
You can also use Moment.js for format the date you need.
const el = document.querySelector('#date');
const myDateFormat = 'YYYY-MM-DD';
const date = el.textContent;
const newDate = moment(date, myDateFormat).format(myDateFormat);
el.textContent = newDate;
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<div class="Wrapper shadow">
<h3 class="date" id="date">2020-02-20T14:39:40Z</h3>
</div>
Hope to help you and others ^^.
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;
}
I would like to know how my code could be displayed on a webpage instead of displayed in alert boxes, how do I do this. I understand that id's ect are needed but I am a little confused of where to start. Any help would be good. Thankyou!
<!DOCTYPE html>
<html>
<script>
//Set of variables
var nameCheck = /^[a-zA-Z\s]+$/;
//eliminates anything not relevant
var numberCheck = /^[0-9\.]+$/;
//eliminates anything not relevant
var totHours = 0;
//adds total gaming hours on one day
var dayHours = 0;
//how many on one such day set in i from 1-7
var averHours = 0;
//stores the average by dividing by the tothours by 7
var mostPerDay = 0;
//calculates day with most gamed
var mostOnDay = 0;
//Most hours on ONE day
var moreDays = " ";
//adds an s to the end of days if more than one
var mpd = 0;
//most per day
var ah = 0;
//average hours
var th = 0;
//total hours
var name = prompt("What is your name?");
//asks users name
//Make sure user inputs a name that includes letters and or spaces
while (name == "null" || isNaN(name) == false || !name.match(nameCheck)){
alert("Invalid Name!");
name = prompt("What is your name?");
}
//Greets the user by name
alert("Hello " + name );
//Ask how many hours gamed on a day
for (var i = 1; i <= 7; i++){
dayHours = prompt("How many hours have you gamed on day " + i + "?")
//Reask the question if the user inputs an invald answer
while (dayHours == null || isNaN(dayHours) || dayHours > 24 || !dayHours.match(numberCheck) || dayHours < 0){
alert("Incorrect! No letters or symbols, and make sure your input is under 24");
dayHours = prompt("How many hours have you gamed on day " + i + "?")
}
//Adds to total hours
totHours += Number(dayHours)
//Calculates days with most hours gamed
if (mostPerDay > dayHours){
}
else if (mostPerDay < dayHours){
mostPerDay = Number(dayHours);
mostOnDay = i;
}
else if (mostPerDay = dayHours){
mostOnDay += " and " + i;
mostPerDay = Number(dayHours);
}
}
//Adds 's' to the statistics if more than one day
if (isNaN(mostOnDay) == true){
moreDays = "s ";
}
//Divides the total hours by 7 to get average over those 7 days
aver = (totHours / 7);
//Calculates and rounds to the value of 1
th = totHours.toFixed(1);
ah = aver.toFixed(2);
mpd = mostPerDay.toFixed(1);
//States calculated statistics
alert("\nTotal gaming hours this week " + th + "\nAverage gaming hours this week " + ah + "\nMost on one day" + moreDays + mostOnDay + " for " + mpd + " hours." );
//Comments on average hours per day gamed
if (averHours <= 2){
alert("Healthy amount of gaming this week")
}
else if (averHours <= 24){
alert("Unhealthy amount of gaming this week")
}
</script>
</html>
There are several ways to include JavaScript in an HTML document:
Put the JavaScript code in a separate filename.js document and refer to it in the header of the HTML document (that is, between <head> and </head>) as follows: <script type="text/javascript" src="filename.js"></script>. This is the "cleanest" option as it separates functionality (JavaScript) from structure (HTML).
Put the JavaScript code directly in the header of the HTML document; that is, between <script type="text/javascript"> and </script> (no src attribute here)
In the body of the HTML document, again between <script> and </script>, for example when you want to dynamically add text with document.write('');
Changing the text in a <div id="mydiv"> can be done by accessing it via its id:
document.getElementById('mydiv').innerText = 'text';
or through the variants innerHTML, outerText or outerHTML.
For easy DOM manipulation, you may want to look into jQuery. Also, keep in mind that the JavaScript code in the header or external file will be executed immediately, which may cause errors if certain parts of the document body aren't loaded yet. jQuery offers an elegant solution by wrapping the code in
$(document).ready(function () {
// code here
});
Good luck!
A simple method to do this would be to include a link to an external javascript file:
<script src="path/myfile.js"></script>
at the bottom of your html file. If your script requires jQuery, make sure it is linked as an external script before your script. You can reference html elements in your javascript file by giving your html tags an id or class. For example:
In HTML:
<div id = "mydiv"> </div>
Select element in JS:
$('#mydiv')
If you are trying to make your web page more reactive, you may want to look into jquery. It's a lightweight javascript library that can help you make your web page more interactive. Check out the tutorial below:
http://www.w3schools.com/jquery/
I don't entirely understand your question, but just in case you are asking if the javascript will literally show up on your web page, it won't unless you display it as text. If you want to debug your javascript code, you can use developer tools on Chrome or something like it on other browsers:
https://developer.chrome.com/devtools
I'm currently enrolled in a JavaScript class at my community college, and we're supposed to create a page with the following:
"Today's date is (date)"
"Kids Club"
"The time is (time)"
Then, I don't seem to get this part, the instructions state: "Have a link to the new kidsnew.htm page that contains the text "Go To Kids Club". Use onClick and widow.location to open kidsnew.htm.
Before switching, you should use the navigator object and the method to test for the name and version of the browser. Display the name and version of the browser with an alert box and advise the user to upgrade for better results with the new page if their browser is out of date.
The kidsnew page should contain an HTML form button that will take you back to the "kidsold.htm" page."
So. I assume that I'll need the browser verification, where you can find in the first part of the code. I don't get what else I'm supposed to be using, as we were not told of a "onClick" method in the chapter's were reading. Can anyone help me refine the code and get it to display as stated? I did most of it correctly, I think;
Here's my code:
<html>
<head>
<title>Kids Club</title>
<script type = "text/javascript" src = "brwsniff.js"></script>
<script type = "text/javascript">
<!-- hide me from older browsers>
//==============================Browser Info=================================
var browser_info = getBrowser();
var browser_name = browser_info[0];
var browser_version = browser_info[1];
var this_browser = "unknown";
if (browser_name == "msie")
{
if(browser_version < 5.5)
{
this_browser = "old Microsoft";
}
else
{
this_browser = "modern";
}
}
//end
if (browser_name == "netscape")
{
if (browser_version < 6.0){
this_browser = "old Netscape";
else
{
this_browser = "modern";
}
} //end
</script>
//=========================End Browser Info============================
//==========================Start Date Script============================
var date = new Date();
//new is keyword for object Date
//
//getting info from object Date
//
var month = date.getMonth();
var day = date.getDate();
var year = date.getYear();
var hour = date.getHours();
var minutes = date.getMinutes();
//january is month 0, think of arrays
//
month = month + 1;
//fix y2k
//
year = fixY2k(year);
//fix minutes by adding 0 infrotn if less than 10
//
minutes = fixTime(minutes);
var date_string = month + "/" + day + "/" + year;
var time_string = hour + ":" + minutes;
var date = "Today is " + date_string";
var time = "The time is " + time_string;
//y2k fix
//
function fixY2k(number) {
if (number < 1000){
number = number + 1900;
return number;
}
//time fixer
//
function fixTime(number){
if(number < 10) {
number = "0" + number;
}
return number;
}
//========================End Time Script==================================
// show me -->
</script>
</head>
<body>
<script type = "text/javascript">
<!-- hide me from older browsers
document.write(date);
</script>
//show me -->
<h1>Kids Club</h1>
<script type = "text/javascript">
<!-- hide me from older browsers
document.write(time);
</script>
//show me -->
</body>
</html>
Some comments:
> <script type = "text/javascript">
> <!-- hide me from older browsers>
That's rubbish, HTML comment delimiters were never needed to hide script element content, just remove them.
> var year = date.getYear();
You should use the getFullYear method, it avoids the two digit year issue.
> var date = "Today is " + date_string";
There is no need to declare date a second time. It's not harmful, just unnecessary. date started out as a Date object, now it's a string. That's not good programming style, just modify the existing date_string, e.g.
date_string = "Today is " + date_string";
In the body of the page you have:
> <script type = "text/javascript">
> <!-- hide me from older browsers
> document.write(date);
> </script>
> //show me -->
Note that the comment delimiters start inside the script element, then finish outside it. So the browser is left with invalid HTML and whatever happens next is a result of error correction (the same for the next script element too).
Fix that and you may have solved your problem.