I'm trying to create <div> elements with child <p> elements; the <div> elements are being assigned a class of "clock" + a number (increments). While the elements themselves seem to be created, adding text (in my case a moment object) to the <p> element doesn't work.
HTML:
<body>
<select class="tz_list" name="timezones">
<option value="default">Please Select a Timezone</option>
</select>
<input type="button" name="addClock" value="Add Clock" class="button">
</body>
JS:
$(document).ready(function () {
var now = moment();
console.log(now);
//var repeat = setInterval(displayTime, 200);
var tzones = moment.tz.names();
tzones.forEach(function(key,value){
$('<option/>').val(key).html(key).appendTo('.tz_list');
});
var repeat;
var clock_count = 1;
var timezone ="";
function displayTime(timezone, clock_number) {
console.log(timezone);
var location = moment().tz(timezone).format("ddd, MMMM Do YYYY, HH:mm:ss");
console.log(location);
//$('.clock '+clock_number)[0].childNodes[0].nodeValue = timezone;
var selector = '.clock '+clock_number.toString() + ' p';
console.log(selector);
//$('.clock '+clock_number.toString()).css({"height":"100px", "width":"500px"});
$(selector).text(location.toString());
};
$('.button').on('click', function(e){
console.log(e.target.value);
var div = '<div class="clock '+clock_count.toString()+'"><p></p></div>';
$(div).insertAfter('.button');
clock_count+=1;
displayTime(timezone, clock_count-1);
});
$('.tz_list').on('change', function(event){
console.log(event.target.value);
timezone = event.target.value;
});
});
What am I missing?
Here is a JSFiddle
Instead creating class "clock " try to create with out giving space. It will work.
function displayTime(timezone, clock_number) {
console.log(timezone);
var location = moment().tz(timezone).format("ddd, MMMM Do YYYY, HH:mm:ss");
console.log(location);
//$('.clock '+clock_number)[0].childNodes[0].nodeValue = timezone;
var selector = '.clock'+clock_number.toString() + ' p';
console.log(selector);
//$('.clock'+clock_number.toString()).css({"height":"100px", "width":"500px"});
$('.clock'+clock_number.toString()).text(timezone);
$(selector).text(location.toString());
};
$('.button').on('click', function(e){
console.log(e.target.value);
var div = '<div class="clock'+clock_count.toString()+'"><p></p></div>';
$(div).insertAfter('.button');
clock_count+=1;
displayTime(timezone, clock_count-1);
});
Change this line:
$('.clock.'+clock_number.toString()).text(timezone);
add the "." after clock but is not a god practice add number as class, instead use something like clock_1 (or clock1 like the answer below)
Related
How can i check when a value on input is changed.
I have a calendar and when i click on calendar it changes the value on input , but when im trying to see if it has changed its not working. i have tried AddEventListener, also jquery on change, also i sent a function on change to call it but none of them is working.
<input type="text" id="date" class="date" onchange="changed()" name="" >
function changed(){
alert("hello world");
}
Main js file for creating the calendar :
This function creates the calendar on my php file .
And then when on click it gets the value on the input with id #date
But When im trying to see if value has changed it is not working .
// Initialize the calendar by appending the HTML dates
function init_calendar(date) {
$(".tbody").empty();
$(".events-container").empty();
var calendar_days = $(".tbody");
var month = date.getMonth();
var year = date.getFullYear();
var day_count = days_in_month(month, year);
var row = $("<tr class='table-row'></tr>");
var today = date.getDate();
// Set date to 1 to find the first day of the month
date.setDate(1);
var first_day = date.getDay();
// 35+firstDay is the number of date elements to be added to the dates table
// 35 is from (7 days in a week) * (up to 5 rows of dates in a month)
for(var i=0; i<35+first_day; i++) {
// Since some of the elements will be blank,
// need to calculate actual date from index
var day = i-first_day+1;
// If it is a sunday, make a new row
if(i%7===0) {
calendar_days.append(row);
row = $("<tr class='table-row'></tr>");
}
// if current index isn't a day in this month, make it blank
if(i < first_day || day > day_count) {
var curr_date = $("<td class='table-date nil'>"+"</td>");
row.append(curr_date);
}
else {
var monthplusone = months[month];
var curr_date = $("<td class='table-date' id='"+day+"-"+monthplusone+"-"+year+"'>"+day+"</td>");
var events = check_events(day, month+1, year);
if(today===day && $(".active-date").length===0) {
curr_date.addClass("active-date");
let x = document.getElementById('date').value=day+"-"+monthplusone+"-"+year;
$('.table-date').ready(function () {
x.value;
});
show_events(events, months[month], day);
}
// If this date has any events, style it with .event-date
if(events.length!==0) {
curr_date.addClass("event-date");
}
// Set onClick handler for clicking a date
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
});
curr_date.click({events: events, month: months[month], day:day}, date_click);
row.append(curr_date);
}
}
// Append the last row and set the current year
calendar_days.append(row);
$(".year").text(year);
}
Notice that change is actually triggered when the input is not focused anymore.
document.getElementById("date").addEventListener("change", function () {
alert("hello world");
});
<input type="text" id="date" class="date" name="">
This works. Not sure where you're running into an issue.
function changed(){
console.log("hello world");
}
<input type="text" id="date" class="date" onchange="changed()" name="" >
EDIT: Shortened version of init_calender() for others interested in answering:
function setDate() {
document.getElementById("date").value = '19-Dec-2021'
}
I basically agree with #Spankied in that you should try and shorten your code to the point where you are having the issue. However, after looking at your code it seems to me that you want the following function
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
});
to not only change the value in your #date input but also trigger its change event-handler function. You can do that by changing it to something like
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
$("#date" ).change();
});
jQuery.change() without any arguments will trigger a predefined "change"-event on the DOM-object that is selected by the jQuery-object.
You can use js to do that:
let x = $(...) //select the input box
let val = x.value;
function repeat() {
if (val !== x.value) {
change()
}
}
setInterval(repeat, 100)
This checks if the result is the same.
This might make your site a bit slow and it might look odd but this will work in just every case
<script>
let Oldvalue = $('.date')[0].val();
setInterval(() => {
let currentValue = $('.data')[0].val()
if (Oldvalue != currentValue){
//do whatever but in end write this
Oldvalue = currentValue;
}
}, 10);
</script>
I'm really new to Javascript. I am trying to output the current date and also the content in the textarea tag in HTML on button click.
However I do not know how to obtain the content when the textarea is not declared along with a name/id/class.
Here's my code:
<script>
function displayPost() {
var thisDiv = document.getElementById("posts");
var date = new Date();
date.classList.add("post-time");
var textarea = document.getElementByTagName("textarea");
textarea.classList.add("post-content");
thisDiv.innerHTML = date + textarea;
}
</script>
<html>
<div id="posts"></div>
<textarea rows="4" cols="60">Type your text here...</textarea>
<button onclick = "displayPost()">Post</button>
</html>
Any sort of help is appreciated! Thank you in advance!
You can use document.querySelector when a dom element does have any name/id/class like:
var textarea = document.querySelector('textarea');
To get the current date in a readable format, you can use toLocaleString() method:
var date = new Date();
console.log(date.toLocaleString());
// → "3/21/2020, 7:00:00 PM"
To get <textarea> current entered value you can use:
var textarea = document.querySelector('textarea');
console.log(textarea.value);
DEMO:
function displayPost() {
var thisDiv = document.getElementById('posts');
var date = new Date();
thisDiv.classList.add("post-time");
var textarea = document.querySelector('textarea');
textarea.classList.add("post-content");
thisDiv.innerHTML = date.toLocaleString() + ': '+ textarea.value;
}
.post-time{padding:20px 0}
<div id="posts"></div>
<textarea rows="4" cols="60" placeholder="Type your text here..."></textarea>
<button onclick="displayPost()">Post</button>
you can make use of document.querySelector() which returns first matching element or document.getElementsByTagName() which returns NodeList of all the textarea elements
var textarea = document.querySelector('textarea').value;
or
var textarea = document.getElementsByTagName('textarea')[0].value;
I've just created an dynamic HTML form and two of its fields are of type date. Those two fields are posting their data into two arrays. I have 2 issues:
a) The array data are not printed when I press the button.
b) Since I created the arrays to store the data, my dynamic form doesn't seem to be fully functional. It only produces new fields when I press the first "Save entry" button on the form. It also doesn't delete any fields.
My code is:
$(document).ready(function () {
$('#btnAdd').click(function () {
var $address = $('#address');
var num = $('.clonedAddress').length;
var newNum = new Number(num + 1);
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
newElem.children('div').each(function (i) {
this.id = 'input' + (newNum * 10 + i);
});
newElem.find('input').each(function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$('#btnDel').click(function () {
$('.clonedAddress:last').remove();
$('#btnAdd').removeAttr('disabled');
if ($('.clonedAddress').length == 0) {
$('#btnDel').attr('disabled', 'disabled');
}
});
$('#btnDel').attr('disabled', 'disabled');
});
$(function () {
$("#datepicker1").datepicker({
dateFormat: "yy-mm-dd"
}).datepicker("setDate", "0");
});
var startDateArray = new Array();
var endDateArray = new Array();
function intertDates() {
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
startDateArray[startDateArray.length] = inputs;
endDateArray[endDateArray.length] = inputsend;
window.alert("Entries added!");
}
function show() {
var content = "<b>Elements of the arrays:</b><br>";
for (var i = 0; i < startDateArray.length; i++) {
content += startDateArray[i] + "<br>";
}
for (var i = 0; i < endDateArray.length; i++) {
content += endDateArray[i] + "<br>";
}
}
JSFIDDLE
Any ideas? Thanks.
On your button you are using element ID's several times, this is so wrong, IDs must be unique for each element, for example:
<button id="btnAdd" onclick="insertDates()">Save entry</button>
</div>
</div>
<button id="btnAdd">Add Address</button>
<button id="btnDel">Delete Address</button>
jQuery will attach the $('#btnAdd') event only on the first #btnAdd it finds.
You need to use classes to attach similar events to multiple elements, and in addition to that simply change all the .click handlers to .on('click', because the on() directive appends the function to present and future elements where as .click() only does on the existing elements when the page is loaded.
For example:
<button id="btnDel">Delete Address</button>
$('#btnDel').click(function () {
[...]
});
Becomes:
<button class="btnDel">Delete Address</button>
$('.btnDel').on('click', function () {
[...]
});
Try this : I know its not answer but it's wrong to get element value using id
Replace
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
With
var inputs = document.getElementById('datepicker1').value;
var inputsend = document.getElementById('datepicker2').value;
You are using jQuery so i will strongly recommend you to stick with the jQuery selector,
var inputs = $('#datepicker1').val();
var inputsend = $('#datepicker2').val();
where # is used for ID selector.
I have a html like follows.
<tr class="meta-info" id="${page.id}">
<td>
<div class="pull-left">
<font size="1">
Like
</font>
</div>
<div class="pull-right" style="font-size:1">
<span class="badge"><i class="icon-thumbs-up"></i>1</span>
</div>
</td>
</tr>
I am trying to increase the number of likes when ever the user cliks on Like hyperlink.
Here is my jquery code. I want to know how i can get the html element from the jquery object.
$(".like").click(function(event){
var parentTr = $(event.target).closest("tr");
if(parentTr.length){
var pageId = parentTr.attr("id");
var spanEle = parentTr.get(0)+" div span:first-child"; ------(1)
var lastNumber = parseInt(spanEle.text());
spanEle.text(lastNumber+1);
}
});
I don't know if i am doing right on line which is marked 1.
I think you need to add an extra <span> tag so that you can replace the count without touching the adjacent icon
<span class="badge"><i class="icon-thumbs-up"></i>
<span class="like-count">1</span>
</span>
then you can address it
$(".like").click(function() {
var spanEle = $(this).closest('tr').find('.like-count').first();
if (spanEle.length) {
var newCount = parseInt(spanEle.text());
spanEle.text(newCount + 1);
}
});
In an event handler, the this reference is event.target. You may be able to handle the element doesn't exist case neater than that too but that way's safe.
JSFiddle demo: http://jsfiddle.net/rupw/VfCvK/
Try this...
$(".like").click(function(event) {
var parentTr = $(event.target).closest("tr");
if (parentTr.length) {
var pageId = parentTr.attr("id");
var spanEle = parentTr.first('.badge');
var lastNumber = parseInt(spanEle.text(), 10);
spanEle.text(lastNumber + 1);
}
});
If the span element always has that classname then it will find the first (only?) one and return an int value of the text within.
Try: Fiddle
var lastNumber = parseInt(parentTr.find('.pull-right span').text(), 10);
You code will look like:
$(".like").click(function(event) {
var parentTr = $(event.target).closest("tr");
if (parentTr.length) {
var pageId = parentTr.attr("id");
var spanEle = parentTr.find('.pull-right span');
var lastNumber = parseInt(spanEle.text(), 10);
spanEle.text(lastNumber + 1);
}
});
Update: If you wish to keep the <i> tag then use:
spanEle.html(spanEle.html().replace(lastNumber, lastNumber + 1));
insteadof : spanEle.text(lastNumber + 1);
Sample
Can some help me figure out why my javascript HTML template doesn't auto-update the time but the regular HTML does? Here's the templating library i'm using: https://github.com/blueimp/JavaScript-Templates
here's my JS (you can fiddle with it here: http://jsfiddle.net/trpeters1/SpYXM/76/ ):
$(document.body).on('click', 'button', function(){
var id= $(this).data('id');
var data={id:id, string: "just now...", fxn: nicetime()};
var result = tmpl('<div id="string" data-id="'+id+'">{%=o.string%}</div><div id="function" data-id="'+id+'">{%=o.fxn%}</div>', data);
$('div[data-id="'+id+'"]').html(result);
nicetime();
});
function nicetime(){
var time = new Date(),
var comment_date = setInterval(function() {
var time2 = time_since(time.getTime()/1000);
$('#time_since').html(time2);
return time2;
},
1000);
}
HTML:
<button data-id="1">1</button>
<div data-id="1"></div> //tmpl output
<div id="time_since"></div> //non-tmpl output
You want something like this.
With JavaScript templating, you generally want to template once, then update the values of specific elements dynamically, as opposed to resetting the innerHTML of an entire element every second.
Here's the JavaScript:
$(document.body).on('click', 'button', function(){
var id= $(this).val(),
time = +new Date,
data = {
id: id,
string: "just now..."
},
result = tmpl('<span class="string">{%=o.string%}</span>', data),
tgt = $('#'+id),
str;
tgt.html(result);
str = tgt.find('.string');
window.setInterval(function() {
str.html(time_since(time/1000));
}, 1000);
});