How to optimize or make this dynamic (html javascript) - javascript

i'm still new in html javascript. I want to ask can i use for loop to optimize or make this dynamic
var port = [];
port[0]=$('#slcPort_0').val();
port[1]=$('#slcPort_1').val();
port[2]=$('#slcPort_2').val();
port[3]=$('#slcPort_3').val();
port[4]=$('#slcPort_4').val();
i used this code in function to retrieve data from html form
thanks

You could use:
// selects all the elements whose 'id' starts-with "slcPort_":
var port = $('[id^=slcPort_]').map(function(){
// returns the value from those elements:
return this.value;
// converts to an array:
}).get();
This isn't guaranteed to be in numerical order, though it will be in order of the appearance of those elements in the DOM.
References:
Attribute-starts-with ([attribute^=value]) selector.
get().
map().

Simply, you can do the following:
var port = Array();
for (i = 0; i < 5; i++){
port[i] = $("#slcPort_"+i).val();
}
DEMO: http://jsbin.com/yiyaruweja/1/

It might make more sense to give all those elements a class, like slcPort. Then something like
var port = [];
$.each($('.slcPort'), function(index,value) {
port[index] = $(value).val();
});
Much prettier. Plus all those elements are related anyways, so just class em up.
$.each documentation

Related

$.grep filter with contains

I am trying to filter an array with grep to apply CSS. My code is like below.
var depos = $('.panel-default > .panel-heading');
var chkd = ['ABC','XYZ'];
var found_p = $.grep(depos, function(v) {
return jQuery.inArray(v.innerText,chkd);
});
The first issue is that found_p is not filtering the needed array values from chkd. After filtering it, how can I apply CSS? I tried like below but it fails
$(found_p[0]).css('background-color', 'red');
Can anybody help me out with this.
Assuming from your code that you're trying to find the elements that have innerText matching a value in the chkd array, you can use the filter() method. Try this:
var $depos = $('.panel-default > .panel-heading');
var chkd = ['ABC','XYZ'];
var $found_p = $depos.filter(function() {
return $.inArray($(this).text(), chkd) != -1;
});
The $found_p variable will then hold a jQuery object with all matched elements. You can apply CSS to them like this:
$found_p.css('background-color', 'red');
Example fiddle
However, I would suggest using CSS classes instead of adding inline styles as it is much better practice.

Using JQuery's .attr() When Selector Returns Multiple elements

