Obtain a substring of a string using jQuery - javascript

I have a div with the following classes:
form-group val-presence-text val-type-pos-int val-length-10 has-success has-feedback
I want to get the 10 from the val-length-10 class name. I've tried various methods, but none seem to work for a dynamic multi-class attribute such as this. In addition, the 10 could be any positive integer and the class could be located anywhere within the group of classes.
Any ideas?

You can use this:
var val_length = $('div').attr("class").match(/val-length-(\d+)/)[1];

One possible solution:
var n = (this.className.match(/val-length-(\d+)/) || []).pop();
Or in the context:
$('[class*="val-length-"]').each(function() {
var n = (this.className.match(/val-length-(\d+)/) || []).pop();
console.log(n);
});

Assuming that the it is 'val-length' that never changes and just the integer on the end of it, you should be able to do this:
//get an array of classes on a specific element
var classList =$('#elementId').attr('class').split(/\s+/);
//loop through them all
$.each( classList, function(index, item){
//check if any of those classes begin with val-length-
if (item.indexOf('val-length' === 0) {
console.log(item.substring(11))
}
});

Try this...
$("div[class*=val-length-]").each(function() {
var s = this.className;
var length = 0;
$(s.split(" ")).each(function() {
if (this.search("val-length-") === 0) {
length = this.substr(11);
}
});
console.log(length);
});
It will find the relevant div and pull the value for you.

Related

Get length of longest String in Array

i need to find out the longest string of an array. First of all i push different "text" elements into my array, since the stringe and amount of those "text" elements can differ from case to case. (they are lables of an chart and thus are generated based on the charts sections.
my code right now looks like this:
var textLengthArray = [];
domContainer.find(" g > .brm-y-direction > .tick > text").each(function () {
textLengthArray.push($(this));
});
var lgth = 0;
var longestString;
for (var i = 0; i < textLengthArray.length; i++) {
if (textLengthArray[i].length > lgth) {
var lgth = textLengthArray[i].length;
longestString = textLengthArray[i];
}
}
It already pushes all text elements into my array. But when i use
alert(longestString.length)
i allway get "1" as a result. I am pretty shure i have to add .text anywhere before .length, since the code does not check die textlength of the textelements.
Since i am quite new to javascript i would highly appreciate some help.
Thanks in advance!
textLengthArray.push($(this)); should be textLengthArray.push($(this).text()); otherwise your array consists of jQuery objects. And indeed jQuerySet has length property. And in your case the set consists of 1 element.
You are re-declaring lgth in each iteration of the array which is re-assigning the value.
Replace var lgth = textLengthArray[i].length with lgth = textLengthArray[i].length and you should be good.
I don't know about the rest of your code, looks fine. But you're pushing a jQuery object$(this), not a string. Line three should read textLengthArray.push(this);.
Apparently one of the strings your pushing is a valid jQuery selector that finds an element :-)
No need to create a separate array. Just iterate objects and update as you go:
longest = "";
$('div').each(function() {
var t = $(this).text();
if(t.length > longest.length)
longest = t;
});
alert(longest)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>hello</div>
<div>wonderful</div>
<div>world</div>
To get the longest string from any array, try reduce:
a = ['hello', 'wonderful', 'world']
longest = a.reduce(function(prev, e) {
return prev.length >= e.length ? prev : e;
});
alert(longest)
Sort the array by length and get the first element. Hope it works for you
stackoverflow.com/questions/10630766/sort-an-array-based-on-the-length-of-each-element

How can I modify my code to select specific checkboxes?

I want to write a simple javascript script to select from a large list of checkbox items on a website. Lets say I want to select the 3rd, 12th, and 25th checkbox. How would I do that? Right now it selects every item.
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
$("#detail input:checkbox").click();
I would use filter() and prop()
var indexesToCheck = [2,11,24];
$("#detail input:checkbox").filter(function(index){
return $.inArray( index, indexesToCheck ) > -1;
/* OR something like*/
return $(this).hasClass('someClass');
}).prop('checked',true);
Since it's not clear how you intend to determine which ones get checked I used a simple array. You could aslo check classes or any other element attributes inside filter using this which would be the instance of each element
References:
filter() docs
prop() docs
I will provide a solution in javascript and equivalent jQuery. I added a last solution (my favourite), which would generic, creating a custom pseudo selector.
For javascript, I chose all the inputs and verify their type. Incrementing a counter when the type is checkbox. Then I compare with an array of the indexes I want to select and I push the element to the final array with all my elements (mySelection):
var mySelection = [];
var checkboxIndexes = [3,12,25];
var checkCounter = 0;
var allInputs = document.getElementsByTagName("input");
for(var i=0;i<allInputs.length;i++) {
if (allInputs[i].type == 'checkbox') {
if(checkboxIndexes.indexOf(checkCounter) > -1;)
mySelection.push(allInputs[i]);
checkCounter++;
}
};
For the jQuery you could use:
$('#detail input:checkbox:eq(index)');
But I did an equivalent to the javascript one using filter. I personally like more this solution since you can put all the index to be selected in one array:
var checkboxIndexes = [3, 12, 25];
var mySelection = $("#detail input:checkbox").filter(function(index) {
return checkboxIndexes.indexOf(index) > -1;
});
The last solution would be a generic solution which will allow to create a custom pseudo selector that I called "multieq". The goal is to use "multieq" as a filter directly from the selector in this way:
var mySelection = $("input:checkbox:multieq(3, 12, 25)");
And this is the code I used in order to create that pseudo selector:
$.expr[':'].multieq = $.expr.createPseudo ?
$.expr.createPseudo(function(match) {
var checkboxIndexes=match.split(',');
for(var i=0; i<checkboxIndexes.length;i++) checkboxIndexes[i] = parseInt(checkboxIndexes[i], 10);
var index=-1;
return function( elem, doc, isXML ) {
index++;
return checkboxIndexes.indexOf(index) > -1;
};
}) :
function( elem, index, match ) {
var checkboxIndexes=match[3].split(',');
for(var i=0; i<checkboxIndexes.length;i++) checkboxIndexes[i] = parseInt(checkboxIndexes[i], 10);
return checkboxIndexes.indexOf(index) > -1;
};
//Now we can use this:
var mySelection = $("input:checkbox:multieq(3, 12, 25)");
Since 1.8+ $.expr breaks for certain cases and it is not including the param index, it is recommended to use createPseudo(), that is why there is a fallback function for jQuery version under 1.8. createPseudo, does not include index neither but allow us to create the index (as a counter).
I hope it helps!
<input type="checkbox" name="multi_selection"/>
var idArr = [];
$.each($("input[name='multi_selection']:checked"), function(){
idArr.push($(this).val());
});
Now idArr is the array of the selected checkboxes... alert(idArr)

Better way to create arrays in javascript?

I'm trying to create an array in Javascript with a size that is equivalent to the number of times a certain class is found in the DOM, and then iterate through it to grab the text from an input field present in that class. I can easily do this like so:
var count = 0;
$('.className').each(function() {
count++;
});
var classes = new Array(count);
count = 0;
$('.className input[type=text]').each(function() {
classes[count++] = $(this).val();
});
This looks like a lot of code for what seems to be a relatively simple task. Is there a more efficient or less lengthy way of doing this?
Thanks
It looks like you want this :
var classes = $('.className input[type=text]').map(function(){
return this.value
}).get();
But it's a guess : it's not clear why you start by counting all elements of the class and then iterate on the inputs.
You can construct an array of elements directly from your selector via the makeArray function, then transform the result using a map.
var classes = $.makeArray($('.className input[type=text]')).map(function() {
return $(this).val();
});
Use jQuery's map function, then get if you need a pure array:
var values = $('.className input[type=text]').map(function() {
return $(this).val();
}).get();
each passes the index, so you don't need to do it yourself:
var classes = [];
$('.className input[type=text]').each(function(index, value) {
classes[index] = $(this).val();
});
Arrays are dynamic and therefore don't need to be initialized. Create a new array, loop through the inputs and push the values to the new array:
var classes = [];
$('.className input[type=text]').each(function(idx, elem) {
classes.push($(elem).val());
});

I want to get part of the class of a clicked element in jQuery

So, I have a function like this:
$('a.tdt-btn-*').click(function() {
var class = $(this + "[class^=tdt-btn-*]"); // Need more here
console.log(class);
});
What I want to do is get the value of the wildcard part at the end. How could I do this?
I'd suggest:
$('a[class*=tdt-btn-]').click(function() {
var elClasses = this.className.split(/\s+/),
elClassWildcard;
for (var i = 0, len = elClasses.length; i < len; i++){
if (elClasses[i].indexOf('tdt-btn-') === 0) {
elClassWildcard = elClasses[i].replace('tdt-btn-', '');
}
}
console.log(elClassWildcard);
});
JS Fiddle demo.
Incidentally, class is a reserved word in JavaScript and should, or can, not be used as a variable name (I believe an error is thrown if you do so).
References:
Attribute contains (attribute*=value) selector.
String.indexOf().
String.split().
Only one class:
Try this (class is a reserved word, so I'm using clazz):
$('a[class^="tdt-btn-"]').click(function() {
var clazz = $(this).attr('class').replace('tdt-btn-','')
console.log(clazz);
});
Demo fiddle
Multiple CSS classes:
It will take the first occurrence of the tdt-btn-*.
$('a[class*="tdt-btn-"]').click(function() {
var clazz = $(this).attr('class').match(/(tdt-btn-)(.+?)(?=(\s|$))/)[2];
console.log(clazz);
});
Demo fiddle

Is there a way to loop through all fields in a fieldset?

I would like to change the class for all the fields in a specific fieldset.
Is there a way to loop through the fields in a fieldset?
You can use getElementsByTagName.
var fieldset= document.getElementById('something');
var fieldtags= ['input', 'textarea', 'select', 'button'];
for (var tagi= fieldtags.length; tagi-->0) {
var fields= fieldset.getElementsByTagName(fieldtags[tagi]);
for (var fieldi= fields.length; fieldi-->0;) {
fields[fieldi].className= 'hello';
}
}
(If you only care about input fields, you could lose the outer tag loop.)
If you needed them in document order (rather than grouped by tag) you'd have to walk over the elements manually, which will be a pain and a bit slow. You could use fieldset.querySelectorAll('input, textarea, select, button'), but not all browsers support that yet. (In particular, IE6-7 predate it.)
Using jQuery (yay!):
$('#fieldset-id :input').each(function(index,element) {
//element is the specific field:
$(element).doSomething();
});
Note the solution below is for NON-JQUERY Implementations.
Implement a getElementsByClassName Method like this:
After you implement the code below you can then use document.getElementsByClassName("elementsInFieldSetClass") it will return an array of the elements with that class.
function initializeGetElementsByClassName ()
{
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
}
window.onload = function () {
initializeGetElementsByClassName();
};
Another jQuery solution here.
If you are simply adding a class(es) to the elements, it's this simple:
$('fieldset :input').addClass('newClass');
.addClass() (like many other jQuery functions) will work on all of the elements that match the selector.
Example: http://jsfiddle.net/HANSG/8/
Permanently? Find & replace in your editor of choice.
When the user clicks something? jQuery way:
$('fieldset <selector>').each(function() {
$(this).removeClass('old').addClass('new');
});

Categories