Alert class based on it's length with Javascript/jQuery - javascript

So basically I'm trying to select the class "on" only, but based on the class length of 2.
<div class="film cars-0317219 on"></div>
<div class="film wall-e-0910970 on"></div>
<div class="film off up-0945232"></div>
<div class="film on finding-nemo-0266543"></div>
<div class="film off cars-0317219"></div>
Something like:
$('div.film').live('click', function(){
var classes=$(this).attr("class").split(" ");
var status=classes[classes.length=2];
alert(status);
});
Should alert "on"
Any idea how to get the alert based on the string length? (Likewise, if I put 3 instead of 2 in the code, it should alert "off")

var status=classes[1]; // the second element of the array
Better way to do what you want to do:
var isOn=$('.film').hasClass('on');
alert(isOn?'on':'off');
Remember that $('.film') will only get the 1st element with that class when perform these types of operations unless this is in a handler like click in which case you would use $(this)

You should do:
alert(classes[1]);
arrays in javascript are zero based and so the second element has an index of 1 (and the third element has an index of 2)
EDIT - now i understand the OP means the length of the word on (2 letters):
var classes=$(this).attr("class").split(" ");
for (i = 0; i<classes.length; i++){
if (classes[i].length ===2){
alert(classes[i]);
}
}

If you want to alert only classes of a certain length, you can proceed like this
a=['film', 'cars-0317219', 'on'];//same as your var classes;
var status = a.filter(function(x){
return x.length==this.size;
},{size:2});//contains ['on']
However filter is implemented for firefox, I don't know for other browsers.

function something(){
var classSplitOn =" ";
var desiredCount = 2;
var onClassSelector = ".on";
$('.film').each(function(index,elem){
var classString = elem.className;
if(classString && classString.split(classSplitOn).length == desiredCount){
var alertVal = "off";
if($(this).is(onClassSelector)){
alertVal = "on";
}
alert(alertVal);
}
});
}

Related

Update href text value dynamically using JQuery

