issue with javascript for loop not executing every time - javascript

I'm using this JavaScript code for alert count in an array of pages.
urls is an array of page names, and count is the count value.
I want to alert the count value in each pages of the array urls.
But the for loop is not executing all time. I don't know what happens... Any body please help me to find out the mistake..
Am using echo $_POST['suggest']; in the array of pages. But i want to use JavaScript code for receiving the value of suggest and alert it. How to receive the value using JavaScript?
<script>
$(document).ready(function () {
var count = document.getElementById('display_visitor_number').innerHTML; //count
var urls = document.getElementById('display_visitor_urls').innerHTML; //array of page names
var myarr = urls.split(",");
for (var i=1;i<myarr.length;i++)
{
$.post(myarr[i],{suggest:count}, function(data) {
alert(data);
});
}
});
</script>

if the string urls starts with , before you split it will have an empty string as first value (this will cause jquery to make an ajax call for the current page) you may want to check for that and start with 0
<script>
$(document).ready(function () {
var count = document.getElementById('display_visitor_number').innerHTML; //count
var urls = document.getElementById('display_visitor_urls').innerHTML; //array of page names
var myarr = urls.split(",");
for (var i=0;i<myarr.length;i++)
{
if(myarr[i] !== '')$.post(myarr[i],{suggest:count}, function(data) {
alert(data);
});
}
});
</script>

instead of using split function you'd better try RegExp and match all non-space character sequences. replace
var myarr = urls.split(",");
with
var myarr = urls.match(/[^ ,]+/g)
and you should start you for loop with var i=0 then.

Related

TypeError: 'undefined' is not an object in Javascript

I have a piece of Javascript code that assigns string of values to a string array.
Unfortunately if I try to add more than one string to the array, my UI simulator(which runs on JS code) closes unexpectedly. I have tried debugging but I cannot find anything. I am attaching that piece of code where the issue is. may be you guys could find some flaw? On the pop up button click the values I selcted on the UI should get stored in the array and I have a corressponding variable on the server side to handle this string array.
_popupButtonClick: function (button) {
var solutions = this._stateModel.get('solutionName');
var i;
var solutionsLength = solutions.length;
var selectedSolution = [solutionsLength];
this.clearPopupTimer();
if (button.position === StatusViewModel.ResponseType.Ok) {
for(i=0;i<solutionsLength;i++)
{
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
}
this._stateModel.save({
selectedsolutions: selectedSolution,
viewResponse: StatusViewModel.ResponseType.Ok
});
} else {
this._stateModel.save({
viewResponse: StatusViewModel.ResponseType.Cancel
});
}
}
Change
var selectedSolution = [solutionsLength];
to
var selectedSolution = [];
This makes your array have an extra item that might be causing a crash.
Also,
you have an
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
But no corresponding else, so your array has undefined values for i which are not entering the if.
Maybe adding an empty string might solve it:
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
else
{
selectedSolution[i] = "";
}
The code is looking fine but there seems to be a piece of code which can cause error. For example, you are assigning var selectedSolution = [solutionsLength]; and for example solutionsLength is 5 then your loop runs for 5 times
for(i=0;i<solutionsLength;i++) // runs for 5 times
{
if(this._list.listItems[i].selected)
{
// but selectedSolution = [5]; which is on 0th index and from 1st to 4th index it is undefined
selectedSolution[i] = this._list.listItems[i].options.value;
}
}
So you can try to use push() like
selectedSolution.push(this._list.listItems[i].options.value);
and on initialization change it like,
var selectedSolution = [];
Hopefully this will solve your problem.
var selectedSolution = [solutionsLength];
keeps the value in the selectedSolution variable.
var selectedSolution = [3];
selectedSolution[0] gives the values as 3
So make it simple
var selectedSolution = [];

How to remove all characters before specific character in array data

