Loop through all defined variables jquery - javascript

Hi I want to loop through all defined variables in a jquery function for pushing corresponding variable name into an array. The code is given below
function pushallvariables()
{
var list = [];
var name = /^[A-Za-z\s.]+$/;
var general = /^[A-Za-z0-9\s.\-\/]{2,20}$/;
var email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
var digit = /^[+]?[0-9\s]+$/;
list.push('name');
list.push('general');
list.push('email');
list.push('digit');
}
I want to modify this function into
function pushallvariables()
{
var list = [];
var name = /^[A-Za-z\s.]+$/;
var general = /^[A-Za-z0-9\s.\-\/]{2,20}$/;
var email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
var digit = /^[+]?[0-9\s]+$/;
for each(variable as var)
{
list.push(var.name);
}
}
But the modified function is not correct. How can I write the function ?

The best and clear way to do that is:
var list = {};
list.name = /^[A-Za-z\s.]+$/;
list.general = /^[A-Za-z0-9\s.\-\/]{2,20}$/;
list.email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
list.digit = /^[+]?[0-9\s]+$/;
without loops, etc

Related

If...else based on random selection from string

I am creating a script to populate an email template with random variables, using the replace() method.
Unfortunately, I am struggling to find a way of inserting a gender pronoun, based on the gender of a random name chosen from a string. Is there a way to do this using the excerpts of the scripts below (or am I missing something incredibly obvious)?
HTML
<p id="lineTwo">firstName told genderPronounOne friends...</p>
JavaScript
//Random Name
var maleNames = ['Tom', 'Tony'];
var femaleNames = ['Tina', 'Tracy'];
var maleRandom = maleNames[Math.round(Math.random()*(maleNames.length-1))]+'\n';
var femaleRandom = femaleNames[Math.round(Math.random()*(femaleNames.length-1))]+'\n';
var nameGender = [maleRandom, femaleRandom
var name = nameGender[Math.round(Math.random()*(nameGender.length-1))]+'\n';
//Determine Gender
var pronounOne;
if(/* this is where I'm struggling */){
pronounOne = 'his';
} else {
pronounOne = 'her';
}
//Replace HTML
var replaceHTML = document.getElementById("lineTwo").innerHTML;
var replaceName = replaceHTML.replace("firstName", name);
var replacePronoun = replaceHTML.replace("genderPronounOne", pronounOne);
document.getElementById("lineTwo").innerHTML = replaceName;
document.getElementById("lineTwo").innerHTML = recplacePronoun;
Can anyone help? Thank you.
Store the 0 or 1 in a variable and use it
var mf = Math.round(Math.random()*(nameGender.length-1))
var name = nameGender[mf]+'\n';
//Determine Gender
var pronounOne = mf ? "her" :'his';
How about you check to see if the name that you selected is in the array of male names?
if (maleNames.indexOf(name) > -1) {
pronounOne = 'his';
} else {
pronounOne = 'her';
}

Access Json outside of javascript each function

below is my script,
var holidays = {};
var count=0;
$('.row').each(function(index) {
var names = document.getElementById('name['+count+']').value;
var dates = document.getElementById('dateh['+count+']').value;
holidays[names] = dates;
count ++;
console.log(holidays);
});
If i do console.log(holidays); inside the function i can get the json object, but if i do the same outside of $('.row').each(function(index) it's not printing any.
Did anyone know where i'm going wrong ?
declare array like
var holidays = [];
or
var holidays = new Array();

How do I overwrite object properties in an array?

I would like to overwrite a certain allOrders[i] with data, similar to how I create a new one. For some reason I can't figure out what to search on.
I have an array of objects allOrders.
I have an object BusinessCard. I take the form fields, serialize() them, clean up the data with a regex, then push the them into an array.
allOrders.push(new BusinessCard(currentOrder.quantity, currentOrder.FullName, currentOrder.Title, currentOrder.CellNumber, currentOrder.OfficeNumber, currentOrder.FaxNumber, currentOrder.EmailAddress, currentOrder.Address, currentOrder.website, currentOrder.price));
I've tried searching for overwriting existing object properties in an array and the likes and haven't figured out what to do here.
My best guess was allOrders[i].push -- but it seems to me that I have to write a new function to replace each property in the object.
Right now I am using(because using serialize() on the form inputs doesn't help me at all:
allOrders[i].quantity = $('#bcQuantity').val();
allOrders[i].fullname = $('#fullName').val();
allOrders[i].title = $('#Title').val();
allOrders[i].cell = $('#CellNumber').val();
allOrders[i].office = $('#OfficeNumber').val();
allOrders[i].fax = $('#FaxNumber').val();
allOrders[i].email = $('#EmailAddress').val();
allOrders[i].address = $('#Address').val();
allOrders[i].website = $('#website').val();
allOrders[i].price = $('#bcCostBeforeCart').text();
There has to be a smarter way to do this. Thank you.
EDIT:
function getFormData(formId) {
var currentForm = '#' + formId;
var currentPrice = $('#bcCostBeforeCart').text();
var currentFormData = $(currentForm).serialize();
var currentFormDataFinal = currentFormData + '&price=' + currentPrice;
return JSON.parse('{"' + decodeURI(currentFormDataFinal.replace(/\+/g, " ").replace(/&/g, "\",\"").replace(/=/g, "\":\"")) + '"}');
}
MEANING i could be using
currentOrder = getFormData('businessCardForm');
then
allOrders[i] = currentOrder;
Seems odd that you would be updating all items with the selector's you're using, but I would wrap up getting the updated order information then, you can run thru a loop.
Depending on your output, as long as it's outputing the respective properties and values of an order object you could just do:
for(int i =0; i < allOrders.length; i++){
var currentFormId = '' // update this for each iteration.
allOrders[i] = getFormData(currentFormId);
}
allOrders[i] = getUpdatedOrder();
function getUpdatedOrder() {
var order = {};
order.quantity = $('#bcQuantity').val();
order.fullname = $('#fullName').val();
order.title = $('#Title').val();
order.cell = $('#CellNumber').val();
order.office = $('#OfficeNumber').val();
order.fax = $('#FaxNumber').val();
order.email = $('#EmailAddress').val();
order.address = $('#Address').val();
order.website = $('#website').val();
order.price = $('#bcCostBeforeCart').text();
return order;
}

javascript fails when populating array

When I run the following javascript, it fails when input_array[input_array.length] = id; is not commented out. Can anyone see what is causing this?
function cat_images_low_lag () {
var input_array = new array ();
cat_images = $(".category-description").next().find("img");
cat_images.each(function () {
url = $(this).parent().attr("href");
id = url.split("id=");
id = id[1];
input_array[input_array.length] = id;
});
alert ("trst");
alert(input_array.join("\n"));
}
cheers!
First thing, replace:
var input_array = new array ();
With:
var input_array = new Array();
And use this to insert:
input_array.push(id);
Or directly add:
input_array[input_array.length] = id;
Other ways to initialize arrays:
var input_array = [];
Others noted the capitalization problem, but since you're using jQuery, a nicer way to build the Array is like this:
function cat_images_low_lag () {
var input_array = $(".category-description + * img").map(function () {
return this.parentNode.href.split("id=")[1];
}).toArray();
alert ("trst");
alert(input_array.join("\n"));
}
Your initialization of the array is incorrect
var input_array = new array ();
You should use the shorthand
var input_array = [];
or
var input_array = new Array();
Moreover, to avoid having cat_images be a variable in the global scope, you may want to consider scoping it locally like this
var cat_images = $(".category-description").next().find("img");

extract elements from two arrays with same value

Hello I want to extract elements from both arrays with the same url .How can i loop these two arrays and get their content, because it gives me undefined for the news_url and i think it outputs twice the items in the console.
function geo(news_array,user_tweets){
console.log(news_array,user_tweets);
for (var x=0; x<user_tweets.length; x++) {
var user = user_tweets[x].user;
var date = user_tweets[x].date;
var profile_img = user_tweets[x].profile_img;
var text = user_tweets[x].text;
var url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
function second(user,date,profile_img,text,url){
for (var i = 0; i < news_array.length; i++) {
var news_user = news_array[i].news_user;
var news_date = news_array[i].news_date;
var news_profile_img = news_array[i].news_profile_img;
var news_text = news_array[i].news_text;
var news_url=news_array[i].url;
if (url==news_array[i].news_url) {
geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url);
}
}
}
function geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url) {
console.log(url,news_url);
}
}
The problem is
in news_tweets function, you add news_url to news_array. So you should call
news_array[i].news_url
in second function.
I modify your code as
news_url: (item.entities.urls.length > 0)?item.entities.urls[0].url : '' in news_tweets function
add close brace } for geo function and remove } from last
add new_array parameter to second function like second(user, date, profile_img, text, url,news_array);
Modify code can be tested in http://jsfiddle.net/rhjJb/7/
You have to declare some variables before the first for loop, so that they can be accessed in the scope of the second function. Try to replace your first for loop with the following code:
var user, date, profile_img, text, url;
for (var x=0; x<user_tweets.length; x++){
user = user_tweets[x].user;
date = user_tweets[x].date;
profile_img = user_tweets[x].profile_img;
text = user_tweets[x].text;
url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
Moreover, in the if of your second function, news_array[i].news_url isn't defined. Use if (url == news_url) instead.

Categories