How can I add condition in string javascript? - javascript

My javascript code like this :
var res = `<td>
if(product.photo == photo.name)
<div class="box-check">
<span class="fa fa-check"></span>
</div>
</td>`;
I try like that. But seems it's wrong
How can I do it?

simplest (easiest) change I can think of is as follows:
var inner = product.photo == photo.name ? `<div class="box-check">
<span class="fa fa-check"></span>
</div>` : '';
var res = `<td>${inner}</td>`;
alternatively
var res = `<td>${product.photo == photo.name?'<div class="box-check"><span class="fa fa-check"></span></div>':''}</td>`;
but you can NOT (easily) make the <div><span etc multiline in this case
I didn't try hard enough - nested template literals FTW :p
var res = `<td>${product.photo == photo.name?`<div class="box-check">
<span class="fa fa-check"></span>
</div>`:''}</td>`;

Related

fail to modify content of template

<template id="entry-temp">
<li id="movie-list">
<span id="movie-info"> <span id = "li-movie-title"></span> (<span id = "li-movie-year"></span>) - <span id = "li-movie-rating"></span></span>
<button type="submit" id="movie-edit" name="movie-edit">edit</button>
<button type="submit" id="movie-delete" name="movie-delete">delete</button>
</li>
</template>
function appendMovie(title, year, rating) {
let template = document.querySelector("#entry-temp");
let tempNode = document.importNode(template.content, true);
tempNode.querySelector("#li-movie-title").innerHTMl = title;
tempNode.querySelector("#li-movie-year").innerHTMl = year;
tempNode.querySelector("#li-movie-rating").innerHTMl = rating;
let moviePanel = document.getElementById("movie-panel");
alert(tempNode.innerHTMl);
moviePanel.appendChild(tempNode);
}
The alert gives me undefined, and tempNode is a document fragment.
Also, is there a better way to print out the tag in JavaScript for debugging?
For example, How can I check if I really write title, year, and rating?

Get Innerhtml of a nestate span element jquery?

just wants to get the inner html of a nestate span tag..
<span class="select2-selection__rendered" id="select2-SearchByUser-container" title="chowdhury , nayan (nayanchowdhury92#gmail.com)">
<span class="select2-selection__clear">×</span>
mark john
</span>
i need mark john and i try =>
alert($('#select2-SearchByUser-container').html())
i give output/alert something like =>
<span class="select2-selection__clear">×</span>mark john
is there any way that i can get only mark john...help please...
To do what you need you can retrieve the last textNode in the element, like this:
var text = $('#select2-SearchByUser-container').contents().filter(function() {
return this.nodeType == 3 && this.nodeValue.trim();
}).last().text().trim();
console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="select2-selection__rendered" id="select2-SearchByUser-container" title="chowdhury , nayan (nayanchowdhury92#gmail.com)">
<span class="select2-selection__clear">×</span> mark john
</span>
Try this :
https://jsfiddle.net/4nwp25Le/
jQuery(document).ready(function() {
var node = $('#select2-SearchByUser-container').contents().filter(function() {
return this.nodeType == 3; // text node
});
alert(node.text());
});
Your html is not good so far, if possible fix that so that you can get different spans for them.
If you don't have control over HTML, can give a try like this
$('#select2-SearchByUser-container').clone().children().remove().end().text()
https://jsfiddle.net/qspoygox/
var el = document.getElementById("select2-SearchByUser-container"),
child = el.firstChild,
texts = [];
while (child) {
if (child.nodeType == 3) {
texts.push(child.data);
}
child = child.nextSibling;
}
var text = texts.join("");
alert(text);
<span class="select2-selection__rendered" id="select2-SearchByUser-container" title="chowdhury , nayan (nayanchowdhury92#gmail.com)">
<span class="select2-selection__clear">×</span>
mark john
</span>

Trouble declaring and referencing global array in JS

