Checking for decimal character code in element - javascript

I have a sorting feature I am making for my tables and as such I have used the decimal character codes...
▲
▼
...to create a representation of an up and down arrow. When I click on the arrow it calls a function to do the sorting (and also to switch the orientation of the arrow). To do this I have been trying to use code along these lines...
const assn = this.id;
const text = document.getElementById(assn).innerHTML;
if (text === "▼") {
document.getElementById(assn).innerHTML = "▲";
}
else {
document.getElementById(assn).innerHTML = "▼";
}
However this does not seem to work as the variable text seems to save as the literal arrow itself, and compare to the literal string "&#9660" instead of the arrow that this string will create. I am wondering if this is the cause, and if so, is there any way in which I can actually compare the character codes together?
I have tried using document.getElementById(assn).textContent too but this seems to have the same effect. Thank you for all your help.

why don't you try just CSS ? Simplest version below:
<style type="text/css">
.arrowControl > span {display:none;}
.arrowControl.down > span.down
, .arrowControl.up > span.up {display:inline;}
</style>
<div id="anyContainer">
<div class="arrowControl">
<span class="down" onclick="funcForDown();">▼</span>
<span class="up" onclick="funcForUp();">▲</span>
</div>
</div>
and then in your JS
var arrow=document.querySelector('#anyContainer .arrowControl');
if (arrow.classList.contains('up')){
arrow.classList.remove('up');
arrow.classList.add('down');
}
else {
arrow.classList.remove('down');
arrow.classList.add('up');
}

Related

How to apply a class based on the content being upper or lower case

