I don't know how to achieve it and I been looking for ways to do this for hours without any success.
Let's say I have this code:
var vara="bing.com";
var varb="google.com";
jQuery('a[href^="http://'+vara+'"],a[href^="https://'+vara+'"]').click(function() {alert('y'); });
jQuery('a[href^="http://'+varb+'"],a[href^="https://'+varb+'"]').click(function() {alert('y'); });
And what I need to achieve here is to use one call that sets up the .click functions for each array variable:
var varall=["bing.com","google.com"];
jQuery('a[href^="http://'+varall+'"],a[href^="https://'+varall+'"]').click(function() {alert('y'); });
But this doesn't work. How to make variable "varall" take every element from array, so the second script would work as the first one?
Evan Trimboli's answer is OK but... In this case this selector sintaxis is not very good. Because, as I know, when jQuery will add event to <a> it will split a string and loop every element (again). So we get double looping.
I think the best option is to do something like this:
var varall=["bing.com","google.com"];
varall.forEach(function(item, i, arr) {
$(document).on('click', 'a[href^="http://' + item + '"], a[href^="https://' + item + '"]', function() {
alert('y');
});
});
https://jsfiddle.net/Lfjy2Lxu/
It looks like you're looking to do this
var varall=["bing.com","google.com"];
$.each(varall, function(index, value){
jQuery('a[href^="http://'+value+'"],a[href^="https://'+value+'"]').click(function() {alert('y'); });
});
Related
Imagine that you have the following button:
<button id="id" data-trigger-function = "true", data-value-1="12345", data-value-guid="534-534-657647365-gd">Click Me for Function</button>
Is it possible, to get something like the following in the called function:
$(this).attr('data-value-'+ * ).each(...);
The objective would be to use a universal selector in the attribute name, and not in the attribute value (not something like this: [name^='something']). The objective is to get the values of data-value-1 and data-value-guid because they both have the same start.., this means that data-value could be, data-value-qwerty, data-value-xpto, without having to know the *.
I've searched this, but couldn't find anything like this, or any mentions to something like this. Is it possible?
Thank you! (sorry for the bad english)
You could get all attributes and loop through them:
$.each(this.attributes, function(index, attr){
var name = attr.name;
if(name.startsWith('data-value') {
var value = attr.value;
//You code goes here
}
});
Another option:
You may also choose to iterate thru the data-* only and filter our the ones that start with value like below:
$.each($("button").data(), function(key, val) {
if (key.match(/^value/i)) {
alert (key + ": " + val);
}
})
Note: the above requires you to change data-value-1="12345" to something like data-value-one="12345"
A Demo
I have a function that uses each to go over each element in a set and renumber them after one is removed from the DOM.
Right now that function looks like this:
renumber_items = function(){
$(".item_set").each(function(index){
$(this).find('legend').html("Item " + (index+1));
});
};
I remember reading somewhere that find is a really inefficient operation, so I was wondering if there's a way to combine the 'legend' selector into a compound selector with this.
If there is only one legend per .item_set this will abbreviate things a bit:
renumber_items = function(){
$(".item_set legend").html(function(index){
return "Item " + (index+1);
});
};
.html can take a function and the result is stored.
If there is more than one legend per .item_set you will need to retain an outer each to keep the numbers sequential for each set.
Generally if you have speed issues, on a function called many times, and the jQuery selector result is on a fixed set of elements, you just archive the search to a variable once at page load and reuse that:
var $legends = $(".item_set legend");
renumber_items = function(){
$legends.html(function(index){
return "Item " + (index+1);
});
};
Maybe you can try with .filter(). As others say, it shouldn't be such a performance issue as long as you're not using it all the time. Consider labeling all the items you want to find/filter, so that you can get them all in one JQuery selector at once, and you don't have to go filtering everything after. Else you can use (as commented out by #Regent):
renumber_items = function(){
$(".item_set legend").each(function(index){
$(this).html("Item " + (index+1));
});
};
You can replace:
$(this).find('legend')
with:
$('legend', this)
The second argument sets the context in which jQuery searches for 'legend'.
If it is omitted, the context defaults to be document.
I am finding all the divs in a document which contains inside a text: 'thetext' and i am changing this text:
$("div:contains('thetext'):not(:has(*))").each(function () {
$(this).text($(this).text() + " anotherTextAddedBefore");
})
Is it possible to put inside contains multiple values?
I would like to find the divs whic contains: 'thetext', but also another values, for example: 'thetext1', 'thetext2',etc
I`d want to make it in one procedure and not in more: dont want to use as many procedures as texts i´d like to find.
Thanks!
You can use the multiple selector as a or condition like
$("div:not(:has(*))").filter(":contains('thetext'), :contains('thetext2')").each(..)
A selector like this provides an OR condition -
$("div:contains('thetext'), div:contains('thetext1'), div:contains('thetext2')")
A selector like this provides an AND condition -
$("div:contains('thetext'):contains('thetext1'):contains('thetext2')")
Demo - http://jsfiddle.net/jayblanchard/3a72h/
You can have an array
var array = ['John', 'Martin'];
$(array).each(function () {
$("div:contains(" + this + ")").css("text-decoration", "underline");
});
WORKING EXAMPLE
Just adding one more point to above answers, if you want to select elements that dont have particular values then you can use
$("div:not(:contains('thetext'), :contains('thetext1'),:contains('thetext2'))")
works as and condition
You can create an array and loop it:
var containsVals = ["text1","text2"];
for(var i=0;i<containsVals.length;i++){
$("div:contains("+ containsVals[i] +"):not(:has(*))").each(function () {
$(this).text($(this).text() + " anotherTextAddedBefore");
});
}
I want to fetch the id of an element and pass it in jquery function -
$('#fetchedID').fadeOut;
Till now I have tried -
1. $("#$('.delete_status').attr('id')").fadeOut(400);
2. var e = $('.delete_status').attr('id');
$(e).fadeOut(400);
I am sure I am stuck because of the wrong syntax of passing javascript variable in jQuery function. Please help.
Try with concating the Id that you have got with the Id selector(#) like
var e = $('.delete_status').attr('id');
$("#" + e).fadeOut(400);
You have to concatenate the selector, like this:
$("#" + $('.delete_status').prop('id')).fadeOut(400);
If you're going to be using the ID more than once, it is a good idea to cache it:
var delete_status_id = $('.delete_status').prop('id');
$("#" + delete_status_id ).fadeOut(400);
// do something else with delete_status_id...
$("#" + $('.delete_status').attr('id')).fadeOut(400);
Do you really need to pick the ID to then reselect the element and do the fade? If you want to pick only the first occurence of your class, you can use :eq(0) instead.
$('.delete_status:eq(0)').fadeOut(400);
I have an AJAX script that receives a string from a mySQL query returned by PHP.
This string is then parsed and put into an array in Jquery and the results are printed to the screen using .html()
The length of this array varies from 0 items to many, how would I count the items in the array then loop through and print them to the screen.
Here is my UPDATED code per the advice below, though I am still not sure if the for loop goes inside the .html() function or outside?
UPDATED CODE TO INCLUDE .each()
UPDATE 2: Replace (this) in the .html() function with the element I want the text written in and it is working partially, issue is now it is only printing the last item in the array?
UPDATE 3: Seems you can only have a single .html() function run, for instance if I add another .html() statement under the one that is returning the last item in my array it will only now echo on the screen the test value.
$("#n_detail").html(partsArray[index]+"<br />").addClass('jText').fadeTo(900,1);
$("#n_detail").html("Test").addClass('jText').fadeTo(900,1);
It will only print "Test", not the last item in the array like it was previously?
<script type="text/javascript">
$(document).ready(function() {
$("#primary").change(function()
{
$.post("lib/ajax_load_job_detail.php",{ _primaryid_n:$(this).val() } ,function(data)
{
var string = data;
var partsArray = string.split('|');
$("#n_detail").fadeTo(200,0.1,function() //start fading the messagebox
{
$.each(partsArray, function(index) {
$("#n_detail").html(partsArray[index]+"<br />").addClass('jText').fadeTo(900,1);
});
});
});
});
});
Sample value of array partsArray[0]12/12/2005, partsArray[1]This is a sample note from December, etc...
partsArray.length
will give you the items in the array. You can loop either with
for(var i=0;i<partsArray.length;i++){
or using the jquery addon
$.forEach
If you are iterating through an array then you could use the jQuery function each().
Here's a link to the docs: http://api.jquery.com/jQuery.each/
Here's a sample from the docs using your array:
$.each(partsArray, function(index, value) {
alert(index + ': ' + value);
});
EDIT - based on a comment the OP added to another answer, here's a better example using the OPs code:
$.each(partsArray, function(index, value) {
value.addClass('jText').fadeTo(900,1);
});
EDIT 2 - you need the part of the code that is per element of the arry inside the loop and based on your edits I think it should look like this:
$.each(partsArray, function(index) {
$(this).append(partsArray[index]+"br />").addClass('jText').fadeTo(900,1);
}
Cheers,
James
Here is a typical loop structure:
var partsArray = string.split('|');
for(var x=0;x<partsArray.length;x++) {
//...your code ...
//x is the index., so partsArray[x] is the current element
}
Use for ... in, it's significantly faster than jQuery's $.each method, and isn't much different - it provides you with the index of the item in i, rather than the value.
for (var i in partsArray)
{
// You can access values via...
console.log( partsArray[i] );
// Alternatively, this will make it an exact clone of $.each
var value = partsArray[i];
console.log( value );
}