There are href links on the page, its text is not complete. for example page is showing link text as "link1" however the correct text should be like "link1 - Module33". Both page and actual texts starts with same text (in this example both will starts with "link1").
I am getting actual text from JSON object from java session and comparing. If JSON text starts with page text (that means JSON text "link1 - Module33" startsWith "link1" (page text), then update "link1" to "link1 - Module33".
Page has below code to show the links
<div class="display_links">
<ul id="accounts_links_container">
<li id="accounts_mb_2_id"><a href="javascript:void(0)" class="linksmall"
id="accounts_mb_2_a"> link1 </a></li>
<li id="accounts_mb_11_id"><a href="javascript:void(0)" class="linksmall"
id="accounts_mb_11_a"> link2 </a></li>
.
.
.
// more links
</ul>
</div>
Note : li id is not static its different for each page text, however ul id is static.
I am reading correct & full link text from JSON object (from java session) as below
var sessionValue = <%= json %>; // taken from String array
and reading page text as below :-
$('.display_links li').each(function() { pageValue.push($(this).text()) });
sessionValue has correct updated text and pageValue has partial texts. I am comparing using below code
for(var s=0; s<pageValue.length; s++) {
var pageLen = $.trim(pageValue[s]).length;
for(var w=0; w<sessionValue.length; w++) {
var sesstionLen = $.trim(sessionValue[w]).length;
var newV = sessionValue[w].substring(0, pageLen);
if($.trim(newV)==$.trim(pageValue[s])){
**// UPDATING VALUES AS BELOW**
pageValue[s]=sessionValue[w];
}
}
}
I am trying to update page value text to session value text as pageValue[s]=sessionValue[w]; (in above code) but its not actually updating the values. Sorry for the poor comparing text logic.
Please help, how to update it dynamically in the loop after comparing to make sure I am updating the correct link text.
pageValue[s]=sessionValue[w]; just updates the array; it has no effect whatsoever on the li's text.
If you want to update the li's text, you need to do that in your each. Here's an example doing that, and taking a slightly more efficient approach to the comparison:
$('.display_links li a').each(function() {
var $this = $(this);
var text = $.trim($this.text());
var textLen = text.length;
for (var w = 0; w < sessionValue.length; ++w) {
var sessionText = $.trim(sessionValue[w]);
if (sessionText.substring(0, textLen) == text) {
text = sessionText;
$this.text(text);
break; // Found it, so we stop
}
}
pageValue.push(text); // If you want it for something
});
I think it's cleaner to just select the elements you care about (in this case the anchor tags) and then use built-in functionality to compare rather than reimplementing a startsWith function.
var sessionValue = ['link1 - Module33', 'link2 - foobar'];
$('.display_links li a').each(function() {
var $this = $(this);
var text = $this.text().trim();
sessionValue.forEach(function(sessionValue) {
if (sessionValue.startsWith(text)) {
$this.text(sessionValue);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="display_links">
<ul id="accounts_links_container">
<li id="accounts_mb_2_id"> link1 </li>
<li id="accounts_mb_11_id"> link2 </li>
</ul>
</div>
The result of $(this).text() is a primitive string, not a reference to the textNode of the element. It doesn't matter if you update pageValue, because it is not related to the original element.
Instead of pushing the strings to an array to process, you can stay inside the $.each() loop and still have access to the elements, which is needed to update the text. Something like this:
$('.display_links li').each(function() {
var $li = $(this);
var liText = $.trim($li.text());
var liLen = liText.length;
for(var w = 0; w < sessionValue.length; w++) {
var sessionLen = $.trim(sessionValue[w]).length;
var newV = sessionValue[w].substring(0, liLen);
if ($.trim(newV) === liText) {
**// UPDATING VALUES AS BELOW**
$li.text(sessionValue[w]);
}
}
});
I am a noob and thought I would take a shot at this.
Here is my approach although the sessionValue array is a bit foggy to me. Is the length undetermined?
I declared var's outside of the loop for better performance so they are not declared over and over.
Iterate through elements passing each value through Compare function and returning the correct value and update immediately after all conditions are satisfied.
var i = 0;
$('.display_links li a').each(function(i) {
$(this).text(Compare($(this).text(), sessionValue[i]));
i++;
});
var Compare;
var update;
Compare = function(val1, val2) {
// Check if val1 does not equal val2 and see if val2 exists(both must be true) then update.
if(!val1 === val2 || val2) {
update = val2
}
return update;
}

Subtract number in span

I would like 5 left do -1 e.g. become 4 left.
HTML
<span class="small">5 left</span>
jQuery
// Store the 5 left in "numberStock" variable
var numberStock = parseInt($(".small:first").text());
// Subtract with "numberStock -1"
var minusStock = numberStock - 1;
// Here comes the issue, how do I add the new content?
$(".small:first").attr(minusStock "left");
Question
How do I add the new numberStock number 4 and text left?
A solution in plain Javascript
Array.prototype.forEach.call(document.getElementsByClassName('small'), function (a) {
a.innerHTML = a.innerHTML.replace(/\d+/, function (v) {
return v - 1;
});
});
<span class="small">5 left</span>
You can use replace:
// Store the 5 left in "numberStock" variable
var numberStock = parseInt($(".small:first").text());
// Subtract with "numberStock -1"
var minusStock = numberStock - 1;
console.log(minusStock);
// Here comes the issue, how do I add the new content?
var original = $(".small:first").text();
var toAdd = original.replace(original[0], minusStock);
$(".small:first").text(toAdd);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>
Use String#replace method with a callback function.
// use text method with callback where second
// argumnet is old text
$(".small:first").text(function(i, txt) {
// replace text with decremented value
return txt.replace(/\d+/, function(m) {
return m - 1;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>
UPDATE : With pure JavaSript do something like this.
// since you just want the first element use
// querySelector otherwise you need to use
// querySelectorAll and then need to iterate
// over them
var ele = document.querySelector(".small");
// update text content of span element
ele.textContent = ele.textContent.replace(/\d+/, function(m) {
return m - 1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>
i am not sure if i understood your question, but if i did here is a way to do it , which is pretty close to what you were trying to achieve
var numberStock = parseInt($('.small').text())
var minusStock = numberStock - 1;
$('.small').text(minusStock + ' left');
here is a fiddle in case you want to test around with it
https://jsfiddle.net/09wcjp7b/

Dynamical Calculator Javascript

It is a calculator which has spans from which I want to take a values(1,2,3, etc.) and two fields: First for displaying what user is typing and the second is for result of calculation.
The question how to get values so when I click on spans it will show it in the second field
Here is the code.
http://jsfiddle.net/ovesyan19/vb394983/2/
<span>(</span>
<span>)</span>
<span class="delete">←</span>
<span class="clear">C</span>
<span>7</span>
<span>8</span>
<span>9</span>
<span class="operator">÷</span>
....
JS:
var keys = document.querySelectorAll(".keys span");
keys.onclick = function(){
for (var i = 0; i < keys.length; i++) {
alert(keys[i].innerHTML);
};
}
var keys = document.querySelectorAll(".keys span");
for (var i = 0; i < keys.length; i++) {
keys[i].onclick = function(){
alert(this.innerHTML);
}
}
keys is a NodeList so you cannot attach the onclick on that. You need to attach it to each element in that list by doing the loop. To get the value you can then simple use this.innerHTML.
Fiddle
This should get you started.. you need to get the value of the span you are clicking and then append it into your result field. Lots more to get this calculator to work but this should get you pointed in the right direction.
Fiddle Update: http://jsfiddle.net/vb394983/3/
JavaScript (jQuery):
$(".keys").on("click","span",function(){
var clickedVal = $(this).text();
$(".display.result").append(clickedVal);
});
You can set a click event on the span elements if you use JQuery.
Eg:
$("span").click(
function(){
$("#calc").val($("#calc").val() + $(this).text());
});
See:
http://jsfiddle.net/vb394983/6/
That's just to answer your question but you should really give the numbers a class such as "valueSpan" and the operators a class such as "operatorSpan" and apply the events based on these classes so that the buttons behave as you'd expect a calculator to.
http://jsfiddle.net/vb394983/7/
var v="",
max_length=8,
register=document.getElementById("register");
// attach key events for numbers
var keys = document.querySelectorAll(".keys span");
for (var i = 0; l = keys.length, i < l; i++) {
keys[i].onclick = function(){
cal(this);
}
};
// magic display number and decimal, this formats like a cash register, modify for your own needs.
cal = function(e){
if (v.length === self.max_length) return;
v += e.innerHTML;
register.innerHTML = (parseInt(v) / 100).toFixed(2);
}
Using JQuery will make your life much easier:
$('.keys span').click(function() {
alert(this.innerHTML);
});

Determining a character of a sentence when clicked on

On a random break I found myself wondering if it would be possible to use jQuery to determine a single character within a sentence when it is clicked on.
For example:
This
When the user clicks on first h, jQuery would return this to me.
The only way I could think of doing this would be to wrap each character within the sentence in a span with a class of its letter such as the following example:
<span class="clickable T">T</span>
<span class="clickable h">h</span>
<span class="clickable i">i</span>
<span class="clickable s">s</span>
Followed by a $('.clickable').click(function()) that would return its second class.
My question is: is this the most efficient way to do this?
Obviously wrapping every single letter of the document in span tags is not efficient.
I was able to spin something up that works in Chrome at least. Basically, when you click on a letter, it then triggers a double clicks which selects the word. We get the selection which actually gives us the text of the entire target element. From that, we get the letter that was clicked. We remove the selection and do what we want with the letter.
Fiddle here
$(function(){
$(document).click(function(e){
var target = e.target;
$(target).dblclick();
}).dblclick(function(){
var selection,
node,
text,
start,
end,
letter;
if (window.getSelection) {
selection = document.getSelection();
node = selection.anchorNode;
if (node.nodeType === 3) {
text = node.data;
start = selection.baseOffset;
end = selection.extentOffet;
if (!isNaN(start)) {
letter = text.substr(start, 1);
}
}
window.getSelection().removeAllRanges()
} else if(document.selection) {
//continue work here
}
if (letter) {
alert(letter);
}
});
});
You could return the innerHTML as well with:
$('.clickable').on('click', function(){
alert($(this).html());
});
As for a more efficient way to do it...maybe try this:
in Javascript/jQuery, how to check a specific part of a string and determine if it is a whitespace or letter?
You can do it with this script
$('.clickable').on('click', function(){
var html = $(this).text(); // if you want the text inside the span
var index = $(this).index(); // if you want the position among siblings
var classes = $(this).attr('class').split(" ");
var secondClass = getSecondClass(classes);
});
function getSecondClass(classArray){
if(classArray.length<2){
return null;
}else{
return classArray[1];
}
}
I've also included the html and index variables if you want to do something else with the clicked element.
Basically you split the classes of the element by spaces and then check if the array has less than two elements, in that case it returns null, otherwise it returns the second element.
jsFiddle
Well wrapping all text dyanamically with span tag , it is possible what you were looking for
JS
$(function(){
var lengthText = $('#singlecharacter').text().length;
var textValue = $('#singlecharacter').text();
var textArray = textValue.split('');
var newText = new Array();
for (var i = lengthText - 1; i >= 0; i--) {
newText[i] = "<span class='sp'>"+textArray[i]+"</span>";
};
$('#singlecharacter').html(newText);
$('.sp').click(function()
{
alert($(this).text());
});
});
HTML
<div id='singlecharacter'>THIS</div>
DEMO JSFIDDLE

Java Script : get the string equivalent of a elements ID

my naming convention
id=xxxxx //actual field shown in the screen
id=xxxxxHDN // hidden field containing the enable/disabled status of the component from the set from the controller.
Now what I am trying to do is get the satus of xxxxxHDN to be true/false ,
and accordingly set the components status to disabled /enabled .with java script..
var div = document.getElementById("hiddenFields"); // i hava some 30 hidden fields containing the
var j;
for (j=0;j<div.childNodes.length;j++)
if(div.childNodes[j].value){
alert("inside the loop");
var someElementHDN = div.childNodes[j].id; // my aim is to get the ID=xxxxxHDN
var someElementHDNToString = someElementHDN .toString(); // my aim is to get the string value "xxxxxHDN"
var toRemove = 'HDN'; // the part i wanna remove from 'someElementHDNToString' to make it an id for 'xxxxx'
var equivalantComponentIDAsString = someElementToString.replace(toRemove,'');
$('#' + equivalantComponentIDAsString ).attr('disabled', true);
}
}
Invested a lot of time manupulatiing things above , doesent seems to work . I am new to java scrcript , Where am I missing it?
If you have an element with id like 'fooHDN' and want to find another element with id 'foo', then you can do something like:
var otherElement = document.getElementById(someElement.id.replace(/HDN$/,''));
Assuming that you already have someElement and it's a DOM element.
Your posted js code has error: div does not have a "length", do you mean "div.childNodes.length"?
Anyway, since you're using jQuery already, I think it can become easier as below:
Already tested and it works fine.
$("#hiddenFields input[type='hidden'][id$='HDN']").each(
function () {
var elemId = this.id.replace(/HDN$/, '');
$('#' + elemId).attr('disabled', this.value.toLowerCase() == 'false' ? false : true);
}
);

Categories

Resources