javascript /jQuery - For Loop - javascript

I have a query ajax response which I then use to set the array variables.
Is there anyway to use a 'For Loop' to change to #name so that I don't have to write out a line of code to set each array element.
array[0]=$('#event00',response).html();
array[1]=$('#event01',response).html();
array[2]=$('#event02',response).html();
array[3]=$('#event03',response).html();
So '#event00' could be used in a for loop to change to '#event01' etc

Use a regular for loop and format the index to be used in the selector.
var array = [];
for (var i = 0; i < 4; i++) {
var selector = '' + i;
if (selector.length == 1)
selector = '0' + selector;
selector = '#event' + selector;
array.push($(selector, response).html());
}

What about something like this?
var arr = [];
$('[id^=event]', response).each(function(){
arr.push($(this).html());
});
The [attr^=selector] selector matches elements on which the attr attribute starts with the given string, that way you don't care about the numbers after "event".

.each() should work for you. http://api.jquery.com/jQuery.each/ or http://api.jquery.com/each/ or you could use .map.
var newArray = $(array).map(function(i) {
return $('#event' + i, response).html();
});
Edit: I removed the adding of the prepended 0 since it is suggested to not use that.
If you must have it use
var newArray = $(array).map(function(i) {
var number = '' + i;
if (number.length == 1) {
number = '0' + number;
}
return $('#event' + number, response).html();
});

Related

Get concatenate string of multiple value variable in Javascript

I've a list of div
<div data-attr="sel" data-num="1"></div>
<div data-attr="notSel" data-num="2"></div>
<div data-attr="sel" data-num="3"></div>
I'm tryng to get a string only div with the data-attr="sel" set.
function SI_MoveTasks() {
var getSelected = document.querySelector('[data-attr~="sel"]');
var selectedNums = getSelected.dataset.num;
alert(selectedNums);
}
Now i get (1), how can i get the concatenate string (1,3)?
Thanks for support.
DEMO -> http://jsfiddle.net/0d54ethw/
Use querySelectorAll instead of querySelector since the latter only selects the first element as opposed to all of them.
Then use for loop as shown below
var getSelected = document.querySelectorAll('[data-attr~="sel"]');
var selectedNums = [];
for (var i = 0; i < getSelected.length; i++) {
selectedNums.push(getSelected[i].dataset.num);
}
alert(selectedNums.join(','));
You would need to use document.querySelectorAll to get all matching elements. document.querySelector returns only the first matching element, or null if there is none.
function SI_MoveTasks() {
var getSelected = document.querySelectorAll('[data-attr~="sel"]');
console.log(getSelected);
var selectedNums = '(';
for(var i=0; i< getSelected.length; i++) {
if (selectedNums !== '(') {
selectedNums += ',';
}
selectedNums += getSelected[i].dataset.num;
}
selectedNums += ')';
alert(selectedNums);
}
SI_MoveTasks();
Thats a working code, jsFiddle is: https://jsfiddle.net/3kjye452/

Remove comma from javascript array

