I have below function:
$(".import-shipments").on("click", function(){
var sendinger = $('#shipments').val().split("/\n/");
for(var i = 0; i < sendinger.length; i++){
console.log(sendinger[i]); //This returns 3 lines
addRow(i,"#rows") //It only adds 1 line
}
});
Which takes the values in my textarea, and count each value per line.
I then have below function, which should append a new "row", for each value:
function addRow(id, element){
var row = '<div class="row">'+
'<div>#'+id+'</div>'
'</div>';
$(element).append(row);
}
The problem is, that above only appends one row, when it should append 3.
Please see this jsFiddle for an example on how above works.
What I want to do is, for each line in the text area, it should also run the addRow() function for each line.
You are using wrong argument in split function. You are mixing regex and string here. which returns only one element in seninger array. it should be:
var sendinger = $('#shipments').val().split(/\n/); //USING Regex
or
var sendinger = $('#shipments').val().split("\n"); //USING String
Working Demo
Related
I have this function that I am trying to figure out/fix and can't seem to pinpoint the issue / can't figure out a way to get it working.
Basically my CMS is spitting certain hrefs that I would like to:
Part 1) change the targeted href URL
Part 2) change the button's text
Right now I only have 2 instances of this type of button, so here's what is printing out in my console:
Part 1) for this part I get the correct urls without the characters i want to strip out.
Part 2) two instances of the button's text (See All) followed by the correct variable of btnParent for the first button and then the second button and finally one instance of "Products".
My issue is, I can't figure out how to:
Part 1) send back the stripped URL to its respective button's href as an each function.
Part 2) Have the each() function print out the new text as "See All + BLAH + Products" for each instance, and then append the new text to the respective button.
Here is the code:
function viewMoreBtn() {
var btnMain = $("li:contains('See All')");
var btnText = $("li:contains('See All')").text();
var btnParent = $("li:contains('See All')").parent('ul').prev('li').text();
// PART 1 - STRIP LINK URL OF -_-// CHARACTERS
$.each(btnMain, function(i, v) {
v = $(this).find('a').attr('href').replace('-_-//', '');
console.log(v);
});
// PART 2 - ADD LABEL TO HTML TEXT OF BTN
$.each(btnMain, function(index, value) {
value = (btnText + btnParent + 'Products');
$(btnMain).text(value);
console.log(value);
});
}
viewMoreBtn();
Thank you.
jQuery objects, as return by $(...) have a each method already on them. The element is passed as the this context. You could use that further with jQuery to act on the objects in an scoped context. Basically, you have the right code, just in the wrong scope.
Part 1
btnMain.each(function() {
var $li = $(this);
var $a = $li.find('a');
var desiredUrl = $a.attr('href').replace('-_-//', '');
$a.attr('href', desiredUrl);
});
Part 2
btnMain.each(function() {
var $li = $(this);
var btnText = $li.text();
varbtnParent = $li.parent('ul').prev('li').text();
value = (btnText + btnParent + 'Products');
console.log(value);
$li.find('a').text(value);
});
See #Zequ's answer for the iteration over the each() function in the returned btnMain.
This is how $.each( obj, function( key, value ) works: you iterate over btnMain, and for each iteration of $.each(), the function assigns the index of the iteration to i and the value of btnMain at that index to v.
$.each(btnMain, function(i, v) {
//v = $(this).find('a').attr('href').replace('-_-//', '');
console.log(i); // I am the index of $.each() iterator
console.log(v); // I am the node from the btnMain array
// I don't know if this is right without seeing your HTML, but it seems like what you want
v.find('a').attr('href').replace('-_-//', '');
});
The second $.each() follows the same pattern.
If I understood correctly, you're confusing your variables.
$.each is a function for each element of the array/object being passed. It gives you a index and the element, check the reference
In part 1, you're defining v as the string you want, you're not changing the element at all,you need something like this:
$.each(btnMain, function() {
// you're saying you got the correct URLs, so the only thing you need to do is to change the element afterwards
var element = $(this).find('a');
v = element.attr('href').replace('-_-//', '');
element.attr('href', v);
});`
Also you could use btnMain.each instead of $.each
In part 2, you are changing the value variable (it's actually the element you're iterating over), to the string you want, then you follow it by trying to change btnMain's text. This is wrong, from what I understood, btnMain is an array of two elements you can't change it's text. You should change the element's value (that you are calling value). It would be something like that
$.each(btnMain, function(index, element){
// I think this is the time you want to define the btnParent, relative to the element
var btnParent = element.parent('ul').prev('li').text();
var value = (btnText + btnParent + 'Products');
element.text(value);
}
I THINK this is what you need.
Also you could append both parts into one, since both are iterating over btnMain
I am trying to open the 5 urls inputted by the user in the textarea
But the array is not taking the url separately instead taking them altogether:
function loadUrls()
{
var myurl=new Array();
for(var i=0;i<5;i++)
{
myurl[i] = document.getElementById("urls").value.split('\n');
window.open(myurl[i]);
}
}
You only should need to split the text contents once. Then iterate over each item in that array. I think what you want is:
function loadUrls() {
var myurls = document.getElementById("urls").value.split('\n');
for(var i=0; i<myurls.length; i++) {
window.open(myurls[i]);
}
}
Here's a working example:
var input = document.getElementById('urls');
var button = document.getElementById('open');
button.addEventListener('click', function() {
var urls = input.value.split('\n');
urls.forEach(function(url){
window.open(url);
});
});
<button id="open">Open URLs</button>
<textarea id="urls"></textarea>
Note that nowadays browsers take extra steps to block popups. Look into developer console for errors.
There are a couple issues I see with this.
You are declaring a new Array and then adding values by iterating through 5 times. What happens if they put in more than 5? Or less?
split returns a list already of the split items. So if you have a String: this is a test, and split it by spaces it will return: [this, is, a, test]. There for you don't need to split the items and manually add them to a new list.
I would suggest doing something like:
var myUrls = document.getElementById("urls").value.split('\n');
for (var i = 0; i < myUrls.length; i++) {
window.open(myUrls[i]);
}
However, as others suggested, why not just use multiple inputs instead of a text area? It would be easier to work with and probably be more user friendly.
Basically:
document.getElementById("urls").value.split('\n');
returns an array with each line from textarea. To get the first line you must declare [0] after split the function because it will return the first item in Array, as split will be returning an Array with each line from textarea.
document.getElementById("urls").value.split('\n')[0];
Your function could simplify to:
function loadUrls(){
var MyURL = document.getElementById("urls").value.split('\n');//The lines
for(var i=0, Length = MyURL.length; Length > i; i++)
//Loop from 0 to length of URLs
window.open(
MyURL[i]//Open URL in array by current loop position (i)
)
}
Example:
line_1...
line_2...
... To:
["line_1","line_2"]
I am trying to figure out how to get each value within my div. I am using
var cart = $('.basic-cart-cart-node-title.cell').text();
It is giving the results of OI-01OP-01OS-10-5SOR-04OR-05
I need to view them one by one: OI-01, OP-01, OS-10-5S, OR-04 OR-05.
So that I can match them against another field.
If you care to help me further, I have another div on the page:
var ParNum = $('.assess-title').text();
I would like to compare the values returned from the var cart and see if that value is in the ParNum. If it is there, I would like to apply a class.
Any help would be greatly appreciated.
Thanks!
You can store the values in an array using .map() method:
var values = $('.basic-cart-cart-node-title.cell').map(function() {
return $.trim( $(this).text() );
}).get();
For checking existence of the ParNum value in the array:
var does_exist = values.indexOf(ParNum) > -1;
Try this to iterate over elements:
var text = '';
$('.basic-cart-cart-node-title.cell').each(function (i, div) {
text += ' ' + $(div).text();
});
or this to get an array of matching div elements:
var divs = $('.basic-cart-cart-node-title.cell').toArray();
for (var i = 0; i < divs.length; i++) {
// $(div).text();
}
Reason for this is that $('.basic-cart-cart-node-title.cell') returns all div's at once, and you need to loop through the result. More specifically, $(selector) returns a so-called "wrapped set". It can be used to access each matching element (as I've shown above) or it can be used to apply any other jQuery function to the whole set at once. More info here.
var text = "";
$('.basic-cart-cart-node-title.cell').each(function(){
text += $(this).text() + ", ";
});
// remove the last ", " from string
text = text.substr(0, text.length -2);
var cart = [];
$('.basic-cart-cart-node-title.cell').each(function {
cart.push($(this).text());
}
This performs the matching and class adding you mentioned in the question.
var ParNum = $('.assess-title').text();
$('basic-cart-cart-node-title.cell').each(function () {
if ($(this).text() == ParNum) {
$(this).addClass("someclass");
}
}
You should try using
var cart ='';
$('.basic-cart-cart-node-title'.find('.cell').each(function()
{
cart = cart + $(this).val();
});
Hope it works for you.
var cart = $('.basic-cart-cart-node-title.cell').text().match(/.{5}/g);
This will give you an array with items 5 chars long. Regexes arent very fast, but a loop might be slower
Or easier to read, and in a string with commas:
var cart = $('.basic-cart-cart-node-title.cell').text(); // get text
cart = cart.match(/.{1,5}/g); // split into 5 char long pieces
cart = cart.join(",",); join on comma
I want to count the number of specific cars and output the cars,
I can count the number of saabs, but when i try to out the 2 saab cars i am getting "sa"
updated
<!DOCTYPE html>
<html>
<body>
<script>
cars=["BMW","Volvo","Saab","Ford","Saab"];
var count=0;
var totalSuccessArray= new Array();
for (var i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
if(cars[i]=="Saab") {
totalSuccessArray.push(cars[i]);
count++;
}
}
alert(count);
document.write(count + "<br>");
for (var a=0;a<count;a++) {
document.write("totalssuccess"+totalSuccessArray[a] + "<br>");
}
</body>
</html>
In your first for loop, you set totalSuccessArray to "Saab" (the value held in cars[i]).
This means that when you come to reference totalSuccessArray[a] in your second for loop, its value is a string. A string is an array of characters, so what this second for loop does is output the first two elements of "Saab" i.e. the characters "S" and "a".
You need to change the line
totalSuccessArray = cars[i];
to
totalSuccessArray.push(cars[i]);
So that you add the value "Saab" to the existing totalSuccessArray array.
In addition to this, you should also move the declaration of totalSuccessArray to the top of your code, outside the for loop.
There are a number of other optimisations you could also make to this code but that's outside the scope of the specific question.
Try moving your totalSuccessArray definition outside your for loop and then push()ing the elements onto it like this:
cars=["BMW","Volvo","Saab","Ford","Saab"];
var count=0;
var totalSuccessArray= new Array();
for (var i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
if(cars[i]=="Saab") {
totalSuccessArray.push(cars[i]);
count++;
}
}
In your original code, you're recreating the totalSuccessArray every time. In addition, the value you're setting the totalSuccessArray to is a string, instead of pushing the string into the array.
You are changing totalSuccessArray to a string, and then iterating over the letters in it. The brackets used on a string returns the character at that position. I think what you meant to do was add the new car to the array:
cars=["BMW","Volvo","Saab","Ford","Saab"];
var count=0;
var totalSuccessArray= new Array();
for (var i=0;i<cars.length;i++) {
document.write(cars[i] + "<br>");
if(cars[i]=="Saab") {
totalSuccessArray[count] = cars[i];
count++;
}
}
I am attempting to print out lables (bar codes) from a table using JS (the table is using JQ Tablesorter) and the barcode jquery. My issue is that I need to iterate through all of the isbn's and it is showing one number per line. Here is the code I have:
$("#barcode").live('click', function(){
var title="";
var isbn="";
var first = "";
var second = "";
var indexGlobal = 0;
$('#acctRecords tbody tr').each(function()
{
isbn += $(this).find('#tableISBN').html();
title += $(this).find('#tableTitle').html();
}); //end of acctRecords tbody function
//Print the bar codes
var x=0;
for (x=0;x<isbn.length;x++)
{
first += '$("#'+indexGlobal+'").barcode("'+isbn[x]+'", "codabar",{barHeight:40, fontSize:30, output:"bmp"});';
second += '<div class="wrapper"><div id="'+indexGlobal+'"></div><div class="fullSKU">      '+isbn[x]+
'</div><br/><div class="title">'+title[x]+'</div></div><br/><br/>';
indexGlobal++;
}
var barcode = window.open('','BarcodeWindow','width=400');
var html = '<html><head><title>Barcode</title><style type="text/css">'+
'.page-break{display:block; page-break-before:always; }'+
'body{width: 8.25in;-moz-column-count:2; -webkit-column-count:2;column-count:2;}'+
'.wrapper{height: 2.5in;margin-left:10px;margin-top:5px;margin-right:5px;}'+
'.fullSKU{float: left;}'+
'.shortSKU{float: right;font-size:25px;font-weight:bold;}'+
'.title{float: left;}'+
'</style><script type="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.js"></script><script type="text/javascript" src="../barcode/jquery-barcode.js"></script><script>$(document).ready(function() {'+first+'window.print();window.close();});</script></head><body>'+second+'</body></html>';
barcode.document.open();
barcode.document.write(html);
barcode.document.close();
}); // end of click function
I am pretty sure that the issue is with these lines:
var x=0;
for (x=0;x<isbn.length;x++)
For example if an isbn is 9780596515898 I am getting 9 on the first line, 7 on the second, 8 on the third etc.
How do I get it to print out the entire isbn on one line?
Nope, those 2 lines are fine. But these 2, on the other hand...
var isbn="";
...
isbn += $(this).find('#tableISBN').html();
This makes isbn a string. And you are just making the string longer every time you add an isbn to it. "string".length will tell you the number of characters in that string, which is why you get one character per iteration.
You want an array instead, which you append items to with the [].push() method. [].length will tell you the number of items in that array.
var isbn = [];
...
isbn.push($(this).find('#tableISBN').html());
for (var x=0; x<isbn.length; x++) {
isbn[x]; // one isbn
}