I have a function in my code that I need to modify links in my page, it looks something like this:
$('a').each(function(){
// code here related to HREF attr
});
$('form').each(function(){
// Code relate to the TARGET attr
});
I need to apply this function on all the links and targets of forms pointing to some specific domains. Let's say I have a list like this one: www.example.com,www.domain.com,www.anotherdomain.com
How can I modify the selector in a way it could apply it only to links and form pionting to the domains in the list?
You can use .filter:
var $exampleComLinks = $('a').filter(function() {
return this.href.indexOf('https://example.com') == 0
|| this.href.indexOf('https://example2.com') == 0
|| this.href.indexOf('https://example3.com') == 0;
});
Or simple if statement:
$('a').each(function() {
if (this.href.indexOf('https://example.com') == 0
|| this.href.indexOf('https://example2.com') == 0
|| this.href.indexOf('https://example3.com') == 0) {
console.log('do something this $(this)');
}
});
Using #Praveen Kumar's domainList approach:
var domainsList = ["www.example.com", "www.domain.com", "www.anotherdomain.com"];
$('a').each(function () {
if (domainsList.indexOf($(this).attr("href").replace(/https?:\/\/([^\/]*).*/gi, "$1")) > -1)
// Do it.
});
$('form').each(function () {
// Code relate to the TARGET attr
if (domainsList.indexOf($(this).attr("href").replace(/https?:\/\/([^\/]*).*/gi, "$1")) > -1)
// Do it.
});
If the targets are site url I suggest to add http:// or https:// and then (elsewhere you have to remove http:// from attr("target") or href when comparing.):
var domains="http://www.example.com,http://www.domain.com,http://www.anotherdomain.com";
$('a').each(function(){
if (domains.indexOf($(this).attr("href")) > -1)
});
$('form').each(function(){
if (domains.indexOf($(this).attr("target")) > -1)
});
You can use new RegExp() with parameter array list joined with separator "|", RegExp.prototype.test()
var list = ["www.example.com","www.domain.com","www.anotherdomain.com"];
$("a, form").each(function(i, el) {
if (new RegExp(list.join("|")).test(this.href || this.target)) {
// do stuff
}
})
jsfiddle https://jsfiddle.net/xkjpxd6L/
Related
I'm looking for a way to rewrite URL of the location when the user want's to change page. So, let's say you have something like this:
<body>
<a href="http://example.com" />
</body>
Is there a way I can catch URL changing moment, and actually modify that URL before location is changed, for example I would like to change href into relative link like \http://example.com and redirect page actually there.
If you just want to trap the link and then modify it then yes, that's quite simple...
$("a").on("click", function(e) {
e.preventDefault(); // stops the link doing its default thing
window.location.href = "something/" + $(this).attr("href");
});
You obviously need to modify the line that changes the location, so that it modifies the href value however you need. I'd also recommend giving the links a class and selecting them with that, as the above code will affect every link on the page.
Finally, this will need to run after the DOM is loaded, so either wrap it in a document.ready handler of your choice, or put it in a script at the bottom of the body.
Demo
You can work from here. Also you will need urlrewrite in htaccess for this to work properly.
$(function () {
$('.buttonn').on('click', function (e) {
var seperator = (window.location.href.indexOf("?") === -1) ? "?" : "&";
if (window.location.href.indexOf("s1") === -1 && window.location.href.indexOf("s2") != -1) {
window.location.href = window.location.href.replace(/&?s2=([^&]$|[^&]*)/i, "&s1=s1");
} else if (window.location.href.indexOf("s1") != -1) {
window.location.href = window.location.href.replace(/&?s1=([^&]$|[^&]*)/i, "&s1=s1");
} else {
window.location.href = window.location.href + seperator + "s1=s1";
}
});
});
$(function () {
$('.buttono').on('click', function (e) {
var seperator = (window.location.href.indexOf("?") === -1) ? "?" : "&";
if (window.location.href.indexOf("s2") === -1 && window.location.href.indexOf("s1") != -1) {
window.location.href = window.location.href.replace(/&?s1=([^&]$|[^&]*)/i, "&s2=s2");
} else if (window.location.href.indexOf("s2") != -1) {
window.location.href = window.location.href.replace(/&?s2=([^&]$|[^&]*)/i, "&s2=s2");
} else {
window.location.href = window.location.href + seperator + "s2=s2";
}
});
});
I have a class js-bootstrap3 that is generated by a cms. What I need to do is check if the containing element just has js-bootstrap3and .unwrap() the contents, but if the element has multiple classes which include js-bootstrap3 then I'm trying to just remove that class.
jsFiddle
$('.jsn-bootstrap3').each(function(){
if( $(this).attr('class') !== undefined && $(this).attr('class').match(/jsn-bootstrap3/) ) {
console.log("match");
$(this).contents().unwrap();
$(this).removeClass('jsn-bootstrap3');
}
});
This just seems to detect any element with js-bootstrap3as a class and unwraps it.
this.className is a string with all of the classes for the element (space delimited), so if it's not just "jsn-bootstrap3" you know it has more than one class:
$('.jsn-bootstrap3').each(function(){
if( $.trim(this.className) !== "jsn-bootstrap3") {
// Just jsn-bootstrap3
$(this).contents().unwrap();
} else {
// More than just jsn-bootstarp3
$(this).removeClass('jsn-bootstrap3');
}
});
Dependeing on the browsers you need to support element.classlist (IE10+) might or might not be what you need.
classList returns a token list of the class attribute of the element.
classList is a convenient alternative to accessing an element's list of classes as a space-delimited string via element.className. It contains the following methods:
Otherwise you're looking at splitting the className into an array like so to count the values:
var classes = element.className.split(" ");
Building on your example you could do something liket his:
$('.jsn-bootstrap3').each(function(i, el){
if( el.className.indexOf('jsn-bootstrap3') != -1 ) {
console.log("match");
if ( el.className.split(" ").length > 1 ) {
$(this).removeClass('jsn-bootstrap3');
} else {
$(this).contents().unwrap();
}
}
});
Try this code.
$(document).ready(function(){
$('.jsn-bootstrap3').each(function(){
var classes = $(this).attr('class');
var new_cls = classes.split(' ');
if( new_cls.length > 1 ){
$(this).removeClass('jsn-bootstrap3');
} else {
$(this).contents().unwrap();
}
});
});
I have the following structure:
<div id="campaignTags">
<div class="tags">Tag 1</div>
<div class="tags">Tag 2</div>
<div class="tags">Tag 3</div>
</div>
And I'm trying to match user input against the innerText of each children of #campaignTags
This is my latest attempt to match the nodes with user input jQuery code:
var value = "Tag 1";
$('#campaignTags').children().each(function(){
var $this = $(this);
if(value == $(this).context.innerText){
return;
}
The variable value is for demonstration purposes only.
A little bit more of context:
Each div.tags is added dynamically to div#campaignTags but I want to avoid duplicate values. In other words, if a user attempts to insert "Tag 1" once again, the function will exit.
Any help pointing to the right direction will be greatly appreciated!
EDIT
Here's a fiddle that I just created:
http://jsfiddle.net/TBzKf/2/
The lines related to this question are 153 - 155
I tried all the solutions, but the tag is still inserted, I guess it is because the return statement is just returning the latest function and the wrapper function.
Is there any way to work around this?
How about this:
var $taggedChild = $('#campaignTags').children().filter(function() {
return $(this).text() === value;
});
Here's a little demo, illustrating this approach in action:
But perhaps I'd use here an alternative approach, storing the tags within JS itself, and updating this hash when necessary. Something like this:
var $container = $('#campaignTags'),
$template = $('<div class="tags">'),
tagsUsed = {};
$.each($container.children(), function(_, el) {
tagsUsed[el.innerText || el.textContent] = true;
});
$('#tag').keyup(function(e) {
if (e.which === 13) {
var tag = $.trim(this.value);
if (! tagsUsed[tag]) {
$template.clone().text(tag).appendTo($container);
tagsUsed[tag] = true;
}
}
});
I used $.trim here for preprocessing the value, to prevent adding such tags as 'Tag 3 ', ' Tag 3' etc. With direct comparison ( === ) they would pass.
Demo.
I'd suggest:
$('#addTag').keyup(function (e) {
if (e.which === 13) {
var v = this.value,
exists = $('#campaignTags').children().filter(function () {
return $(this).text() === v;
}).length;
if (!exists) {
$('<div />', {
'class': 'tags',
'text': v
}).appendTo('#campaignTags');
}
}
});
JS Fiddle demo.
This is based on a number of assumptions, obviously:
You want to add unique new tags,
You want the user to enter the new tag in an input, and add on pressing enter
References:
appendTo().
filter().
keyup().
var value = "Tag 1";
$('#campaignTags').find('div.tags').each(function(){
if(value == $(this).text()){
alert('Please type something else');
}
});
you can user either .innerHTML or .text()
if(value === this.innerHTML){ // Pure JS
return;
}
OR
if(value === $this.text()){ // jQuery
return;
}
Not sure if it was a typo, but you were missing a close } and ). Use the jquery .text() method instead of innerText perhaps?
var value = "Tag 1";
$('#campaignTags').find(".tags").each(function(){
var content = $(this).text();
if(value === content){
return;
}
})
Here you go try this: Demo http://jsfiddle.net/3haLP/
Since most of the post above comes out with something here is another take on the solution :)
Also from my old answer: jquery - get text for element without children text
Hope it fits the need ':)' and add that justext function in your main customised Jquery lib
Code
jQuery.fn.justtext = function () {
return $(this).clone()
.children()
.remove()
.end()
.text();
};
$(document).ready(function () {
var value = "Tag 1";
$('#campaignTags').children().each(function () {
var $this = $(this);
if (value == $(this).justtext()) {
alert('Yep yo, return');)
return;
}
});
//
});
This is a known issue for iScroll and it only seems to happen in iOS5 where the menu completely stops working. All my sub links in iScroll are hash anchors. Does anyone have a workaround for this?
The way I handled it was to hijack the anchor links themselves and replace them with scrollToElement calls instead.
// Hijack hash anchors and scroll to them
$('a').click ( function (e) {
var id = $(this).attr('href');
if (id.substr(0,1) == '#') {
e.preventDefault();
setTimeout( function() {
scroller.scrollToElement ( id, 0 );
}, 0);
return false;
} else {
return true;
}
});
This code should only hijack links that begin with #. It then handles the scrollToElement in a setTimeout which fixes some other intermittent bugs. It works well on my end as long as your anchors are properly named with id's. If you are using name attributes instead of id attributes, you'll need to rewrite these.
This code will copy name attributes and put them in the id attribute if it is blank. You probably won't need this, though.
$('a').each (function (i, e) {
var n = $(e).attr('name');
var id = $(e).attr('id');
if ( typeof id == 'undefined' || id === null || id === '') {
$(e).attr('id', n);
}
});
I have a (very) basic validation script. I basically want to check for any inputs with class .required to see if there values are a) blank or b) 0 and if so, return false on my form submit. This code does not seem to return false:
function myValidation(){
if($(".required").val() == "" || $(".required").val() == 0){
$(this).css({ backgroundColor:'orange' }) ;
return false;
}
}
Appending this function to my onSubmit handler of my form is not returning any results. Any light shed on this matter will be appreciated.
I am basically after a function that iterates through all the inputs with class .required, and if ANY have blank or 0 values, return false on my submit and change the background colour of all badly behaved inputs to orange.
Your code currently gets the .val() for the first .required, from the .val() documentation:
Get the current value of the first element in the set of matched elements.
You need to filter through each one individually instead, like this:
function myValidation(){
var allGood = true;
$(".required").each(function() {
var val = $(this).val();
if(val == "" || val == 0) {
$(this).css({ backgroundColor:'orange' });
allGood = false;
}
});
return allGood;
}
Or a bit more compact version:
function myValidation(){
return $(".required").filter(function() {
var val = $(this).val();
return val == "" || val == 0;
}).css({ backgroundColor:'orange' }).length === 0;
}
Try this jQuery selector:
$('.required[value=""], .required[value=0]')
You could also do it by defining your own custom jQuery selector:
$(document).ready(function(){
$.extend($.expr[':'],{
textboxEmpty: function(el){
return ($(el).val() === "");
}
});
});
And then access them like this:
alert($('input.required:textboxEmpty').length); //alerts the number of input boxes in your selection
So you could put a .each on them:
$('input.required:textboxEmpty').each(function(){
//do stuff
});