Hi all I am framing a url with Query string in javascript as follows every thing works fine but a comm is coming in between the query string so can some one help me
<script type="text/javascript">
function RedirectLocation() {
var cntrl = "Q1;Q2";
var str_array = cntrl.split(';');
var cnt = str_array.length;
if (cnt == 0) {
location.href = '/callBack.aspx';
}
else {
var arr = [];
for (var i = 0; i < str_array.length; i++) {
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
arr.push(str_array[i] + '=1');
if (i != str_array.length - 1) {
arr.push('&');
}
}
location.href = '/Sample.aspx?' + arr;
}
}
</script>
This is giving me the query string as follows Sample.aspx?Q1=1,&,Q2=1 I need this to be like `Sample.aspx?Q1=1&Q2=1
To remove the commas from a string you could simply do
s = s.replace(/,/g,'');
But in your specific case, what you want is not to add the commas. Change
location.href = '/Sample.aspx?' + arr;
to
location.href = '/Sample.aspx?' + arr.join('');
What happens is that adding an array to a string calls toString on that array and that function adds the commas :
""+["a","b"] gives "a,b"
Don't rely on the implicit string conversion (which concatenates the array elements with a comma as separator), explicitly .join the array elements with &:
var arr = [];
for (var i = 0; i < str_array.length; i++) {
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
arr.push(str_array[i] + '=1');
}
location.href = '/Sample.aspx?' + arr.join('&');
Think about it like this: You have a set of name=value entries which you want to have separated by &.
You can use arr.join(glue) to concatenate Array elements with something inbetween. In your case glue would be an empty string arr.join("").

How to check if a particular characters are available in a javascript string array

I have a javascript array like
var main_array = ["allen~1", "ajay~2", "raj~3"];
I have another array like
var sub_array=["allen", "ajay"];
EDIT
I need to check whether each values of sub_array is found in main_array, (i.e) whether 'allen' found in ["allen~1", "ajay~2", "raj~3"] so the values which do not match must be removed from the array. As the result "raj~3" must be removed from the main_array
How to achieve this?
I have tried indexOf(), match() but that fails since it expects an exact match like "allen~1"..
Thanks in advance
your question is kind if not so clear, but i think what you want to achieve is an array which contains all values from main_array which are part of sub_array? in your example the resulting array should be
["allen~1", "ajay~2"]
? if so see this:
then you need to loop over your sub-array, and check in your main_array:
var i, j, result = [];
for (i = 0; i < sub_array.length; i++) {
for (j = 0; j < main_array.length; j++) {
if (main_array[j].indexOf(sub_array[i]) != -1) {
result.push(main_array[j]);
}
}
}
see a working jsfiddle: http://jsfiddle.net/yf7Dw/
edit: Felix Kings answer is probably best, but if you dont want to use polyfills and must support older IE's you could use my solution
edit2: Array.splice is your friend if you want to remove the element from the main array. see the updated fiddle: http://jsfiddle.net/yf7Dw/2/
var i, j;
for (i = 0; i < sub_array.length; i++) {
for (j = 0; j < main_array.length; j++) {
if (main_array[j].indexOf(sub_array[i]) != -1) {
main_array.splice(j, 1);
}
}
}
You can use .every [MDN] and .some [MDN]:
var all_contained = sub_array.every(function(str) {
return main_array.some(function(v) {
return v.indexOf(str) > -1;
});
});
Have a look at the documentation for polyfills for older IE versions.
If you want to remove elements, you can use .filter [MDN] and a regular expression:
// creates /allen|ajay/
var pattern = new RegExp(sub_array.join('|'));
var filtered = main_array.filter(function(value) {
return pattern.test(value);
});
Values for which the test returns false are not included in the final array.
If the values in sub_array can contain special regular expression characters, you have to escape them first: Is there a RegExp.escape function in Javascript?.
Build a RegExp from the searched string and use match with it
string.match(new RegExp(searchedString + ".*"));
or
string.match(new RegExp(searchedString + "~[0-9]+"));
try
var globalBoolean =true;
$.each(subarray, function (index,value) {
if ( !($.inArray(value, main_array) > -1)){
globalBoolean =false;
}
});
If globalBoolean is true then equal.
try
var main_array = ["allen~1", "ajay~2", "raj~3"];
var main_array1 = new Array();
for (var i = 0; i < main_array.length; i++) {
main_array1.push(main_array[i].split('~')[0])
}
var sub_array = ["allen", "ajay"];
if ($.inArray('allen', main_array1) == -1) {
alert('false');
}
else {
alert('true');
}
Just another solution...
var filtered_array = jQuery.grep(main_array, function(n1, i1){
var y = jQuery.grep(sub_array, function(n2, i2){
return n1.indexOf(n2) !== -1; // substring found?
});
return y.length; // 0 == false
});
Get underscore js. Then do this:
var myarray = ["Iam","Iamme","meIam"];
var sub_ar = ["am", "amI", "amme"];
_.each(myarray, function(x){
_.each(sub_ar, function(y){
if(x == y)
{
console.log(y + " is a match");
});
});
Sorry. This wont work because you are looking for substring. My bad. Try this:
var myarray = ["Iam","Iamme","meIam"];
var sub_ar = ["am", "amI", "amme"];
_.each(myarray, function(x){
_.each(sub_ar, function(y){
if(x.indexOf(y) !== -1)
{
console.log("match found");
});
});

How to increment number in string using Javascript or Jquery

The id of my textarea is string and of this format
id='fisher[27].man'
I would like to clone the textarea and increment the number and get the id as fisher[28].man and prepend this to the existing textarea.
Is there a way to get this done easily with jquery?
var existingId = $("#at textarea:last").attr('id');
var newCloned = lastTextArea.clone();
var newId = newCloned.attr('id');
//add the index number after spliting
//prepend the new one to
newCloned.prepend("<tr><td>" + newCloned + "</td></tr>");
There has to be easier way to clone, get index number, split and prepend.
I'm have also tried to do this with regEx
var existingIdNumber = parseInt(/fisher[(\d+)]/.exec(s)[1], 10);
Can anybody help me with this?
Correct regex would be this
/fisher\[\d+\].man/
Here is a way through through which you would extract the the id.
id = text.replace(/fisher\[(\d+)\].man+/g,"$1");
//Now do whatever you want with the id
Similarly, Same replacement technique can be used to get an incremented id as:
existingId = 'fisher[27].man';
newId = existingId .replace(/(\d+)+/g, function(match, number) {
return parseInt(number)+1;
});
console.log(newId);
Demo with both usage
jsFiddle Demo
No need for all the extra code. Change this line:
var newId = newCloned.attr('id');
To:
var newId = newCloned.attr('id').replace( /(\d+)/, function(){return arguments[1]*1+1} );
Another easy solution from this question's accepted answer:
'url1'.replace(/\d+$/, function(n){ return ++n }); // "url2"
'url54'.replace(/\d+$/, function(n){ return ++n }); // "url55"
Very clean and readable.
If your Id has this format
id='fisher[27].man'
You can do something like this
var startIndex = newId.indexOf('[');
var endIndex = newId.indexOf(']');
var number = parseInt(newId.substr(startIndex + 1, endIndex - startIndex - 1));
var incrementedId = number + 1; // 28
where
var newId = newCloned.attr('id');
I am amazed that there is not any good implementation for this simple thing. All of the examples forget the case of having zeroes before the number. The code below should take care of that.
// 'item001' => 'item002'
function increment_alphanumeric_str(str){
var numeric = str.match(/\d+$/)[0];
var prefix = str.split(numeric)[0];
function increment_string_num(str){
var inc = String(parseInt(str)+1);
return str.slice(0, str.length-inc.length)+inc;
}
return prefix+increment_string_num(numeric);
}
Example:
> increment_alphanumeric_str('test09')
'test10'
Only drawback is that this will break if we have something like 'test99'.
You can do this pretty easily with a regex replacement:
var id = "fisher[27].man";
id = id.replace(/\[(\d+)\]/, function(match, number) {
return '[' + (parseInt(number, 10) + 1) + ']';
});
// id is now "fisher[28].man"

Accessing a counter in a variable name in Javascript (code inside)

I am looking to do something very similar to the following PHP code but in javascipt:
for ($weenumber = 1; $weenumber <= 30; $weenumber++)
{
$weenumber = str_pad($weenumber, 2, "0", STR_PAD_LEFT);
echo $_POST["entry{$weenumber}_cash"];
}
Basically accessing the loop number padded with a trailing 0 if less than 10 but I dont know the syntax in JS to do this :(
Sorry for noob style question
I think that you mean a leading zero rather than a trailing zero...
You can for example use the conditional operator:
(n < 10 ? '0' : '') + n
You could also implement a general purpose function:
function padLeft(str, len, ch) {
while (str.length < len) str = ch + str;
return str;
}
To access an object property by name in Javascript you use brackets. Example:
var value = obj['entry' + (n < 10 ? '0' : '') + n + '_cash'];
If n contains 4, this will be the same as obj.entry04_cash.
Whether or not there's a specific function to do this, if you know how to use an if clause, and you know how to perform string concatentation (using the + operator if you didn't), then you should be able to easily roll you own version of str_pad by hand (which works for numbers below 100).
Think about the cases involved (there are only two) and what you need to output in either case.
This is the code you should use:
for(var i=0; i<30; i++){
document.writeln(i<10 ? "0"+i : i);
}
change document.writeln() with any function you want to handle the data
for (weenumber = 1; weenumber <= 30; weenumber++) {
weenumber = str_pad(weenumber, 2, "0", STR_PAD_LEFT);
}
For the str_pad() function, you can use PHPJS library:
http://phpjs.org/functions/str_pad:525
This library will also ease transition from php to javascript for you. Check it out.
for(var i=0; i<30; i++)
{
var index = i;
if(i<10) index = "0" + index
var elem = document.getElementById("entry"+index);
}
var someArray = [/*...*/];
for (var i= 1;i<= 30;i++)
{
var weenumber = i+"";
for(var j=weenumber.length;j<2;j++)
weenumber = "0" + weenumber;
var key = "entry" + weenumber + "_cash";
document.write(someArray[key]);
}
Here's a function you can use for zeropadding:
function zeroPad(nr,base){
var len = (String(base).length - String(nr).length)+1;
return len > 0? new Array(len).join('0')+nr : nr;
}
//usage
alert(zeroPad(3,10)); //=> 03
or extend the Number prototype
Number.prototype.zeroPad = Number.prototype.zeroPad ||
function(base){
var nr = this, len = (String(base).length - String(nr).length)+1;
return len > 0? new Array(len).join('0')+nr : nr;
};
//usage
var num = 1;
alert(num.zeroPad(100)); //=> 001
Now for the variable name part: if it's a global variable (not advisable) that variable is a property of the global object, in a browser that's window. You can get a variable by its dynamic name using the equivalent of: window['myvariable'+myJustResolvedNumericValue]. Within an object (instance) you can use the same bracket notation: myObject['myvariable'+myJustResolvedNumericValue].
Using this information, in javascript your function could look like:
for (var weenumber = 1; weenumber <= 30; weenumber++)
{
// execute something using the variable that uses the counter in the
// variable name as parameter
executeSomeFunction(window['entry'+weenumber.padLeft(10) + '_cash']);
}

Categories