I'm trying to select multiple <div> elements with the class .choice and then check if the contents are all uppercase OR if the contents are all lowercase. Based on if its contents are all lowercase or uppercase i then want to apply a CSS class.
I've been trying to use Jquery/Javascript to do this however I'am very new to both languages.
The Jquery i used was along the lines of:
$(".choice").text()
// and also
$(".choice").text().isUppercase().addClass()
But i'm pretty sure i can't use JavaScript and Jquery in this manner.
To achieve this you can provide a function to addClass() which checks the case of the text in the current element and returns the class to add based on what it finds. Try this:
$(".choice").addClass(function() {
var t = $(this).text();
if (t.toUpperCase() === t)
return 'upper';
else if (t.toLowerCase() === t)
return 'lower'
});
.upper { color: #C00; }
.lower { color: #0C0;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="choice">ALL UPPERCASE</div>
<div class="choice">Both Cases</div>
<div class="choice">all lowercase</div>
Note that the if condition can be shortened using the below ternary statement. It's a personal preference if you prefer brevity over readability:
return t.toUpperCase() === t ? 'upper' : t.toLowerCase() === t ? 'lower' : null;

Check if field contains numbers, wrap the numbers with container and class?

If you have something simple like this in HTML:
<div class="main">Item 7,000</div>
How to make javascript apply an html element and a class for the 7,000 part (because its numeric) on page load? To something like this:
<div class="main">Item <span class="wrap">7,000</span></div>
Or maybe just an html element, if with class not possible.
I apologies I don't have any code to share right now. I'm still browsing other questions.
Maybe it should be something with jQuery if $.isNumeric() is true then apply element?
There will be edge case but accomplishes your goal
$(function () {
$(".main").each(function (index, element) {
var $element = $(element);
var wrapped = $element.text().replace(/(.+?)((\d{1,3},?)+)/g, '$1<span class="wrap">$2</span>');
$element.html(wrapped);
});
});
.wrap {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">Item 7,000</div>
<div class="main">Item 960</div>
<div class="main">Item 7,000,000</div>
If you use node.textContent you can get the string inside the div
string = document.querySelector('#main').textContent // --> "Item 7,000"
From here you can use Array#split to separate each word:
array = string.split(' '); --> ['Item','7,000']
Now remove the comma and check isNaN for each, return an array w:
newNode = array.map((e)=> isNaN(e.replace(/,/g,"")) ? e : {element:'span', content: e})
Now you have ['Item', { element: 'span', content: '7,000'}] which you can use to generate the contents of the div element in your example...
There might be way better ways to do this, I am just trying to help :)
Use javascript regex find a matching number and replace with span
var regex =/\b(\d+)\b/g
var regex =/\b(\d+)\b/g
var text = document.getElementById("main").innerHTML;
document.getElementById("main").innerHTML = text.replace(regex,'<span class="wrap">$1</span>')
span.wrap{
color:red;
}
<p id="main">Item : 7000</p>

Two different css classes in the same javascript line

I'm trying to assign these css values (below) for the javascript line in the example below, but don't know a way to target valueB with the .valueB-class.
$(".valueA").html(valueA + " valueB" + ((valueA > 1) ? 's': ''));
.valueA-class { font-size:X }
.valueB-class { font-size:XX }
Here is an example of what I need help with (you may have to click on the input boxes in the results panel to get the calculations to show up - that's what I had to do): http://jsfiddle.net/hughett/g21g8t85/
Welcome to stackoverflow!
Your question seems a bit vague. I assume that this is you want to achieve. In the specific example the value of the class is changed through the use of the jquery attr function. Firstly, the specific div in which our text is placed is retrieved and then the value gets specified. I am attaching a code snippet below.
A general note, using a . in css indicates that you are referring to a class so there is no need to attach a -class in the name.
$( "#myButton" ).on( "click", function() {
var attr = $("#myText").attr('class');
console.log(attr);
if (attr == "valueA") {
$("#myText").attr("class","valueB");
} else {
$("#myText").attr("class","valueA");
}
});
.valueA { font-size:11pt }
.valueB { font-size:25pt }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton" type="button">Change Text size</button>
<div id="myText" class="valueA">sdsa asd aasdaas asdjlasj dasdkas asldjsalj slad TEST</div>
EDIT to include another answer
In order for the text included in a single span to have different font-size you need to separate it somehow. In the specific example, I have added a second span in the respective div and adjusted the cacl_summary method to get the expected result.
The code is available below; I have also updated the jsfiddle here
<div style="background:yellow;"><span class="label">Simple payback</span>
<span class="figure sp"></span> <span class="figure year"></span></div>
function calc_summary(){
if (cspy) {
sp = parseFloat($("input[name=upgrade]").val()) / cspy;
if (sp) {
sp = (sp < 100) ? sp.toString().substring(0, 4) : sp;
$(".sp").html(sp);
$(".year").html(" years" + ((sp > 1) ? 's': ''));
$(".ror").html(parseInt((1/sp) * 100) + '%');
}
}
}

Underline some characters in a String

I have the following problem:
My JavaScript code shows a display value this way:
d3.select("#" + uiElement).html("")
.append("span").attr("class", "displayvalue").html(stringToUse);
stringtoUse is the value to show, my issue is to underline that string, but some times, it's not required underline all the string but all except the first character of it.
In your opinion what's the best way to do so?
Use CSS first-letter pseudo element. Make your all text underlined and then apply css to it as:
#element::first-letter
{
text-decoration:none !important:
}
Reference to use.
By simple pure javascript:
var text = document.getElementById("element").innerHTML;
document.getElementById("element").innerHTML = text.substring(0,1)+"<u>"+text.substring(1)+"</u>";
This will allow you to format any javascript innerHTML using CSS directly, without hassling around in javascript:
The javascript:
function test(){
document.getElementById('pp').innerHTML = 'here is pp';
document.getElementById('qq').innerHTML = 'here is qq';
}
The HTML:
<p style = 'whatever'>
<a id = 'pp'></a>
<a id = 'qq' style = 'color:red; text-decoration: underline;' ></a>
</p>
<script>
test()
</script>
This works with or without a wrapper like <p>.

How can I show/hide divs dynamically (on KeyUp, iTunes style) using Javascript/jQuery and a text or search field with case insensitive

I set out on a journey to create an iTunes-like search using Javascript. I learned about jQuery, and with some help from people on StackOverflow, I was successful.
I've come back here to share with you a very simple way to create a dynamic hide/show list based on the user input.
Let's search!
The entirety of the tutorial code can be found here.
And a JSFiddle for it is here!
So good to see Nick was successful on this experiment. good job on learning how to do it :)
Just in case you haven't encountered this jquery plugin, you might want to take a look at it too it's called Quick search.
https://github.com/riklomas/quicksearch
And I've used it on numerous pages and it works like a charm. example:
http://fedmich.com/works/types-of-project.htm
First, create a simple Div Layout with some text in the divs and search bar above it.
<div class="search_bar">
<form><!--The Field from which to gather data-->
<input id="searchfield" type="text" onclick="value=''" value="Case Sensitive Search">
</form>
</div>
<!--Containers With Text-->
<div class="container">
<div class="container_of_hc">
<div class="horizontal_containers">Cat</div>
<div class="color">Black</div>
<div class="color">White</div>
<div class="color">Orange</div>
</div>
<div class="horizontal_containers">Dog</div>
<div class="horizontal_containers">Rat</div>
<div class="horizontal_containers">Zebra</div>
<div class="horizontal_containers">Wolf</div>
</div>
CSS:
.container {
width: 100%;
}
.horizontal_containers {
height:10%;
border: solid 3px #B30015;
font-size: 45px;
text-align: center;
}
Second, you will make a script utilizing jQuery. Remember the title says this is a Dynamic Search, meaning (for us) we want to update the search with each key typed:
$("#searchfield").keyup(function() {
Note: Need a selector refresher?
Then we will set a variable to the value in #searchfield:
var str = $("#searchfield").val(); //get current value of id=searchfield
To ensure we show all the divs in our list when there is nothing in the searchfield we create an if statement based on the length of our new variable (str):
if (str.length == 0) {
//if searchfield is empty, show all
$(".horizontal_containers").show();
}
Last, we do the actual hiding of the divs if the length of str is not 0:
else {
//if input contains matching string, show div
//if input does not contain matching string, hide div
$("div:contains('" + str + "').horizontal_containers").show();
$("div:not(:contains('" + str + "')).horizontal_containers").hide();
}
});
The div:contains() and div:not(:contains()) statements are what set the conditions. It's essentially an if statement. They search the text contained within the div, not the div attributes. If you want to search a deeper div structure you can use more than one selector in the script's jQuery statements like so:
if (str.length == 0) {
//if searchfield is empty, show all
$(".container .color").show();
} else {
//if input contains matching string, show div
//if input does not contain matching string, hide div
$(".container div:contains('" + str + "').color").show();
$(".container div:not(:contains('" + str + "')).color").hide();
}
Replace the script statement you already have to give it a try.
Note: The nesting structure of your divs must match that in your selector.
And that's essentially it. If you have tips to improve this, know how to change it to a case insensitive search, or anything else you can think of, please let me know!
Thanks to MrXenoType I have learned case insensitivity for the :contains function.
To create a case insensitive search for this project simply add:
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
This creates a pseudo for the contains function. Place this code above your other script (within the same script) to make true for only this script.
Try:
$.expr[":"].contains_nocase = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
for adding a :contains_nocase() selector with jQuery 1.8

Categories