Selecting, Deleting jQuery based on wildcard - javascript

What I would like is if there is NOT a word "link" in the href "www.1link.com" all the top classes 1-6 is changed to classdefault.
Also a different code that does the same thing except of adding "defaultclass" it removes all the classes 1-6 empty.
This is what I've tried so far and it hasn't worked
http://jsfiddle.net/yLxXn/2/
$(document).ready(function() {
if ($('a[href$="link"]')) {
// do something here
$("[class^=content]").attr("class", "classdefault");
}
});

Try something like this :
if ($('a').attr('href').indexOf('link') != -1) {
// other code
}

UPDATE
If you want this to happen if it does not contain "link", change >= to <=. As following:
For replacing all classes:
$('div').find('a').each(function(){
var hrefString = $(this).attr('href');
if (hrefString.indexOf("link") <= 0){
$('[class^=class]').attr('class', 'classdefault');
}
});
For removing all classes:
$('div').find('a').each(function(){
var hrefString = $(this).attr('href');
if (hrefString.indexOf("link") <= 0){
$('[class^=class]').removeClass();
}
});

Related

Utilizing jQuery Selectors to simplify HTML parser code

This code uses jQuery find() and several if statements to pick out certain text from an HTML document.
I'm trying to remove the if statements and interpret them to jQuery selectors in find(), at the very top line of code. Is this possible? If so, what would the selectors need to be?
$(document).find("a[href^='http://fakeURL.com/']").each(function()
{
var title = $(this).text();
var url = $(this).attr('href');
if(title.indexOf('Re: ') != 0)
{
if($(this).parent().attr('class') != 'quoteheader')
{
if(url.indexOf('topic') == 36)
{
if($(this).parent().attr('class') == 'middletext')
{
console.log(title);
}
}
}
}
});
For the last thing I left, you want to check if the topic is at index 36 ? not sure its possible via the selector, beside that everything went up to the selector (code not tested, should work tho)
$(document).find(".middletext:not(.quoteheader) > a[href^='http://fakeURL.com/']").each(function()
{
if(url.indexOf('topic') != 36)
return;
var title = $(this).text();
if(title.indexOf('Re: ') != 0)
return;
console.log(title);
});

Remove only second character in jQuery

$('input').keypress(function(e){
if(($(this).val().split('a').length - 1) > 0){
console.log($('input').val());
$('input').val($('input').val().replace('a', ''));
}
})
jsfiddle: http://jsfiddle.net/Ht8rU/
I want have only one "a" in input. I check if length a > 1 and next remove "a" from input, but this not working good. I would like remove only second a from this input. One "a" is allow.
Edit: Oh I see now... If you want to keep only the first a you can try this:
$('input').keypress(function(e) {
var key = String.fromCharCode(e.which);
if (/a/i.test(key) && /a+/i.test(this.value)) {
e.preventDefault();
}
});
Demo: http://jsfiddle.net/elclanrs/Ht8rU/6/
You have to check if the current letter being typed is a:
if (String.fromCharCode(e.which) == 'a')
But here's a simplified version. You don't need to use val() if you can use value, specially because it makes your code cleaner. Also you might want to check for A or a so a regex might be a better option. Here's the code:
$('input').keypress(function(e) {
var A = /a/gi,
letter = String.fromCharCode(e.which);
if (A.test(letter)) {
$(this).val(this.value.replace(A,''));
}
});
Demo: http://jsfiddle.net/elclanrs/Ht8rU/3/
I suggest using preventDefault to stop the key from being pressed:
$('input').keypress(function(e) {
if (e.keyCode === 97 && $(this).val().split('a').length > 1) {
e.preventDefault();
}
});
JSFiddle
This code may seem long and without any usefulness, but it works.
$('input').keyup(function(e) {
var e = $(this),
val = e.val(),
aPos = val.indexOf('a'),
spl1 = val.substring(0, aPos + 1),
spl2 = val.substring(aPos, val.length).replace(/a/gi, ''),
v = spl1 + spl2;
e.val(v);
});
Here is a working JSFiddle of this.
I would try something like this. Not sure how well supported is the input event currently, though.
(function() {
var elem = $('input');
var value = elem.val();
elem.bind("input propertychange", function(e) {
if (elem.val().split('a').length - 1 > 1)
elem.val(value);
else
value = elem.val();
});
})();
http://jsfiddle.net/Ht8rU/8/
When the user presses 'a' or 'A', you can check if there is one 'a' or 'A' already present, if there is one already then you don't add it to the input.
$('input').keypress(function(e){
if ((e.keyCode === 65 || e.keyCode === 97) & $(this).val().match(/a/gi) !== null) e.preventDefault();
})
Updated jsFiddle
Here's a modified version of your fiddle that works: http://jsfiddle.net/orlenko/zmebS/2/
$('input').keypress(function(e){
var that = $(this);
var parts = that.val().split('a');
if (parts.length > 2) {
parts.splice(1, 0, 'a');
that.val(parts.join(''));
} else {
// no need to replace
}
})
Note that we only replace the contents of the input if we have to - otherwise, constant rewriting of the contents will make it impossible to type in the midle or at the beginning of the text.
If you want to further improve it and make it possible to type at the beginning even when we are replacing the contents, check out this question about detecting and restoring selection: How to get selected text/caret position of an input that doesn't have focus?