I am attempting to create a global array in javascript to use in multiple functions. The array does not display when attempting to callback.
var iListCount = 0;
var arrListItems = new Array;
function addItem(){
var list = document.getElementById('spanUser');
var sText = document.getElementById('item-text').value;
if (isNaN(iListCount)){
iListCount = 0;
}
if (sText != "") {
iListCount++;
arrListItems[iListCount] = sText;
list.innerHTML = list.innerHTML+"<li class='list-group-item' id='lis"+iListCount+"'>"+sText+"</li>";
document.getElementById("item-text").value = "";
} else {
document.getElementById("item-text").focus();
alert(arrListItems[1]);
}
}
Edit: Html
<div class="form-group" style="margin-bottom:65px" id="header-div">
<label class="txt-sub pull-left">_items</label>
</div>
<div style="margin-left:40px">
<div class="form-group">
<input type="text" class="form-control pull-left" id="item-text" style="margin-bottom:10px; width:200px;margin-right:10px" onKeyUp="if (event.keyCode == 13) document.getElementById('btnAddItem').click()">
<button class="btn btn-default " onClick="addItem()" id="btnAddItem">add</button>
<button class="btn btn-default pull-right" onClick="removeItem()">remove last item</button>
<ul class="list-group" id="user-item" style="margin-top:10px">
<span id="spanUser">
</span>
</ul>
</div>
</div>
<!--End Items-->
Define a global variables from the window object:
window.iListCount = 0;
window.arrListItems = [];
Are you only using iListCount as an index for arrListItems if so replace:
iListCount++;
arrListItems[iListCount] = sText;
with this:
arrListItems.push(sText);
And replace iListCount references with arrListItems.length.
I used the above suggestions in the following fiddle as well as some other good practice measures:
http://fiddle.jshell.net/2hEby/
Just initialize the array like that:
var arrListItems = [];
If you are checking the array result at the statement
alert(arrListItems[1]);
then make sure that the array has got two elements atleast.
First element of the array can be read using the index 0 and second with 1 and so on.
If you are trying to read first element, use
alert(arrListItems[0]);
Also the statements
iListCount++;
arrListItems[iListCount] = sText;
should be merged to one statement like this
arrListItems[iListCount++] = sText;
so that you can start adding elements to the array from it's first location.
You may also try
arrListItems[arrListItems.length] = sText;
Example for arrListItems[iListCount++] = sText;

Show one random icon on page load

How do I show one random icon on page load with js? Below is the HTML code I have:
<span>
<i class="fa fa-trash-o" id="icon-one"></i>
<i class="fa fa-frown-o" id="icon-two"></i>
<i class="fa fa-thumbs-o-down" id="icon-three"></i>
</span>
I need to show only one of the three icons.
My HTML would be
<span id = "mySpan"></span>
You can do this using javascript
var myRand = Math.floor(Math.random() * 3) + 1;
var randString = '';
if(myRand == 1)
randString = 'one';
else if(myRand == 2)
randString = 'two';
else if(myRand == 3)
randString = 'three';
var ele = document.createElement("div");
ele.setAttribute("id","icon-"+randString );
document.getElementById("mySpan").appendChild(ele);
Well , this assumes that your ids have the icon and not the classes
<span>
<i class="fa fa-trash-o" style="display: none;" id="icon-one"></i>
<i class="fa fa-frown-o" style="display: none;" id="icon-two"></i>
<i class="fa fa-thumbs-o-down" style="display: none;" id="icon-three"></i>
</span>
var icons = [ 'icon-one', 'icon-two', 'icon-three' ],
icon = icons[Math.floor(Math.random()*icons.length)];
$( '#' + icon ).show();
This should work if you are using jquery.
use this function to get a random no in range(min, max)
function getRandomArbitary (min, max) {
return Math.random() * (max - min) + min;
}
and use appropriately to show the tag hide other wise
such as
js
var r = function getRandomArbitary (1, 3);
var eleCategory = document.getElementById("main_div");
var eleChild = eleCategory.childNodes;
for( i = 0 , i<eleChild.length; i++ ){
if(i==r){
eleChild[ i ].style.display='block';
}
else
{
eleChild[ i ].style.display='none';
}
}
html
<span id="main_div">
<i class="fa fa-trash-o" id="icon-one"></i>
<i class="fa fa-frown-o" id="icon-two"></i>
<i class="fa fa-thumbs-o-down" id="icon-three"></i>
</span>
you can use java script here. So if there are only three icons one , two and three.
use random function to generate a number between one two and three
var x= Math.floor((Math.random()*3)+1);
if (x==1)
{
//fetch the div id = "icon-one" and display
}
else if (x==2)
{
//fetch the div id = "icon-two" and display
}
else
{
//fetch the div id = "icon-three" and display
}
Although this will work way better if you can rename your id's two icon1,icon2 and so on
it will just be this then :
var x= Math.floor((Math.random()*3)+1);
var icon = "icon";
var id = icon.concat(x);
Simple work woth using jQuery.
Working jsFiddle

