JavaScript substr on jQuery html() of a JavaScript variable - javascript

What I'm trying to ask is that when I take on a .each loop in jQuery using a build of a string by this:
$('.list :checkbox').each(function()
{
var type = $(this).attr('value');
Build += type + ', ';
return Build;
});
But now I need to remove the last "," (without quotes) since it makes a list like this:
Item 1, Item 2, Item 3, Item 4, Item 5,
Then it has to be added to the html() function which works well, but when trying to remove the last "," doesn't work by doing this:
Build.substr(-1);
$('#list-box').html(Build);
But that won't work.

You could simplify your code with something like this:
(updated)
var arr = $(":checkbox").map(function() {
return this.value;
}).get();
$('#list-box').html(arr.join(","));
Try it here: http://jsfiddle.net/andrewwhitaker/rXB2K/ (also updated)
Uses the map() function to translate the jquery results array to an array of checkbox values.
Calls join(), separating each value with a comma.

#YouBook: Try
Build.substr(0, Build.length - 1);
instead.

Have you tried using substring instead of substr? e.g.
Build.substring(Build.length - 1);

Build = Build.slice(0,-1);
works?

Instead this:
return Build;
write this:
return Build.substr(0, Build.length-1);

Don't use initial caps for variables.
Also, Strings are immutable in JS, so it's
build = build.substring(0, b.length-1)
This is a general purpose function called join in most languages, you should break it out as a utility function.
You should take into account the possibility of a zero length list.

Related

Array to Newline String to Array again through HTML

I have an array that comes in from from my API that I would like to arrange in a way that is better for the user (namely, in a column as opposed to the typical comma separated printed array).
This is my JS Fiddle to give a clearer picture: https://jsfiddle.net/2z89owas/
My question is, how can I get output3 to display just like output (and maintain its status as an iterable array like it was as dates)?
First you should not be using value for an html element. You can use .value for extracting value from inputs. Change your line to:
var val = document.getElementById('output2').innerHTML;
Afterwards, you have to split the same way you did join.
var dates3 = val.split('<br>');
document.getElementById('output3').innerHTML = dates3;
You can directly use join, something like:
document.getElementById('output3').innerHTML = dates.join(',');
You can try mapping over the contents of dates instead, as so:
let datesElem = dates.map(date =>`<p>${date}</p>`);
// test: console.log(datesElem)
document.getElementById('output3').innerHTML = datesElem

Using Jquery to get numeric value which is in between "/" in link

I am trying to fetch numeric value from link like this.
Example link
/produkt/114664/bergans-of-norway-airojohka-jakke-herre
So I need to fetch 114664.
I have used following jquery code
jQuery(document).ready(function($) {
var outputv = $('.-thumbnail a').map(function() {
return this.href.replace(/[^\d]/g, '');
}).get();
console.log( outputv );
});
https://jsfiddle.net/a2qL5oyp/1/
The issue I am facing is that in some cases I have urls like this
/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre
Here I have "3" inside text string, so in my code I am actually getting the output as "11466433" But I only need 114664
So is there any possibility i can get numeric values only after /produkt/ ?
If you know that the path structure of your link will always be like in your question, it's safe to do this:
var path = '/produkt/114664/bergans-of-norway-airojohka-jakke-herre';
var id = path.split('/')[2];
This splits the string up by '/' into an array, where you can easily reference your desired value from there.
If you want the numerical part after /produkt/ (without limitiation where that might be...) use a regular expression, match against the string:
var str = '/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre';
alert(str.match(/\/produkt\/(\d+)/)[1])
(Note: In the real code you need to make sure .match() returned a valid array before accessing [1])

jQuery equivalent to "getElementsByName"

What is the correct jquery syntax for a getElementsByName call?
Here is my javascript code:
var test = document.getElementsByName(tableName)[0];
using this is returning a different value:
var test = $("[name=tableName]");
Thanks in advance
Use quotes around the attribute selector:
$('[name="somenamehere"]');
If you need to use a variable within a selector, you need to use string concatenation to get the value of the variable:
$('[name="' + tableName + '"]');
Typically one should avoid using the [name] attribute in favor of the [id] attribute, because selection would be simpler as:
$('#someidhere');
-or-
$('#' + tableID);
Remove the index from the first statement
These are equal.
var test = document.getElementsByName(tableName);
var test = $("[name=tableName]");
"[name=tableName]" is bad syntax in 2 ways. First, you should put your name in quotes, so it should be "[name='tableName']" and second, in the first case, you're using a variable and in the second, a string, so in reality it shoudl be "[name='" + tableName + "']"
good call also on the fact that you have an index on your getelementsbyname() call, if you select item [0] then it will only return one item.
Interesting to know that jquery is a LOT slower than the native method here.
See the jsPrefs test : http://jsperf.com/getelementsbyname-vs-jquery-selektor/4
if you want to get a element value use this code:
var test1 = $("[name='tableName']").val();
alert(test1);
These are equal to get value of specific index[]:
For same index [0]
var test2 = $("[name='arryname[]']")[0];
alert(test2.value);
var test3 = $("[name='arryname[]']").get([0]);
alert(test3.value);

