check if the div id in JavaScript - javascript

I have project that concerns about calendars, at first i have 1 calendar and now i want to have another one but they have different values.
<div id="cal">
....
</div>
<div id="calq">
....
</div>
my question is, how can I check if div id is "calq" in javascript?
if div.id == "calq" ?
...
at first i have ...
<script type="text/javascript">
monthYear = Date.today();
var cal = new Calendar();
cal.generateHTML();
$('#cal').html(cal.getHTML());
setMonthPrice();
setSpecialPrice()
</script>
then i added
<script type="text/javascript">
monthYear = Date.today();
var calq = new Calendar();
calq.generateHTML();
$('#calq').html(calq.getHTML());
setMonthQuantity();
setSpecialQuantity();
</script>
but the setMonthQuantity() also called by cal, i just want the setMonthQuantity() only for calq
function setMonthQuantity()
{
var weekdayBaseQuantity;
weekdayBaseQuantity = {{ product.quantity }};
$('td.calendar-day').append('<div class="dayquantity">' + weekdayBaseQuantity + '</div>');
$('td.Sat .dayquantity, td.Sun .dayquantity').text( weekdayBaseQuantity );
}

To determine the existence, in clean javascript
if(document.getElementById("calq")!='undefined')
{
// do something, it exists
}
using jquery
if($("#calq").length)
{
// do something, it exists
}
To check the id, in clean javascript
if(this.getAttribute('id')=="calc")
{
// do something, it exists
}
Using jquery
if($(this).attr("id")=="calq")
{
// do something, it exists
}

You can do check it, for example, via Jquery. I suppose that you want to make something like switch and for each div do some operation. If I'm right you can use Jquery's each function for looping against div elements and following condition for checking id's.
if($(this).attr("id")=="calq")

Here you go:
if (​$('#calq').length === 1) {
// there is id = calq
}​​​

Seems like the best solution would be to pass in the div to the functions you are calling. That way you know the div you are dealing with.
eg.
<script type="text/javascript">
monthYear = Date.today();
var cal = new Calendar();
cal.generateHTML();
var calDiv = $('#cal');
calDiv.html(cal.getHTML());
setMonthPrice(calDiv);
setSpecialPrice(calDiv)
</script>
<script type="text/javascript">
monthYear = Date.today();
var calq = new Calendar();
var calqDiv = $('#cal');
calqDiv.html(cal.getHTML());
setMonthQuantity(calqDiv);
setSpecialQuantity(calqDiv);
</script>
I am assuming the $('td.calendar-day') is in the calendar HTML? If so setMonthQuantity would be something like
function setMonthQuantity(calDiv)
{
var weekdayBaseQuantity;
weekdayBaseQuantity = {{ product.quantity }};
calDiv.closest('td.calendar-day').append('<div class="dayquantity">' + weekdayBaseQuantity + '</div>');
calDiv.closest('td.Sat .dayquantity, td.Sun .dayquantity').text( weekdayBaseQuantity );
}

Related

How to use different blogger post ID in Javascript variable?