How to get text from span->li->ul-> Element

Hello i have cart full with Elements
This Ex of one of them
<div class="item-container cart-item">
<div>
<img border="0" onerror="src='http://www.myengravedjewelry.com/Admin/surfing.jpg'" title="Bloody Mary Style Colour Name Necklace" src="http://www.myengravedjewelry.com/Admin/surfing.jpg" alt="1009">
<div class="item-header">
<div class="item-body">
<ul class="item-ul">
<li>
<li>
<li>
<span class="bold-14">Price:14.9 </span>
</li>
<li>
<span>ShortId:1010 </span>
</li>
<li>
<span>LongId:110-01-073-10 </span>
</li>
<li>
<span class="spanDefCat">DefaultCat:334 </span>
</li>
</ul>
</div>
</div>
<div class="item-footer"></div>
</div>
When i press save i go trow each one of this element and check if DefaultCat==0
var elements = document.getElementsByClassName("cart-item");
and i try to get to this defaulCat like this
for(i=0;i<elements.length;i++){
var elementContent=elements[i].find(".spanDefCat").html();
var vars = elementContent.split(" ");
var obj = {};
vars.forEach(function(v) {
var keyValue = v.split(":");
obj[keyValue[0]] = keyValue[1];
});
DefaultCat = obj["DefaultCat"];
ShortId = elements[i].children[1].alt;//New style to take ShortID
if(DefaultCat==0)setDefaultCatToProductId(parseInt(ShortId));
arrSortedOrder[i]=parseInt(ShortId);
}
Any one know how to get to this value?
p.s
Plz Do NOT give me solution with $(.spanDefCat) because when i find deff=0 i need to take ShordId as Well from this element[i]
Try this:
$(".cart-item").each(function(){
var shortId = $(this).find(".bold-14").parent("li").siblings("li").children("span").html();
var shortItem = shortId.replace(' ','').split(":");
var defaultCat = $(this).find(".spanDefCat").html();
var item = defaultCat.replace(' ','').split(":");
if(item[1]==0){
var id = parseInt(shortItem[1]);
//do something
}else{
var id = parseInt(shortItem[1]);
//do something else
}
console.log(defaultCat);
console.log(shortId);
});
Note: Above code give you the DefaultCat:334 and ShortId:1010 so now you can use both in if else statement.
If the format of DefaultCat:334 is same for all cart item then you can check whether it is 0 or not
JSFIDDLE DEMO
I see JQuery tag so i give you a response with JQuery statements.
$(".cart-item").find(".spanDefCat").each(function(index, domEle){
//get text, delete spaces and split
split_result = $(domEle).text().replace(' ','').split(":");
//get only numeric value as string
defaultCat = split_result[1];
//parse into int
defaultCat = parseInt(defaultCat);
//if your var is equal to 0
if(defaultCat == 0){
/*********************
* Type you code here *
**********************/
}
});

Categories

Resources