How to make a foldl on the values returned by a selector in jQuery?

Say I have some HTML elements:
<div>First</div>
<div>Second</div>
<div>Third</div>
Whose content I select via a:
$('div').text();
How can I make a "foldl" operation on the elements (iterate, accumulating a result), for example to join them using a newline?
$('div').text().foldl('', function(){ ... join_or_whatever ... })
According to the Wikipedia article on folding, JavaScript's Array.reduce() (for foldl) and Array.reduceRight() (for foldr) functions provide array folding.
So your specific task becomes:
var result = $.makeArray($('div')).reduce(function(prev,curr){
return prev + '\n' + $(curr).text()
});
Note that not all implementations of JavaScript support reduce and reduceRight, so see this example implementation if needed.
UPDATED: Since jQuery doesn't return a true array for $(selector) and some platforms do not support reduce and reduceRight on jQuery's "array-like" collection, I've updated the answer to use $.makeArray() as suggested below. Thanks to #royas for the catch.
I'm not sure what foldl is but
here's how you iterate and concatenate:
var newArray = [];
//'div' is an outer container of your inner divs
$('div').each(function(index, Element) {
newArray.push($(this).text());
});
$('body').append(newArray.join(''));
I think I understand what you mean by "foldl", not sure...
But try this:
var finalStr = "";
$('div').each(function(index) {
finalStr += $(this).text() + "<br>";
});
Available at: http://api.jquery.com/each/

Javascript Regex and getElementByID

I'm trying to search for all elements in a web page with a certain regex pattern.
I'm failing to understand how to utilize Javascript's regex object for this task. My plan was to collect all elements with a jQuery selector
$('div[id*="Prefix_"]');
Then further match the element ID in the collection with this
var pattern = /Prefix_/ + [0 - 9]+ + /_Suffix$/;
//Then somehow match it.
//If successful, modify the element in some way, then move onto next element.
An example ID would be "Prefix_25412_Suffix". Only the 5 digit number changes.
This looks terrible and probably doesn't work:
1) I'm not sure if I can store all of what jQuery's returned into a collection and then iterate through it. Is this possible?? If I could I could proceed with step two. But then...
2) What function would I be using for step 2? The regex examples all use String.match method. I don't believe something like element.id.match(); is valid?
Is there an elegant way to run through the elements identified with a specific regex and work with them?
Something in the vein of C#
foreach (element e in
ElementsCollectedFromIDRegexMatch) { //do stuff }
Just use the "filter" function:
$('div[id*=Prefix_]').filter(function() {
return /^Prefix_\d+_Suffix$/.test(this.id);
}).each(function() {
// whatever you need to do here
// "this" will refer to each element to be processed
});
Using what jQuery returns as a collection and iterating through it is, in fact, the fundamental point of the whole library, so yes you can do that.
edit — a comment makes me realize that the initial selector with the "id" test is probably not useful; you could just operate on all the <div> elements on the page to start with, and let your own filtering pluck out the ones you really want.
You can use filter function. i.e:
$('div[id*="Prefix_"]').filter(function(){
return this.id.match(/Prefix_\d+_Suffix/);
});
You could do something like
$('div[id*="Prefix_"]').each(function(){
if($(this).attr('id').search(/do your regex here/) != -1) {
//change the dom element here
}
});
You could try using the filter method, to do something like this...
var pattern = /Prefix_/ + [0 - 9]+ + /_Suffix$/;
$('div[id*="Prefix_"]').filter(function(index)
{
return $(this).attr("id").search(pattern) != -1;
}
);
... and return a jQuery collection that contains all (if any) of the elements which match your spec.
Can't be sure of the exact syntax, off the top of my head, but this should at least point you in the right direction

Categories