hasClass doesn't function as it should

I have a list of li items and would like to trigger a button click if 2 classes are found.
When a list item has 2 classes, I would like to trigger the btn with a click. Can you guys take a look for me?
The code:
<script type="text/javascript">
$(document).ready(function(){
var $html = $("#my-div ul li");
if ($html.hasClass("current") || $html.hasClass("extra")) {
$(".btn-1 a").click();}
else if ($html.hasClass("current") || $html.hasClass("extra2")) {
$(".btn-2 a").click();}
});
</script>
So one list item has class current + extra, and the other list item hasClass current + extra2.
Any idea what I am doing wrong here?
EDIT: Currently it does not work as should be.
It currently will always trigger ".btn-1" to click and does not look at the other statements. I think it just looks at the "current" class and not if also the "extra" or "extra2" class is in the same li item.
Try this:
<script type="text/javascript">
$(document).ready(function(){
var $html = $("#my-div ul li.current");
if ($html.hasClass("extra")) {
$(".btn-1 a a").click();}
else if ($html.hasClass("extra2")) {
$(".btn-2 a").click();}
});
</script>
The problem is, when you do $html.hasClass("current") || .. it would always evalutate to true and would not go to the else clause when node has a class current
You are making a comparison of a or b where you need a and b so change it to this:
<script type="text/javascript">
$(document).ready(function(){
var $html = $("#my-div ul li");
if ($html.hasClass("current") && $html.hasClass("extra")) {
$(".btn-1 a a").click();}
else if ($html.hasClass("current") && $html.hasClass("extra2")) {
$(".btn-2 a").click();}
});
</script>
Try replacing
$html.hasClass("current") || $html.hasClass("extra")
with
$html.hasClass("current") && $html.hasClass("extra")
and also
$html.hasClass("current") || $html.hasClass("extra2")
with
$html.hasClass("current") && $html.hasClass("extra2")
The original root of the problem is that you're using or (||) and not and (&&) when testing for classes. You're asking "if li has class current OR extra".
However, you can also refactor it a bit and make it a little cleaner as well:
// first, grab the <li> marked as current
var $current = $('#my-div ul li.current');
// test if we have a match and proceed
if ($current.size()){
// cache the final target selector (by initializing it to `false` we
// can later test and only execute the click when we have a match)
var target = false;
// now get in to second-level classes (can use either `.is()` or
// `.hasClass()` (thought I'd show an alternative method as well))
if ($current.hasClass('.extra')) target = '.btn-1 a a';
else if ($current.hasClass('.extra2')) target = '.btn-2 a';
// else if ($current.hasClass('...')) target = '...'; // more tests
// see if we found a match and click it
if (target) $(target).click();
}