I am trying to make every article views having comma separated every 3 digit number. I have found the code for that.
But I have problem to find specific blogger post ID to use for the code to work fine.
Here's the whole code that I am trying to work on.
<--Viewable area /-->
<span class='entry-time'><b:if cond='data:allBylineItems.author and data:allBylineItems.timestamp.label'><span class='on'><data:allBylineItems.timestamp.label/></span></b:if><time class='published' expr:datetime='data:post.date.iso8601'><data:post.date/></time></span><span class='postviews1' style='margin-left:5px; display:display;'><a expr:name='data:post.id'/> <i class='far fa-eye'/> <span id='bacani'><span id='postviews'/></span> Views</span>
<--comma separated every 3 digit /-->
<script>var angka = document.getElementById('bacani').textContent;var reverse = angka.toString().split('').reverse().join(''),ribuan = reverse.match(/\d{1,3}/g);ribuan = ribuan.join(',').split('').reverse().join('');document.getElementById('bacani').innerHTML= ribuan;</script>
<--code for views count /-->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/> <script> $.each($("a[name]"), function(i, e) { var elem = $(e).parent().find("#postviews"); var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name")); blogStats.once("value", function(snapshot) { var data = snapshot.val(); var isnew = false; if(data == null) { data= {}; data.value = 0; data.url = window.location.href; data.id = $(e).attr("name"); isnew = true; } elem.text(data.value); data.value++; if(window.location.pathname!="/") { if(isnew) blogStats.set(data); else blogStats.child("value").set(data.value); } }); });</script>
I want to change:
<span id='bacani'><span id='postviews'/></span>
and
document.getElementById('bacani').textContent;
to have a specific value id which is post id from blogger. The only thing that i found from internet is
<data:post.id>
Is there any other way that i can make it work other than what I am thinking right now? I think I need specific new id to make it work for every article to have comma separated every 3 digit.
I try to use the code but it only work for one time only. I believe to make it work as a whole I need to use different code to read specific unique id base on data:.post.id from blogger post id itself. But i do not sure how to make it work. I am expecting when I know how to use different method which is making new code that find unique id for different article it would work fine.
You can just replace elem.text(data.value) to
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
The full code would be
<!-- code for views count -->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/>
<script>
/*<![CDATA[*/
$.each($("a[name]"), function (i, e) {
var elem = $(e).parent().find("#postviews");
var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name"));
blogStats.once("value", function (snapshot) {
var data = snapshot.val();
var isnew = false;
if (data == null) {
data = {};
data.value = 0;
data.url = window.location.href;
data.id = $(e).attr("name");
isnew = true;
}
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
data.value++;
if (window.location.pathname !== "/") {
if (isnew) blogStats.set(data); else blogStats.child("value").set(data.value);
}
});
});
/*]]>*/
</script>

DatePicker: Select single date when using range selection

I have a range DatePicker from Primefaces.
But I also want to be able to just select one date.
But if i do so, i won't get any values, just a empty array.
This is because the internal function (which i can't modify) only returns something when two values are given. Or at least I think that.
The workaround which i thought of was just taking the first value of the array by calling it with a javascript function, but i can't access it, because the PF function has neither a function name nor a class.
Here the code of the PrimeFaces function:
if (this.isRangeSelection()) {
if (this.value && this.value.length) {
var b = this.value[0],
g = this.value[1];
d = this.formatDateTime(b);
if (g) {
d += " " + this.options.rangeSeparator + " " + this.formatDateTime(g)
}
}
}
Here is my poor javascript attempt:
<script type="text/javascript">
function getArrayValue(){
console.log("inFunction");
console.log(window.d.value[0]);
}
</script>
This is called with this:
<div class="p-field p-col-12 p-md-4">
<p:datePicker id="range" selectionMode="range"
value="#{SearchBean.range}" onblur="getArrayValue()">
</p:datePicker>
</div>
Thanks for your help in advance! :)
I just helped a friend do the same thing that sets the range to both dates being the same you can do it with this JS...
<script type="text/javascript">
function adjustDateRange(widgetVar) {
var widget = PF(widgetVar);
var dates = widget.getDate();
if (dates[0] && !dates[1]) {
dates[1] = dates[0];
widget.jq.data().primeDatePicker.updateModel(null, dates);
}
}
</script>
Then in your DatePicker...
<p:datePicker id="range"
widgetVar="wgtRange"
selectionMode="range"
value="#{SearchBean.range}"
onblur="adjustDateRange('wgtRange')">
</p:datePicker>

Format number with commas in .each function

So I have some js which is converting a div class's number through a daily exchange rate engine. It outputs correctly as it should and I am now trying to separate this number it outputs using jQuery and a function I found whilst doing some research. I am trying to feed the number to the function using a .innerHTML method. I have got the function to alert a converted number but I have multiple elements which this function should run for, so have used an .each function - this is where something isn't working. I get no alert so I think there is something wrong with the .each code.
Can anyone see anything that might be causing it?
The complete code is here:
<script src="https://raw.githubusercontent.com/openexchangerates/money.js/master/money.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="hello">
2300
</div>
<div class="hello">
52400
</div>
<script>
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n= yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
$(".hello").each(function() {
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var demo = function(data) {
fx.rates = data.rates
var rate = fx(currentPrice).from("GBP").to("USD");
currentDiv.html("<div>"+currentPrice +"</div><div id='converted'> " +rate.toFixed(0)+"</div>");
//alert("Product Costs" + rate.toFixed(4))
}
$.getJSON("http://api.fixer.io/latest", demo);
});
$("#converted").each(function() {
var convertedPrice = $(this.innerHTML);
function runThis() { alert( ReplaceNumberWithCommas(convertedPrice)) }
setTimeout (runThis, 100);
});
</script>
I think the reason is
$("#converted").each(function() {
var convertedPrice = $(this.innerHTML);
function runThis() { alert( ReplaceNumberWithCommas(convertedPrice)) }
setTimeout (runThis, 100);
});
happends before you created the converted elements. Because you put the creation inside a get call.
I suggest you put this inside the callback of your get call.
Something like this
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n = yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var demo = function(data) {
fx.rates = data.rates
$(".hello").each(function() {
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var rate = fx(currentPrice).from("GBP").to("USD");
currentDiv.html("<div>" + currentPrice + "</div><div class='converted'> " + rate.toFixed(0) + "</div>");
//alert("Product Costs" + rate.toFixed(4))
});
$(".converted").each(function() {
var convertedPrice = $(this).html();
console.log(ReplaceNumberWithCommas(convertedPrice));
});
}
$.getJSON("https://api.fixer.io/latest", demo);

Javascript results to div

Q1: My point is create many buttons as many rows of array. Like this, only one button appears.
<script type="text/javascript">
var myArray = [];
$('#button').click(function(){
var value1 = $('#value1').val();
var value2 = $('#value1').val();
var value3 = $('#value1').val();
var newArray = [];
var newArray[0] = value1;
var newArray[1] = value2;
var newArray[2] = value3;
myArray.push(newArray);
$("#save").append(
$("<button>").click(function() {
myFunction.apply(null, myArray);
}).text("Click me!")
);
});
});
function myFunction(value1,value2,value3)
{
var jsonData = $.ajax({
url: "file.php?value1=" + value1 + "&value2=" + value2 + "&value3=" + value3
dataType: "json",
async: false
}).responseText;
(...)
}
//edited: problem maybe found. I said buttons dont do anything because of this.
OUTPUT: file.php?value1=paul,23,USA&value2=undefined&value3=undefined
//it seems that value1 gets all values :s
</script>
<div id ="save"></div>
Im looking for a solution that return someting like this:
eg:
<!--<button onclick="myFunction(name,age,country)">Click me</button>-->
<button onclick="myFunction(paul,23,USA)">Click me</button>
<button onclick="myFunction(john,23,USA)">Click me</button>
EDITED MY CODE WITH MORE DETAILS
.html replaces, and your quotes are mismatched. But it doesn't matter - jQuery is better at manipulating the DOM than it is at manipulating strings. Try:
$("#save").append(
$.map(myArray, function(item) {
return $("<button>").click(function() {
myFunction.apply(null, item);
}).text("Click me");
})
);
Here's a demo.
You're only seeing one button because the .html() method replaces the html of the element. It doesn't append.
Luckily, jQuery has a method for the behavior you want, fittingly called append. Change it to look like this:
for(i=0;i<myArray.length;i++)
{
var button = $("<button>Click me</button>");
$("#save").append(button) ;
}
I intentionally left the onclick behavior out of that snippet. You can write it in the html of the button you create, as you have been, or you can do it with jQuery - the second method is preferable, and would look like this:
for(i=0;i<myArray.length;i++)
{
var button = $("<button>Click me</button>")
.click(function(){
// call the actual function you want called here
});
$("#save").append(button);
}
Did you mean this:
<div id="save">
</div>
<script type="text/javascript">
function addButtons(){
for(i=0;i<myArray.length;i++)
{
var button = $('<button id="btn_'+i+'" onclick="myFunction(this);">Click me</button>')
$(button).data('details',myArray[i]).appendTo("#save");
}
}
function myFunction(element){
alert($(element).data('details'));
}
</script>
This is because you are replacing the html in the $("#save") in the loop . Try
$("#save").append("<button onclick="myFunction('"+myArray[i]+"')">Click me</button>") ;
for(i=0;i<myArray.length;i++){
//Create a new DOM button element ( as jQuery object )
// Set the current button index, and add the click action
var button = $('<button />').data('myindex', i).click(function(){
var myArrayItem = myArray[$(this).data('myindex')];
alert(myArrayItem);
}).html('My label n. '+i);
$('#save').append(button)
}
Why bothering with all the JQuery and complicated code, just use simple way to implement this
<script type="text/javascript" >
var myArray = ["New York", "Boston", "San Jose", "Los Angeles"];
var strHTML = "";
for(i=0;i<myArray.length;i++)
{
strHTML += "<button onclick='myFunction("+i+")'>Click me</button>";
}
$("#save").innerHTML = strHTML;
function myFunction(index)
{
alert(index);
// do your logic here with index
}
</script>