I have a comma-separated string being pulled into my application from a web service, which lists a user's roles. What I need to do with this string is turn it into an array, so I can then process it for my end result. I've successfully converted the string to an array with jQuery, which is goal #1. Goal #2, which I don't know how to do, is take the newly created array, and remove all characters before any array item that contains '/', including '/'.
I created a simple work-in-progress JSFiddle: https://jsfiddle.net/2Lfo4966/
The string I receive is the following:
ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC
ABCD/ in the string above can change, and may be XYZ, MNO, etc.
To convert to an array, I've done the following:
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
Using console.log, I get the following result:
["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"]
I'm now at the point where I need the code to look at each index of array, and if / exists, remove all characters before / including /.
I've searched for a solution, but the JS solutions I've found are for removing characters after a particular character, and are not quite what I need to get this done.
You can use a single for loop to go through the array, then split() the values by / and retrieve the last value of that resulting array using pop(). Try this:
for (var i = 0; i < currentUserRole.length; i++) {
var data = currentUserRole[i].split('/');
currentUserRole[i] = data.pop();
}
Example fiddle
The benefit of using pop() over an explicit index, eg [1], is that this code won't break if there are no or multiple slashes within the string.
You could go one step further and make this more succinct by using map():
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',').map(function(user) {
return user.split('/').pop();
});
console.log(currentUserRole);
You can loop through the array and perform this string replace:
currentUserRole.forEach(function (role) {
role = role.replace(/(.*\/)/g, '');
});
$(document).ready(function(){
var A=['ABCD','ABCD/Admin','ABCD/DataManagement','ABCD/XYZTeam','ABCD/DriverUsers','ABCD/RISC'];
$.each(A,function(i,v){
if(v.indexOf('/')){
var e=v.split('/');
A[i]=e[e.length-1];
}
})
console.log(A);
});
You could replace the unwanted parts.
var array = ["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"];
array = array.map(function (a) {
return a.replace(/^.*\//, '');
});
console.log(array);
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(i=0;i<currentUserRole.length;i++ ){
result = currentUserRole[i].split('/');
if(result[1]){
console.log(result[1]+'-'+i);
}
else{
console.log(result[0]+'-'+i);
}
}
In console, you will get required result and array index
I would do like this;
var iur = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC',
arr = iur.split(",").map(s => s.split("/").pop());
console.log(arr);
You can use the split method as you all ready know string split method and then use the pop method that will remove the last index of the array and return the value remove pop method
var importUserRole = ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++;){
var data = currentUserRole[x].split('/');
currentUserRole[x] = data.pop();
}
Here is a long way
You can iterate the array as you have done then check if includes the caracter '/' you will take the indexOf and substact the string after the '/'
substring method in javaScript
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++){
if(currentUserRole[x].includes('/')){
var lastIndex = currentUserRole[x].indexOf('/');
currentUserRole[x] = currentUserRole[x].substr(lastIndex+1);
}
}

JavaScript remove everything before a character for a URL array

I currently have a blog featuring content within a div.
I have the following script which returns all a href tags in a blog.
function (){
var tags = [];
var count = $(".blog-featured").children().length;
for(var i=0; i<count; i++){
tags.push($('.blog-featured').children().eq(i).find('a').attr('href'));
}
return tags;
}
This is returning an array of URLs like the following [undefined, www.test.com.au/product/url/60145675?product/computer, www.test.com.au/product/url/6014 8796/test/products]
I would like to manipulate this array to:
Remove any spaces which may have occurred (not sure why but the script returns URLs with spaces)
Remove anything before a '6' and anything after the the 8(or 9 if the space isn't removed_) character product number
Remove any undefined values.
So the final array looks something like [60145675,60148796].
just split the href and replace any spaces before pushing it into the array:
eg: www.test.com.au/product/url/6014 8796/test/products
var loc =location.href;
var locPortions=loc.split("/");//splits the href at each "/";
var num=locPortions[3].replace(/ /g,"");//gets the desired portion of the href and replaces any spaces with no character - removing the spaces;
tags.push(num);//gives 60148796 out of the original href;
or to put it into your original function:
EDIT - function below amended to check for "6" at start of the locPortions.
function (){
var tags = [];
var count = $(".blog-featured").children().length;
for(i=0; i<count; i++){
var loc = $('.blog-featured').children().eq(i).find('a').attr('href');
var locPortions=loc.split("/");
for (ii=0;ii<locPortions.length;ii++){
if(locPortions[ii].charAt(0)=="6")
{
var num=locPortions[ii].replace(/ /g,"");}
tags.push(num);
}
}
return tags;
}

how to split the textarea into parts in javascript

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"]

minimized code for arrays in js

I have three arrays in js and now i want to add empty check on them..so please help me in short/ minimized code for the empty array check.My js code is
var selectedfirst = jQuery('select#frsts').val();
var selectedsecond = jQuery('select#secnds').val();
var selectedthird = jQuery('select#thirds').val();
var lastfindal = selectedfirst.concat(selectedsecond); // Array concatination
var getfinal = lastfindal.concat(selectedthird); // Array concatination
I know how can i process empty check on single array but due to contcatenation the code goes longer . i contcate first array to second then concate to third.I want to concate array when they are not empty. like selectedfirst.length > 0.if anyone not understand fully i will provide more detail on request.Thanks in advance
After working i fix the issue.I created new array like
var hege = [];
if (selectedfirst!== null) {
alert('not emtpy');
var hege = hege.concat(selectedfirst);
}
the same condition for other too.

Categories

Resources