I wanted to get the following code dynamic:
var items = $("#scenario_select option");
Above should become (with dropDownObj= $("#scenario_select"); :
function someFunction(dropDownObj){
var items = $(dropDownObj + " option");
var items = $("#" + dropDownObj + " option");
}
This both doesn't work. I did not find any help on that (only without the options tag)
Any help is greatly appreciated.
Try this:
function someFunction(dropDownObj){
var items = $('#' + dropDownObj.prop('id') + " option");
}
But I suppose a more 'proper' way to do it would be to use find as suggested by #Exception, or use:
function someFunction(dropDownObj){
var items = $("option", dropDownObj);
}
Which basically does the same thing as .find(). See This SO question for a comparison between the two (tl;dr: They are pretty much equivalent).
To find the number of items (as you noted in the comments) you could also use:
function someFunction(dropDownObj){
var items = $("option", dropDownObj).length;
}
Which is a bit shorter than the solution you posted in the comments.
You should also note that since
dropDownObj= $("#scenario_select");
It is already a jQuery object, and you don't need to wrap it using $. With this in mind you solution becomes:
var items = dropDownObj.children('option').length;
This should work.
var dropDownObj = $('#yourDropDownID');
dropDownObj.find('option')
Related
I have a situation, hope experts here will help me to sort it out. I need to get "id" values for first three tags and than on console.log print the values with comma separated.
I have managed to get the values from tag and print it on output. However, I am not able to comma separate them, and the issue is I am getting id of all the number of articles rather than only 3.
This is the jquery code that I come up with
jQuery(document).ready(function($) {
$("article").each(function() {
var info1 = $(this).attr("id");
var info2 = info1.replace( /[^\d]/g, '');
console.log(info2);
});
});
And this is the test
http://jsfiddle.net/0mvjbkhs/1/
Please note that I am not able to do any changes to html, all I can do is to get things done using jquery.
Please help to fix my code, So my output will looks like
[155569, 155570, 155571]
Thank you,
Use the jQuery .map() method which returns an array; if you need a single comma-delimited string, use the JavaScript .join() method. Don't forget :lt(3) which say you want the first three:
var arr1st3 = $('article:lt(3)').map(function() {
return this.id.replace(/[^\d]/g, '');
}).get();
console.log( arr1st3 );//OUTPUT: ["155569", "155570", "155571"]
//If you want [155569, 155570, 155571] as output
//use return +this.id.replace(/[^\d]/g, ''); instead
DEMO
jQuery(document).ready(function($) {
// search by the attribute
var ids = $('article')
// Take only the first three items
.slice(0, 3)
// Loop them to return an array
.each(function() {
// Get just the id and put that in the array
return this.attr('id');
});
// Format your output
console.log('[' + ids.join(', ') + ']');
});
http://jsfiddle.net/0mvjbkhs/4/
jQuery(document).ready(function($) {
var articles = [];
$("article").each(function() {
var info1 = $(this).attr("id").replace( /[^\d]/g, '');
articles.push(info1);
if (articles.length == 3) {
// break;
return false;
}
});
console.log('[' + articles.join(', ') + ']');
});
Please check out this Fiddle Example. It searches for strings that contain "Glucosamine". How can I strip out "Glucosamine" and add an "&" if it returns two strings, like this:
A Item
Sulfate
B Item
Sulfate & HCl
I got an undefined error using .replace("Glucosamine","") after append.
JSON:
[{"title":"A","Ingredient":"Glucosamine Sulfate,Vitamin C"},{"title":"B","Ingredient":"Vitamin D,Glucosamine Sulfate,Glucosamine HCl,Vitamin A"}]
Code:
$.ajax({
url: "text.json",
success: function (data) {
$(data.query.results.json.json).each(function (index, item) {
var title = item.title;
var ingredients = item.Ingredient;
ingredients = ingredients.split(",");
$.each(ingredients,function(i,ingredient){
if (ingredient.indexOf("Glucosamine") >= 0) {
$('.' + title+'glu').append('<h5>'+ingredient+'</h5>')
}
});
});
},
error: function () {}
});
HTML:
<h3>A Item</h3>
<div class="Aglu"></div>
<h3>B Item</h3>
<div class="Bglu"></div>
Answer
The problem is that you are trying (as far as I can tell) to use replace on the jQuery object like so:
// this will not work
$('.' + title+'glu').append('<h5>'+ingredient+'</h5>').replace("Glucosamine","");
The problem is that replace() is a function of the String object in javascript and there is no replace method in the jQuery object. What you want to do is run replace() against the ingredient variable which is a string.
// this will work
$('.' + title+'glu').append('<h5>'+ingredient.replace("Glucosamine","")+'</h5>');
Not answer
However, based on your latest comment, I don't believe this will actually help you. Although it's unrelated to the actual problem you were having, I'll go ahead and quick put down here how I would approach what you are actually trying to do. I would write your function this way:
$(data.query.results.json.json).each(function (index, item) {
var title = item.title;
var ingredients = item.Ingredient;
// this is good. I like the use of split here
ingredients = ingredients.split(",");
// here I would just filter the array. Don't bother with indexOf.
// You can just as easily use regex. I've chosen to use an
// actual regex pattern but you can also use something like this
// just as easily: ingredient.match("Glucosamine");. I just
// chose to use regex for the sake of using i for case insensi-
// tivity. glucosamineBased is now an array of only the glucose
// ingredients
var glucosamineBased = ingredients.filter(function(ingredient){
return ingredient.match(/glucosamine\s/i);
});
// now that we know which ones are actually glucose based, we
// don't need to itterate through them. Instead we can just jump
// on combining them. I use join which works the opposite as
// split above. After they are joined into one big happy string,
// I strip out the glucosamine words. Easy-peasy. Just keep in
// mind that you need g for global (don't just replace the first
// one, but replace all instances of the pattern) and maybe i for
// case insensitivity.
$('.' + title+'glu').append('<h5>' +glucosamineBased.join(' & ').replace(/glucosamine\s/gi, '')+'</h5>');
});
Hope this helps.
Demo
http://jsfiddle.net/HANvQ/
(oops... forgot the demo)
It's trickier to add the ampersand if the array contains more than one instance of the word "Glucosamine", but the following should do the trick:
$(data.query.results.json.json).each(function (index, item) {
var title = item.title;
var ingredients = item.Ingredient;
ingredients = ingredients.split(",");
var string = '';
$.each(ingredients, function (i, ingredient) {
if (ingredient.indexOf("Glucosamine") >= 0) {
ingredient = ingredient.replace("Glucosamine","");
string += (string.length == 0) ? ingredient : " & "+ingredient;
}
});
$('.' + title + 'glu').append('<h5>' + string + '</h5>')
});
http://jsfiddle.net/wDyZd/2/
I have this code which manipulates the asp.net treeview html code.
This code gets run frequently, so its important that it runs as fast as possible.
I want to learn more about jquery selectors and improving its speed. So far I was able to get this code myself.
Some things I am not sure about is if you want the third child element, do I use [2] or .eq(2) or :nth-child(2)? Also what if I use $ to select something that was from an array of selected stuff, is this necessary, or is it already selected?
Does anyone know any tricks or hints I can do to improve my jquery select efficiency?
Thanks.
function showResultsOnTreeview(treeviewID, filenameDictionary) {
var sectionNodes = $("#" + treeviewID + " > table");
var numOfSections = sectionNodes.length;
var i, j, sectionName, divContainer, itemNodes, numOfItems, itemName, itemTag, itemPath;
for (i = 0; i < numOfSections; i += 1) {
sectionName = $(sectionNodes[i]).text();
divContainer = $(sectionNodes[i]).next('div');
divContainer.hide();
itemNodes = $('table', divContainer);
numOfItems = itemNodes.length;
for (j = 0; j < numOfItems; j += 1) {
itemTag = $('td', $(itemNodes[j])).eq(2);
itemTag.removeClass('treeViewResult');
itemName = getNameFromItem($(itemNodes[j]).text());
itemPath = filenameDictionary[itemName];
if (itemPath != null) {
if (itemPath.indexOf(sectionName + "/" + itemName) != -1) {
itemTag.addClass('treeViewResult');
divContainer.show();
}
}
}
}
}
There is some optimisation you can do. The first on is for sure to use .eq() instead of []. Like here, you hare creating a jQuery object :
var sectionNodes = $("#" + treeviewID + " > table");
But then later, you do this :
sectionName = $(sectionNodes[i]).text();
divContainer = $(sectionNodes[i]).next('div');
Here you are creating 2 more, unneeded, jquery object, you could just do this :
sectionName = sectionNodes.eq(i).text();
divContainer = sectionName.next('div');
Then, i do't know if you have a different way to do it, but if you can remove the "loop in a loop", that would be great.
After, instead of using context selectore ($('selector', $element)), use find. Context use find so it will reduce the number of function calls. Take this line for example :
$('td', $(itemNodes[j])).eq(2)
You are creating 2 jQuery object when you can do the same without an extra object and could use .find():
itemTag = itemNodes.eq(j).find('td').eq(2);
Basicly, use .find() instead of context and avoid creating unneeded jQuery object. Hope that will help.
I have many jquery click function, they are very similar, how to combine them for shorter code. (use regex or use array foreach?)
$(".menu").live('click', function() {
var value = $(this).html();
$('#menu').html(value);
});
$(".nav").live('click', function() {
var value = $(this).html();
$('#nav').html(value);
});
$(".list").live('click', function() {
var value = $(this).html();
$('#list').html(value);
});
This should do:
var elems = ["menu", "nav", "list"];
$.each(elems, function(i, elem){
$("."+elem).live('click',function(){
var value = $(this).html();
$('#'+elem).html(value);
});
});
Create a list of elements.
Loop through it using $.each
The second argument of the function equals the element in the list (menu, nav, ..)
Rob's answer is definitely vote-up-worthy, but I just wanted to say that sometimes you want to limit the arbitrary connections between two elements. Why should element X have a class that MUST be the same name as element Y's ID? It's pretty arbitrary and can be a hassle for people to later figure out.
You can instead approach it like this to make it more robust:
alice
bob
sue
Now your JS becomes super straight-forward and easy:
$(".foo").live('click',function(){
var value = $(this).html();
var yourDataAttr= $(this).data('yourDataAttr');
$('#' + yourDataAttr).html(value);
});
I'm splitting a string into an array, then I want to remove the white space around each element. I'm using jQuery. I'm able to do this successfully with 2 arrays but I know it's not correct. How do I loop thru an array and trim each element so the elements keep that change. Thanks for any tips. Here is my working code using two array. Please show me the correct way to do this.
var arVeh = vehicleText.split("|");
var cleanArry = new Array();
$.each(arVeh, function (idx, val) {
cleanArry.push($.trim(this));
});
Cheers,
~ck in San Diego
You don't even really need the idx or val parameters. This appears to work on jsFiddle:
var cleanVehicles = [];
$.each(vehicleText.split("|"), function(){
cleanVehicles.push($.trim(this));
});
EDIT: Now that I've seen what you're really after, try using map:
var cleanVehicles = $.map(vehicleText.split("|"), $.trim);
I'm going to suggest not using the overhead of jQuery for a simple for-loop...
var arVeh = vehicleText.split("|");
for (var i = 0, l = arVeh.length; i < l; ++i) {
arVeh[i] = $.trim(arVeh[i]);
});
Alternatively, get rid of the whitespace from the beginning, and avoid the need for another loop at all.
var arVeh = $.trim(vehicleText).split(/\s*\|\s*/);
Without 'creating' an array in the javascript code (an array will nevertheless be created in memory)
vehicles = $.map(vehicleText.split("|"), function(e,i) { return $.trim(e) });
var my_arr = [' cats', 'dogs ', ' what '];
$.each(my_arr, function (id, val) {
my_arr[id] = $.trim(val);
});
console.log(my_arr);
This will trim the value and set it to the indexed item.
You don't have to use JQuery. Here is your vanilla solution:
testArray.map(Function.prototype.call, String.prototype.trim);
Function.prototype.call calls trim() on each of the elements of the testArray. As simple as that!
Could you not just do this?
var arVeh = vehicleText.split("|");
$.each(arVeh, function (idx, val) {
arVeh[idx] = $.trim(this);
});
//a simple function
function trimArray(dirtyArray){
$.map(dirtyArray.split("|"), function(idx, val){
return $.trim(this);
});
}
trimArray(vehicleArray);
should do the trick
Or you could use some of the awesome power of javascript and use array.prototype. I'm still a little new at using the .prototype of any object... so this isnt guaranteed to work (but it certainly can be done).
Array.prototype.trim = function (){
$.map(dirtyArray.split("|"), function(idx, val){
return $.trim(this);
});
}
someArray.trim()
You need these two jQuery functions:
1.) iterate through array element with ability to edit items:
http://api.jquery.com/jquery.map/
2.) remove blank spaces from beginning and end of a string:
http://api.jquery.com/jQuery.trim/
Use them this way:
array = $.map(array, function(value) { return value.trim();});
Check this JSFiddle:
https://jsfiddle.net/L00eyL4x/49/