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);
});
Related
I have this little piece of code that filters through a list of results and hides the divs that don't match. I am writing this for a PhoneGap iOS application. It works fine on Android, but on iOS for some reason it hides the entire search field as well after typing a few characters, not just the results.
Any idea why? I've stripped it down to almost only the HTML code and jQuery and it's still happening. I tried commenting out the $(this).hide(); part and it stops hiding the search field, so I assume somehow that's the culprit, but I can't figure out why or how to fix this. Been at it for 10 hours straight. Any ideas? Maybe I can target the results some other way?
$('#box_search').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis == "") {
$('#listing-results > .listing_container').show();
} else {
$('#listing-results > .listing_container').each(function() {
var text = ($(this).find('.listing_results_text_name').text() + $(this).find('.listing_results_text_name').data("alt")).toLowerCase();
if (text.indexOf(valThis) >= 0) {
$(this).show();
} else {
$(this).hide();
}
});
};
});
obviously I cant see the html but sometimes it helps to clean the code and just change the logic slightly
var box_search = function(e){
var myIndex = $(this).val();
val = (!myIndex || myIndex==='')?false:myIndex;
if(!myIndex){
$('#listing-results > .listing_container').show();
return;
}
//
$('#listing-results > .listing_container').each(function() {
var text = $(this).find('.listing_results_text_name').text() +
$(this).find('.listing_results_text_name').data("alt")
text = (!text || text==='')?false:text;
text = text.toLowerCase();
if(text.indexOf(myIndex.toLowerCase()) >= 0){
$(this).show();
return;
}
$(this).hide();
});
} //end of function
$('.box_search').keyup(box_search);
I am doing some easy div filtering with jQuery and input field. It is working, however it is not detecting that it is empty if I remove input using " Ctrl + a + backspace ", in other words if I select all text and remove it. What causes this?
It is not reordering divs back to default if using the keyboard commands but is going back to normal if you backspace every character.
This is how I do it:
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
$('.card').show();
} else {
$('.card').each(function() {
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).parent().show(): $(this).parent().hide();
});
};
});
Your if block that handles the empty string is not showing the same elements that the else block hides. The else block calls .parent() but the if block does not.
So the else case shows or hides the parent of each .card element, but the if case shows the .card elements themselves—without unhiding their parents. See my comments added to the code (I also reformatted the conditional expression in the else for clarity):
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
// Show all of the .card elements
$('.card').show();
} else {
$('.card').each(function() {
var text = $(this).text().toLowerCase();
// Show or hide the *parent* of this .card element
text.indexOf(valThis) >= 0 ?
$(this).parent().show() :
$(this).parent().hide();
});
};
});
Since it sounds like the non-empty-string case is working correctly, it should just be a matter of adding .parent() in the if block so it matches the others:
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
// Show the parent of each .card element
$('.card').parent().show();
} else {
// Show or hide the parent of each .card element
$('.card').each(function() {
var text = $(this).text().toLowerCase();
text.indexOf(valThis) >= 0 ?
$(this).parent().show() :
$(this).parent().hide();
});
};
});
This is the kind of situation where familiarity with your browser's debugging tools would pay off big time. The .show() or .hide() methods manipulate the DOM, and by using the DOM inspector you could easily see which elements are being hidden and shown.
In fact, as a learning exercise I recommend un-fixing the bug temporarily by going back to your original code, and then open the DOM inspector and see how it reveals the problem. While you're there, also try out the JavaScript debugger and other tools.
If you use Chrome, here's an introduction to the Chrome Developer Tools. Other browsers have similar tools and documentation for them.
It seems to be working just fine:
$('#brandSearch').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis.length == 0) {
$('.card').show();
console.log("input is empty");
} else {
console.log("input is not empty");
$('.card').each(function() {
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).parent().show(): $(this).parent().hide();
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="brandSearch">
What is the best way cross-browser to trim an element innerHTML?
jsFiddle: http://jsfiddle.net/6hk8z/
I am assuming you are getting confused with the html code that is not whitespace but merely rendered as such by the browser. See customised implementation below:
String.prototype.trimmed = function(){
return this.replace(
/^(\s| |<br\s*\/?>)+?|(\s| |<br\s*\/?>)+?$/ig, ' '
).trim();
}
updated jsFiddle
Use the DOM, not innerHTML which you would need to parse.
function trimContents(element) {
function iterate(start, sibling, reg) {
for(var next, c = element[start]; c != null; c=next) {
next = c[sibling];
if (c.nodeType == 1 && c.nodeName.toLowerCase() == "br"
|| c.nodeType == 3 && !(c.nodeValue = c.nodeValue.replace(reg, "")))
element.removeChild(c);
else
break;
}
}
iterate("firstChild", "nextSibling", /^\s+/);
iterate("lastChild", "previousSibling", /\s+$/);
}
(demo at jsfiddle.net)
Have you tried jQuery's $.trim()? See jQuery documentation for more details.
$('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?
With jQuery I am trying to determine whether or not <div> has content in it or, if it does then I want do nothing, but if doesn't then I want to add display:none to it or .hide(). Below is what I have come up with,
if ($('#left-content:contains("")').length <= 0) {
$("#left-content").css({'display':'none'});
}
This does not work at all, if the div has not content then it just shows up anyway, can any offer any advice?
Just use the :empty filter in your selectors.
$('#left-content:empty').hide();
if( $( "#left-content" ).html().length == 0 ) {
$( "#left-content" ).hide();
}
try to remove first whitespaces:
// first remove whitespaces
// html objects content version:
var content = $.trim($("#left-content).html()).length;
if(content == 0) {
$("#left-content).hide();
}
// html RAW content version:
var content = $.trim($("#left-content).html()); // <-- same but without length
if(content == "") { // <-- this == ""
$("#left-content).hide();
}