I am trying to pull 2 pieces of data from each of several fields. All the fields have been given the same "name" so as to allow them to be referenced easily.
<input type="text" name="common_name" data-X='ABC'>
The first piece of data I am pulling is their values, which does seem to be working. My issue is when I try to use attr(). It just stops dead in the water at that point.
var length = $('[name=common_name]').size();
for(var i=0; i < length; i++){
var value = parseInt($('[name=common_name]').get(i).value); //doesn't kill the script
var dataX = $('[name=common_name]').get(i).attr('data-X'); //Script is killed here
}
Since I'm not having issues with using attr() in general when the selector is selecting the element based on an id, I would think the issue has to do with the fact that in this case multiple elements are being returned by jQuery. What I am confused by is that I thought that get(#) is supposed to grab a specific one…in which case I don't see what the problem would be. (After all, using get(#) DOES work when I use val()).
So…why doesn't attr() work here?
.get() returns a dom element reference which does not have the .attr() method, so you can use the .eq() method which will return a jQuery object
var length = $('[name=common_name]').size();
for (var i = 0; i < length; i++) {
var value = parseInt($('[name=common_name]').eq(i).val()); //doesn't kill the script
var dataX = $('[name=common_name]').eq(i).attr('data-X'); //Script is killed here
}
The correct way to iterate over an jQuery object collection is to use the .each() method where the callback will be invoked for each element in the jQuery collection
$('[name=common_name]').each(function () {
var $this = $(this);
var value = parseInt($this.val()); //or this.value
var dataX = $this.attr('data-X'); //or $this.data('X')
})
Suppose the html is like this
<input type="text" name="common_name" data-X='ABC'>
<input type="text" name="common_name" data-X='DEF'>
<input type="text" name="common_name" data-X='GHI'>
Now the script part
$('input[name="common_name"]').each(function() {
var el = $(this);
text_val = el.val();
data = el.attr('data-X');
console.log(text_val);
console.log(data);
});
attr is a jquery fn, should call by jquery object
use like this
$('[name=common_name]').attr('data-X')
so try
dataX = $($('[name=common_name]').get(i)).attr('data-X');

Simple JSON array

I want to create a simple array like item_structure = {thumb, head, cont} and here is my code:
$('.items_options').find('#'+item_id+' .option .blog_item_structure li')
.each(function(event) {
var item_class = $(this).attr('class');
item_structure[] = item_class;
});
But it seems that expresion item_structure[] = ... is not working. So does anyone of you know what is rigt syntax?
Thx for your time.
You probably mean to push a value:
item_structure.push(item_class);
This adds item_class as the last element of item_structure.
For this to work item_structure must be an array, most easily made so this way:
item_structure = [];

Uncaught TypeError: Object #<HTMLDivElement> has no method 'attr'

Im trying to grab my divs with the class tooltip.
And then do something like this:
var schemes = $(".tooltip");
for (var i in schemes) {
var scheme = schemes[i];
console.log(scheme.attr("cost"));
}
But it throws the above error. What am i missing? (Im new to javascript + jquery obviously)
If you use for-loop to iterate jQuery set, you should get the elements with eq() method, but not using square bracket notation (i.e. []). The code like $(".tooltip")[i] will pick up DOM elements, but not jQuery objects.
var schemes = $(".tooltip");
for (var i = 0; i < schemes.length; i++) {
var scheme = schemes.eq(i);
console.log(scheme.attr("cost"));
}
However, you may always use each() to iterate jQuery set:
$(".tooltip").each(function() {
var scheme = $(this);
console.log(scheme.attr("cost"));
});
var schemes = $(".tooltip");
schemes.each(function(index, elem) {
console.log($(elem).attr('cost'));
});
As a sidenote "cost" is not a valid attribute for any element as far as I know, and you should probably be using data attributes.

javascript - get all anchor tags and compare them to an array

I have been trying forever but it is just not working, how can I check the array of urls I got (document.getElementsByTagName('a').href;) to see if any of the websites are in another array?
getElementByTagName gives you a nodelist (an array of nodes).
var a = document.getElementsByTagName('a');
for (var idx= 0; idx < a.length; ++idx){
console.log(a[idx].href);
}
I really suggest that you use a frame work for this, like jquery. It makes your life so much easier.
Example with jquery:
$("a").each(function(){
console.log(this.href);
});
var linkcheck = (function(){
if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]===obj){
return i;
}
}
return -1;
}
}
var url_pages = [], anchor_nodes = []; // this is where you put the resulting urls
var anchors = document.links; // your anchor collection
var i = anchors.length;
while (i--){
var a = anchors[i];
anchor_nodes.push(a); // push the node object in case that needs to change
url_pages.push(a.href); // push the href attribute to the array of hrefs
}
return {
urlsOnPage: url_pages,
anchorTags: anchor_nodes,
checkDuplicateUrls: function(url_list){
var duplicates = []; // instantiate a blank array
var j = url_list.length;
while(j--){
var x = url_list[j];
if (url_pages.indexOf(x) > -1){ // check the index of each item in the array.
duplicates.push(x); // add it to the list of duplicate urls
}
}
return duplicates; // return the list of duplicates.
},
getAnchorsForUrl: function(url){
return anchor_nodes[url_pages.indexOf(url)];
}
}
})()
// to use it:
var result = linkcheck.checkDuplicateUrls(your_array_of_urls);
This is a fairly straight forward implementation of a pure JavaScript method for achieving what I believe the spec calls for. This also uses closures to give you access to the result set at any time, in case your list of urls changes over time and the new list needs to be checked. I also added the resulting anchor tags as an array, since we are iterating them anyway, so you can change their properties on the fly. And since it might be useful to have there is a convenience method for getting the anchor tag by passing the url (first one in the result set). Per the comments below, included snippet to create indexOf for IE8 and switched document.getElementsByTagName to document.links to get dynamic list of objects.
Using Jquery u can do some thing like this-
$('a').each(function(){
if( urls.indexOf(this.href) !- -1 )
alert('match found - ' + this.href );
})
urls is the your existing array you need to compare with.

Categories

Resources