How to get child element by ID in JavaScript?

I have following html:
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
How can I get textarea element? I can't use document.getElementById("textid") for it
I'm doing it like this now:
var note = document.getElementById("note");
var notetext = note.querySelector('#textid');
but it doesn't work in IE(8)
How else I can do it? jQuery is ok
Thanks
If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.
$('#note').find('#textid');
You can also use jQuery selectors to basically achieve the same thing:
$('#note #textid');
Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.
On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.
Update 2020.03.10
It's a breeze to use native JS for this:
document.querySelector('#note #textid');
If you want to first find #note then #textid you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(
var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;
Here is a pure JavaScript solution (without jQuery)
var _Utils = function ()
{
this.findChildById = function (element, childID, isSearchInnerDescendant) // isSearchInnerDescendant <= true for search in inner childern
{
var retElement = null;
var lstChildren = isSearchInnerDescendant ? Utils.getAllDescendant(element) : element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].id == childID)
{
retElement = lstChildren[i];
break;
}
}
return retElement;
}
this.getAllDescendant = function (element, lstChildrenNodes)
{
lstChildrenNodes = lstChildrenNodes ? lstChildrenNodes : [];
var lstChildren = element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].nodeType == 1) // 1 is 'ELEMENT_NODE'
{
lstChildrenNodes.push(lstChildren[i]);
lstChildrenNodes = Utils.getAllDescendant(lstChildren[i], lstChildrenNodes);
}
}
return lstChildrenNodes;
}
}
var Utils = new _Utils;
Example of use:
var myDiv = document.createElement("div");
myDiv.innerHTML = "<table id='tableToolbar'>" +
"<tr>" +
"<td>" +
"<div id='divIdToSearch'>" +
"</div>" +
"</td>" +
"</tr>" +
"</table>";
var divToSearch = Utils.findChildById(myDiv, "divIdToSearch", true);
(Dwell in atom)
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
<script type="text/javascript">
var note = document.getElementById('textid').value;
alert(note);
</script>
Using jQuery
$('#note textarea');
or just
$('#textid');
$(selectedDOM).find();
function looking for all dom objects inside the selected DOM.
i.e.
<div id="mainDiv">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<div id="innerDiv">
link
<p>Paragraph 3</p>
</div>
</div>
here if you write;
$("#mainDiv").find("p");
you will get tree p elements together. On the other side,
$("#mainDiv").children("p");
Function searching in the just children DOMs of the selected DOM object. So, by this code you will get just paragraph 1 and paragraph 2. It is so beneficial to prevent browser doing unnecessary progress.

Categories

Resources