I have a jScript function to text search an element in drop down. It used to work fine till ie7. I have a workaround that works cross browsers but is slow in ie7 using jQuery option:contains instead of Regex.
Function:
/// For the dropdown element passed, find the index where the Text matches the passes string
/// and select this option. Returns true if found otherwise false
function selectTextinDropdown(el, sometext) {
// Use REgex instead of option:contains as it it much faster!
$(el).find("option:[text^='" + sometext.trim() + "']").each(function () {
// works ok but SLOW in IE 7!!
// $(el).find("option:contains('" + sometext.trim() + "')").each(function () {
//alert("found|" + this.text + "|" + sometext);
$(this).attr("selected", "selected");
if ($(this).text() == sometext) {
$(this).attr("selected", "selected");
return true; //found and selected!
}
return false; //Not found and Not selected!
});
}
Anybody familiar with a better workaround?
tks for reading!
Try this:
function selectTextinDropdown(selectEle, targetText) {
if(targetText==null){
return false;
}
targetText = targetText.trim();
// Find all options that meet your condition
var $matches = $(selectEle).find('option').filter(function(index){
// only use jquery selector once
var $this = $(this);
// extract text from the option
var text= $this.text();
// determine if it's found
// OPTION A: exact match
var found = (text === targetText);
// OPTION B: partial match
// var found = (text.indexOf(targetText) >= 0);
if(found){ // select item if found
$this.attr("selected", "selected");
}
return found;
});
return ($matches!=null && $matches.length>0);
}
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 trying to search the contents using jquery. Search option working fine. But, I have faced some case insensitive problem here. My full codes on jsfiddle. if i put senthil in my search it didn't show the result. Because, I have Senthil (Uppercase S) in my content. How do I find Uppercase letters in jquery?
JsFiddle
$('#search').on('input', function(){
var text = $(this).val();
$('.subjects a').show();
$('.subjects a:not(:contains(' + text + '))').hide();
$('.subjects a span').show();
});
You can use a custom expression for contains like this:
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
Updated Fiddle
Add this code to your JS code
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
Credits Here
Sorry for the horrible title, Am terrible at wording these things.
What I am trying to do is quite simple I think.
I have a set of hidden letters that make up a word.
Below them is a selection of random jumbled up letters.
When people click one of the random jumbled letters I am filtering through the hidden letters and showing the corresponding letter.
What I need to do is, if someone clicks a letter, filter through the hidden letters and either return a "true" and show the letter or return a "false/null" and make an alert();
This is how I am filtering at the moment. I am confused as to where to place an if statement or if that is even the approach I should be taking.
And here is a fiddle (the hidden word is "Seal") - http://jsfiddle.net/GA7WB/
var $buttons = $('#letters span'),
$hidden = $('.letter');
$buttons.click(function(){
_selected = $(this).html();
$hidden.filter(function() {
return $(this).text() == _selected;
}).show();
});
You just need to check the length of the results returned by the filter:
// get matched elements
var matches = $hidden.filter(function() {
return $(this).text() == _selected;
});
// show them, or alert if none
if (matches.length > 0) matches.show();
else alert("There are no " + _selected + "'s");
See Fiddle
Try setting a flag if you find one:
var $buttons = $('#letters span'),
var $hidden = $('.letter');
$buttons.click(function(){
_selected = $(this).html();
var foundOne = false;
$hidden.filter(function() {
var retval = $(this).text() == _selected;
if (retval) foundOne = true;
return retval;
}).show();
if (!foundOne) {
alert("Nope");
}
});
FIDDLE http://jsfiddle.net/GA7WB/4/
$('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?
I am trying to implement tagging just like what facebook does with #friendname. I have a textarea and I wanted to detect when a user typed in #. How do I do so using a keyup listener? Is it possible to get the entered text using keyup? Here's what I have now
$("#recommendTextArea").keyup(function () {
var content = $(this).val(); //content Box Data
var go = content.match(start); //content Matching #
var name = content.match(word); //content Matching #friendname
console.log(content[content.length-1]);
//If # available
if(go.length > 0)
{
//if #abc avalable
if(name.length > 0)
{
//do something here
}
}
});
Most importantly what I need is the index of the'#' that the user just entered.
LINK
(function ($, undefined) {
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
} else if('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
$("#recommendTextArea").on('keypress', function(e){
var key = String.fromCharCode(e.which);
if(key === '*') {
var position = $(this).getCursorPosition();
alert(position); // It is the position
alert($(this).val()); // This is the value
}
});
I made some changes HERE.
To detect a #, you'd do something like :
$("#recommendTextArea").keyup(function (e) {
if (e.which===50) {
alert('you typed #');
}
});
and this.value get's you whatever is typed into the textarea, and you'll need a regex to get what's between # and the first following space, or something similar depending on how you intend to do this ?
To get a name, you can do something like this :
var _name = false;
$("#recommendTextArea").keyup(function (e) {
if (_name) {
$('#name').text('name : ' + this.value.substring( this.value.lastIndexOf('#') ) )
}
if (e.which === 50) {
_name = true;
}
if (e.which === 32) {
_name = false;
}
});
FIDDLE
This is just a quick demo, building something that always works and accounts for every possible outcome will be a lot more work than this.
EDIT:
Most importantly what I need is the index of the'#' that the user just
entered.
that would be this.value.lastIndexOf('#')
EDIT AGAIN:
To get the names typed in the textarea regardless of cursor position, number of names etc. you'll have to use a regex, here's a quick example that gets all and any names typed in, as long as they start with a #, and ends with a blank space :
$("#recommendTextArea").keyup(function (e) {
var names = this.value.match(/#(.*?)\s/g);
$('#name').html('names typed : <br/><br/>' + names.join('<br/>'));
});
FIDDLE