apply diffrent css for text separated by comma inside <div> - javascript

i am trying to change color for text which are separated by comma(','). i cant use any other tag to separate these. is that possible by jQuery or by css?
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">ABCD,XYZ</div>
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">cdE,hhhh</div>

Created a fiddle for you
var colorArr = ['red', 'green'];
$( "[data-value='ABCD,XYZ']" ).each ( function(){
var valueArr = $( this ).html().split( "," );
console.log( valueArr );
for (var counter = 0; counter < valueArr.length; counter++ )
{
valueArr[ counter ] = "<span style='color:" + colorArr[ counter ] + "'>" + valueArr[ counter ] + "</span>";
}
console.log( valueArr );
$( this ).html( valueArr.join("") );
} );

Im not sure if you are referring to the innerHTML or the tag's value.. either way. I was not able to test this due to browser issues.
$('div').each(function(){
var textArray = $(this).html().split(',');
var html = '';
for(var i = 0; i < textArray.length; i++) {
html += '<span style="color: #12345' + i + '">' + textArray[i] + '</span>';
}
$(this).html(html);
}

This is what I would do:
$("[data-value]").each(function(){
var words = $(this).text().split(",");
$(this).text("");
for(var i=0; i< words.length; i++){
var r = Math.floor((Math.random() * 255) + 1);
var g = Math.floor((Math.random() * 255) + 1);
var b = Math.floor((Math.random() * 255) + 1);
$(this).append("<span style='color:rgb("+r+","+g+","+b+")'>"+words[i]+ ((i< words.length-1) ? ",":"")+"</span>");
}
});
Here is the JSFiddle demo
The code randomly generates colors and sets a different color for each word.

You can use
:contains() css3 selector

Check this out
$(document).ready(function(){
$('div').each(function(){
var text = $(this).text();
var array = text.split(',');
var html = array[0] + ',<span style="color:red">' + array[1] + '</span>';
$(this).html(html);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">ABCD,XYZ</div>
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">cdE,hhhh</div>

Since you are using attr data use .data() to find your elements
$('div').data('value','ABCD,XYZ').each(function(i,vi){
var arrVi = vi.innerText.split(',');
var html = '';
arrVi.forEach(function(vj,j){
html += '<span style="color: green">' + vj + '</span>';
});
vi.innerHTML= html;
})
Change the code to the ways it suits you better.

If you can't change the html code at all you can use :before and :after pseudo selectors.
Split the text by ,.
Set attributes for each of them.
Set content to :before and :after by the attributes
Style those pseudo elements.
This solution will works only with 1 comma separation.
[].forEach.call(document.querySelectorAll('div'), function(item) {
// check if there is a , in the text
if (item.innerText.indexOf(',') > -1) {
var texts = item.innerText.split(',');
item.setAttribute('data-text1', texts[0]);
item.setAttribute('data-text2', texts[1]);
item.innerHTML = ',';
}
});
div:before {
content:attr(data-text1);
color:red;
}
div:after {
content:attr(data-text2);
color:yellow;
}
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">ABCD,XYZ</div>
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">cdE,hhhh</div>

Related

Error binding Click Event in for loop in Javascript

I am trying to get array elements(which may be objects) in alert onclick. But, message is not binding on click.
this.openLink() method not getting alert for message and correct value.
I am missing something here while binding click events?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myBox(){
this.create = (id, id3 , arrData) => {
var html = "<div id='box1' class='col-12'></div>";
$("#box").append(html);
var html1 = "<div id='box2' class='col-12'></div>";
$("#box").append(html1);
this.createList(id, id3 , arrData)
}
this.createList = (id, id3 , arrData) =>{
var html = '';
html +='<ul id="' + id + '_List" class="col-12 rmpm" style="overflow-x:scroll;overflow-y:hidden;list-style- type:none;white-space:nowrap;font-size:0;padding: 0px 0px 10px 0px;">';
for (var i = 0; i < arrData.length; i++) {
var iD = id + '_utt' + i;
html += '<li id="' + iD + '" class="col-12 rmpm" style="display:inline;width:auto;border:1px solid #ccc;display:inline-block;font-size:14px;padding: 5px;border-radius: 5px;margin: 10px 10px 10px 0px; cursor: pointer;">';
html += arrData[i];
html += '</li>';
}
html += '</ul>';
$(id3).append(html);
// ---> here, some error for binding click event on li
arrData.forEach((element) => {
$(document).on('click', '#' + iD, () => {
this.openLink(element);
});
});
}
this.openLink = (message) =>{
alert(message); //a,b,c,as,bqsq,csqs <--- alert expecting here
}
}
</script>
<script>
function abc(){
var arrData = ['a','b','c'];
var arrData2 = ['as','bqsq','csqs'];
var bx = new myBox();
bx.create('arrData',"#box1" , arrData);
bx.create('arrData2',"#box2" , arrData2);
}
</script>
</head>
<body>
<button onclick="abc()">Clcik</button>
<div id="box" style=""></div>
</body>
</html>
You are assembling the id, in the for loop above your foreach, then you are using that id to set the clicklistener, you need to assemble the correct id at every loop in the foreach or else you will only put a listener on the last button.
Change your forEach to this:
arrData.forEach((element, index) => {
var clickId = id + '_utt' + index;
$(document).on('click', '#' + clickId, () => {
this.openLink(element);
});
});
To put it into the html as an onclick="function()" you need to assign it in the first loop when you are creating the HTML. and move openlink outside myBox()
function myBox() {
this.create = (id, id3, arrData) => {
var html = "<div id='box1' class='col-12'></div>";
$("#box").append(html);
var html1 = "<div id='box2' class='col-12'></div>";
$("#box").append(html1);
this.createList(id, id3, arrData)
}
this.createList = (id, id3, arrData) => {
var html = '';
html += '<ul id="' + id + '_List" class="col-12 rmpm" style="overflow-x:scroll;overflow-y:hidden;list-style- type:none;white-space:nowrap;font-size:0;padding: 0px 0px 10px 0px;">';
for (var i = 0; i < arrData.length; i++) {
var iD = id + '_utt' + i;
html += '<li ' + 'onclick="openLink(\'' + arrData[i] + '\')" id="' + iD + '" class="col-12 rmpm" style="display:inline;width:auto;border:1px solid #ccc;display:inline-block;font-size:14px;padding: 5px;border-radius: 5px;margin: 10px 10px 10px 0px; cursor: pointer;">';
html += arrData[i];
html += '</li>';
}
html += '</ul>';
$(id3).append(html);
}
}
openLink = (message) => {
alert(message); //a,b,c,as,bqsq,csqs <--- alert expecting here
}
function abc() {
var arrData = ['a', 'b', 'c'];
var arrData2 = ['as', 'bqsq', 'csqs'];
var bx = new myBox();
bx.create('arrData', "#box1", arrData);
bx.create('arrData2', "#box2", arrData2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<body>
<button onclick="abc()">Clcik</button>
<div id="box" style=""></div>
</body>
' + 'onclick="openLink(\'' + arrData[i] + '\')" . How does this worked. Can you please explain or provide some link so that I can understand
The line renders as onclick="openLink('a')" onclick="openLink( renders to the DOM as written. the \' renders a ' in the DOM and javascript sees it as a character that way i dont break the string, but it renders as a ' in the DOM. Then i add arrData[i] that is the n'th (or i'th) index in the array. then i use the same trick to close the onclick function off.

For Loop with two array in javascript

I am new in js and have this problem. I have two arrays and like to achieve this layout by using for loop. I do not know how to write this to achieve it. Here is my code. Please help.
var html ='';
var option = ['meal', 'drink'];
var option_type = ['big', 'medium', 'small', 'big', 'medium'];
for (var i in option){
for ( var j in option_type){
html += '<div>'+ option[i] + '</div>'+'<p>'+option_type[j]+'</p>';
}
}
.(class).html(html);
You can use for like:
var html = '';
var option = ['meal', 'drink'];
var option_type = ['big', 'medium', 'small'];
for (i = 0; i < option.length; i++) {
html += '<div>' + option[i] + '</div>'; //Add option here (header)
for (j = 0; j < option_type.length; j++) {
html += '<p>' + option_type[j] + '</p>'; //Add option_type
}
}
$('body').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
An object data structure is better for representing what you want (at least based on the screenshot)
var options = {
meal: ['big', 'medium', 'small'],
drink: ['big', 'medium']
}
var html = Object.keys(options).reduce((all, option) => {
var headerMarkup = `<div>${option}</div>`;
var itemsMarkup = options[option].map(item => `<p>${item}</p>`).join('');
return `${all}${headerMarkup}${itemsMarkup}`;
}, '');
You can do something like this:
var html ='';
var option = [
['meal', 'big', 'medium', 'small'],
['drink', 'big', 'medium' ]
];
for (var i = 0; i < option.length; i++){
var option_type = option[i];
html += '<div>' + option_type[0] + '</div>';
for(var j = 1; j < option_type.length; j++) {
html += '<span>' + option_type[j] + '</span>';
}
}
document.getElementById('container').innerHTML=html;
#container span{
display:inline-block;
margin-right:10px;
border:1px solid #333;
padding:10px;
}
<div id="container"></div>
this is the direct answer to how to use nested for loops. But if you want to vary the option_types for each option, you will probably want to use an object as suggested by scetiner
var html ='';
var option = ['meal', 'drink'];
var option_type = ['big', 'medium', 'small'];
for (var i in option){
html += '<div><h1>'+ option[i] + "<h1>";
for ( var j in option_type){
html += '<p>'+option_type[j]+'</p>';
}
html += '</div>';
}
document.getElementById('container').innerHTML = html;
#container{
}
h1{
}
#container p{
display:inline-block;
margin:10px;
border:1px solid #333;
min-width: 100px;
padding:10px;
}
<div id='container'></div>
option_type is useless and not logical, try something like this
var html ='';
var option = {
'meal': [
'big',
'medium',
'small'
],
'drink': [
'big',
'medium'
]
};
for (var key in option){
html += '<div>'+ key + '</div>'
for ( var j of option[key]){
html += '<p>'+j+'</p>';
}
}
.(class).html(html);
Followin you approach here a full example: https://jsfiddle.net/57q39xre/17/
The key is:
for (var i in parent){
//parent code
for ( var j in child){
//parent and child code
}
//parent code
}
Each parent will iterate each child.

how to highlight a table cell onClick with unique colors in each cell

In the fiddle below, you can click on any of the cells and they will change colors to those in td.highlighted in the CSS. I want the highlighted color to be assigned inline instead and unique to each element.
https://jsfiddle.net/rvxnmz8r/7
this is the line that generates the style for each table element, and I think the main problem is that I am dumb with CSS. Thanks for any help.
var hstyle = 'style="td.highlighted {background-color: ' + '#'+Math.random().toString(16).substr(-6) + '; color: black;}"';
update: the cells need to remain toggle-able between the default and custom highlighted colors.
When using inline style combined with external CSS, the external need !important to override the inline style.
As a side note, using !important impact the usability of styling in a more difficult way to reuse, though, in your case, create 60 classes to toggle, I found more bad, hence the use of !important
Change your script to
var hstyle = 'style="background-color: ' + '#' + Math.random().toString(16).substr(-6) + '; color: black;"';`
And your CSS to
td.highlighted {
background-color: blue !important;
color: white !important;
}
Stack snippet
var elements = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var transtable = [elements, elements, elements, elements, elements, elements];
var output = [];
output.push('<table id="taxatable">');
for (var row = 0; row < transtable[0].length; row++) {
output.push('<tr>');
for (var col = 0; col < transtable.length; col++) {
var hclass = 'class="highlighted"';
var hstyle = 'style="background-color: ' + '#' + Math.random().toString(16).substr(-6) + '; color: black;"';
output.push(
'<td ' + hclass + ' ' + hstyle + '>' + escape(transtable[col][row]) + '</td>'
);
}
output.push('</tr>');
}
output.push('</table>');
document.getElementById('output').innerHTML = output.join('');
var tbl = document.getElementById("taxatable");
if (tbl != null) {
for (var trow = 0; trow < tbl.rows.length; trow++) {
for (var tcol = 0; tcol < tbl.rows[trow].cells.length; tcol++) {
tbl.rows[trow].cells[tcol].onclick = function() {
this.classList.toggle("highlighted");
};
//console.log(tbl.rows[trow].cells[tcol]);
}
}
}
td {
background-color: black;
color: white;
}
td.highlighted {
background-color: blue !important;
color: white !important;
}
<div id="output">
</div>
Edit
I see what you’re trying to do, but your solution is mixing two things together: inline styles and CSS rules. You can only use style="" on an element to set styling directly on that element, which overrides the rules from your stylesheet. If you want to toggle the highlight class on and off you could do something like this (using jQuery):
$("td").click(function() {
$(this).toggleClass('highlighted');
});
Also, it needs the !important modifier in the highlighted class, as #LGSon explains above.
In combination with my answer below (removing td.highlighted in the inline style), this should probably result in what you are looking for.
Old answer
If you use inline styles, you are styling directly on the HTML element and you won’t need to define a CSS selector. Instead of
var hstyle = 'style="td.highlighted {background-color...
you can simply write:
var hstyle = 'background-color...'
So, your code becomes:
var hstyle = 'style="background-color: ' + '#'+Math.random().toString(16).substr(-6) + '; color: black;"';
You were close. Remove the td.highlighted like so
var hstyle = 'style="background-color: ' + '#'+Math.random().toString(16).substr(-6) + '; color: black;"';

getJSON JSON Array - Search Functionality Crashing Client

I'm running into a problem when trying to add in the search functionality, showList().
It seems to bog down the client so much that Chrome wants to kill the page each time I type into the input field. I'm clearly a novice JS writer, so could I be running an infinite loop somewhere I don't see? Also, any advice to get the search functionality working properly would be hugely appreciated. I don't think I'm using the correct selectors below for the show/hide if statement, but I can't think what else to use.
$(document).ready(function(){
showList();
searchBar();
});
function showList() {
$("#show-records").click(function(){
$.getJSON("data.json", function(data){
var json = data;
$("show-list").append("<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
$("#show-list").append("<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>");
$("show-list").append("</table>");
}
//end getJSON inner function
});
//end click function
});
//end showList()
};
function searchBar() {
//AJAX getJSON
$.getJSON("data.json", function(data){
//gathering json Data, sticking it into var json
var json = data;
for(var i = 0; i < json.length; i++) {
//putting the json objects into var obj
var obj = json[i];
function contains(text_one, text_two) {
if (text_one.indexOf(text_two) != -1)
return true;
}
//whenever anything is entered into search bar...
$('#search').keyup(function(obj) {
//grab the search bar content values and...
var searchEntry = $(this).val().toLowerCase();
//grab each td and check to see if it contains the same contents as var searchEntry - if they dont match, hide; otherwise show
$("td").each(function() {
if (!contains($(this).text().toLowerCase(), searchEntry)) {
$(this).hide(400);
} else {
$(this).show(400);
};
})
})
}
});
};
body {
background-color: lightblue;
}
tr:first-child {
font-weight: bold;
}
td {
padding: 3px;
/*margin: 10px;*/
text-align: center;
}
td:nth-child(6) {
padding-left: 50px;
}
td:nth-child(7) {
padding-left: 10px;
padding-right: 10px;
}
#filter-count {
font-size: 12px;
}
<html>
<head>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script language="javascript" src="process.js"></script>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
</head>
<body>
<a href="#" id='show-records'>Show Records</a><br>
<label id="searchBar">Search: <input id="search" placeholder="Enter Specialist Name"></label>
<span id="search-count"></span>
<div id="show-list"></div>
</body>
</html>
Problem appears to be that you can't treat append as if it was a text editor and you are writing html.
Anything that gets inserted needs to be a proper element ... not a start tag, then some text...then a close tag.
We can however modify your code slightly to produce html strings and then add that at the end
$.getJSON("data.json", function(data){
var json = data;
var html="<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
html+= "<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>";
}
html+= '</table>';
$("#show-list").html(html);
//end getJSON inner function
});

change font size after decimal point

I am working with an Opencart E-Commerce website, I need to customize product price font size,
for example:
product price: $ 250.50 i need to set font size for $ = 16px; 250 = 22px; .50 = 14px;
How can I set different font sizes for a single amount..???
this s my dynamic php code that display price text to my product page:
<span class="price"><?php echo $product['price']; ?></span>
my product list page not a single product with price, there is a lots of product with price list.
thanks for any help, if anybody asked the same question before here, please share with me those links...
$.each($('.price'), function(){
var price = $(this).html();
$(this).html(price.replace(/(\D*)(\d*\.)(\d*)/,'<span style="font-size:16px;">$1</span><span style="font-size:22px;">$2</span><span style="font-size:14px;">$3</span>'));
});
http://jsfiddle.net/gr8x5/10/
Here's a quick and dirty example:
<html>
<head>
<style>
.dollar_sign { font-size: 16px; }
.dollars { font-size: 22px; }
.cents { font-size: 14px; }
</style>
</head>
<body>
<?
$product = array('price' => '245.50');
$part = explode('.', $product['price']);
?>
<span class="dollar_sign">$</span><span class="dollars"><?= $part[0] ?></span>.<span class="cents"><?= $part[1] ?></span>
</body>
</html>
Try this code
var pri = $(".price").text();
var sig = pri.split(" ");
var dol_smbl = "<span style='font-size:16px;'>" + sig[0] + "</span>";
var digits = sig[1].split(".");
befr_dec = "<span style='font-size:22px;'>" + digits[0] + "</span>";
aftr_dec = "<span style='font-size:14px;'>." + digits[1] + "</span>";
$(".price").html(dol_smbl + " " + befr_dec + aftr_dec);
Can be beautifully done with a little css and regex. See this fiddle
the HTML :
<span class="price">$250.50</span>
the css :
.currency { font-size:16px; }
.number { font-size:22px; }
.decimal { font-size:14px; }
the javascript :
var price = $('span.price').text();
var pArry = price.match(/^(\$)(\d+)(\.\d+)?/);
var new_span = $(
'<span class="currency">' + pArry[1] + '</span>' +
'<span class="number">' + pArry[2] + '</span>' +
'<span class="decimal">' + pArry[3] + '</span>');
$('span.price').replaceWith(new_span);
Done
Try like this
var my_price = $(".price").text();
var dol_smbl = "<span style='font-size:16px;'>"+my_price[0]+"</span>";
var price = split(" ",my_price);
var price_arr = split('.',price[1]);
befr_dec = "<span style='font-size:22px;'>"+price_arr[0]+"</span>";
aftr_dec = "<span style='font-size:14px;'>."+price_arr[1]+"</span>";
$(".price").html(dol_smbl + " " + befr_dec + aftr_dec);
The easiest way would be to split up that var? Look at the php function explode().
http://php.net/manual/de/function.explode.php
You can try this generic approach
$('.price').each(function () {
var $this = $(this),
txt = $this.text(),
splt = txt.split('.'),
spltFirst = splt.pop(),
spn3 = $('<span/>', {
text: spltFirst,
'class': 'font-small'
}),
spltSecond = splt.pop(),
spn1 = $('<span/>', {
text: spltSecond.substring(0, spltSecond.lastIndexOf('$') + 1),
'class': 'font-medium'
}),
spn2 = $('<span/>', {
text: spltSecond.substring(spltSecond.lastIndexOf('$') + 1) + '.',
'class': 'font-big'
});
$this.text('');
$this.append(spn1).append(spn2).append(spn3);
});
Check Fiddle
Use different span element for those three different segments and set class for them individually to assign different font styles. Basically spans are inline element, so you dont need to worry about its placement.
For example:
After rendering your markup should be like this,
<span class="price">
<span class="currencySymbol">$</span>
<span class="amt1">250</span>
<span class="amt2">.50</span>
</span>
then in CSS:
.currencySymbol{ font-size:16px; }
.amt1{ font-size:22px; }
.amt2{ font-size:14px; }
A possible simple dynamic way using only split().
This will wrap decimals in a <small> tag on each element having a class format .
document.querySelectorAll(".format").forEach((e) => {
let txt = e.innerHTML.split(".")
e.innerHTML = txt[0] + ".<small>" + txt[1] + "</small>"
})
.format {font-size:3rem}
small {font-size:1.4rem}
<div class="format">34454.545432</div>
<div class="format">0.0000463533</div>
<div class="format"><mark>Hello</mark> -8765.9876</div>

Categories

Resources