jQuery - Check if the tag's content is equal to sometext then do something

Let's say I have many of these in my content div : <cite class="fn">blabla</cite>
How can I check every cite tag's content (in this case: blabla) with class fn to see if it equals to "sometext" then change it's color to red ?
Very simple.
$('cite.fn:contains(blabla)').css('color', 'red');
Edit: though that will match "blablablabla" as well.
$('cite.fn').each(function () {
if ($(this).text() == 'blabla') {
$(this).css('color', 'red');
}
});
That should be more accurate.
Edit: Actually, I think bazmegakapa's solution is more elegant:
$('cite.fn').filter(function () {
return $(this).text() == 'blabla';
}).css('color', 'red');;
You can make use of the amazing .filter() method. It can take a function as its parameter, which will reduce the jQuery collection's elements to those that pass its test (for which the function returns true). After that you can easily run commands on the remaining elements:
var searchText = 'blabla';
$('cite.fn').filter(function () {
return $(this).text() === searchText;
}).css('color', 'red');
jsFiddle Demo
You could potentially do something like:
$('cite.fn').each(function() {
var el = $(this);
if (el.text() === 'sometext') {
el.css({ 'color' : 'red' });
}
});
This fires a function against each cite that has the class fn. That function checks if the current cite's value is equal to 'sometext'.
If it is, then we change the CSS color (text-color) property to red.
Note I'm using jQuery in this example, as you've specifically tagged your question jQuery. Ignore the downvote, this was applied before I edited a typo that I'd made (el.val() rather than el.text())
Without jQuery:
var elms = document.querySelectorAll("cite.fn"), l = elms.length, i;
for( i=0; i<l; i++) {
if( (elms[i].innerText || elms[i].textContent) == "blabla") {
elms[i].style.color = "red";
}
}

Problem removing input from form after adding

so I have got my form successfully adding a new input on the click of a button. However now I want to be able to remove that last addition on the click of a new button and then also feature a reset button.
this was the code I had in place, which I realise now just removes the submit button first, which obviously I dont want.
here is my javascript snippet: (note ive included the appendTo() to demonstrate the div I am successfully appending to)
$(function() {
var i = $('input').size('#temp') + 1;
$('a#add').click(function() {
$('<input type="text" value="user' + i + '" />').appendTo('#temp');
i++;
});
$('a#remove').click(function() {
if(i > 3) {
$('input:last').remove();
i--;
}
});
many thanks,
Your script will remove the last input from the page, not the last one from the div with id temp. Maybe you are removing another input from your page.
Try this:
$('a#remove').click(function() {
if(i > 3) {
$('#temp input:last').remove();
i--;
}
});
Edit:
You only close the $('a#remove').click() event handler, not the anonymous function. That may be a copy/paste error here, but may also be a problem in your code.
Edit 2:
To remove all but the original, I would recommend keeping a reference to all added inputs, as this reduces the need to traverse the DOM for each remove. So do something like this (This code is neither tested nor verified):
$(function() {
var addedInputs = [];
$('a#add').click(function() {
var newInput = $('<input type="text" value="user' + i + '" ">').appendTo('#temp');
addedInputs.push(newInput);
});
$('a#remove').click(function() {
var inputToRemove = addedInputs.pop();
inputToRemove.remove();
});
$('a#clear').click(function() {
var i,
inputToRemove;
for(i = addedInputs.length - 1;i >= 0; i -=1) {
inputToRemove = addedInputs[i];
inputToRemove.remove();
}
addedInputs = [];
});
});
Have you tried :
$("a#remove").click(function() {
if(i > 3) {
$("input[type='text']").last().remove();
i--;
}
});
This will select the inputs having type="text", take the last one and remove it.

Categories

Resources