It's possible I'm just misusing .filter() here, but I've been trying to extract a particular piece of text from javascript option boxes without much success.
In short, each of my option boxes has a bunch of info, then, in brackets, ([x] items left in stock).
I'd like to extract that [x], but I can't seem to get any sort of regular expression filtering working in jQuery - or, perhaps, I'm doing it wrong.
In short, if anyone could complete the below, I'd be very appreciative:
$('.productSelect').change(function() {
selectedItem = $(this + 'option:selected').text();
# Now grab the integer "x" inside the ([x] items left in stock) part of the text
[ your code here]
});
Any help very appreciated.
Something along these lines:
$('.productSelect').change(function() {
selectedItem = $(this + 'option:selected').text();
# Now grab the integer "x" inside the ([x] items left in stock) part of the text
var n = selectedItem.match(/(\()(\d+)(\))/)[2];
});
Of course, this expression depends on the fact that your data is formatted as (number) string
This should get you what you need.
var pattern=/\[(\d+)\] items left in stock/;
var qty = pattern.exec(selectedItem)[1];
So you should use the JavaScript string.match function
var s = "[100] items left in stock";
var p = s.match(regexp);
Related
i'm trying to live edit a text box value so that the result will be split every two character,
adding a column and starting from some default character.
what i have till now is this code, that obviously doesn't work:
$('#textboxtext').keyup(function (){
var text = $("#textboxtext").val();
//$(text).attr('maxlength', '12');
var splitted = text.match(/.{2}|.{1,2}/g);
var result = ("B8:27:EB:" + splitted.join(':'));
});
i need the live split and the default character inside the textbox but i really don't know where to start...
From your code, it seems like you're trying to create a text box that has some very specific behavior. It looks like it needs to format its value in such a way that it always begins with certain 'prefix' of B8:27:EB:, and every subsequent pair of characters is is separated by a :. This is actually a very complex behavior and you have to consider a number of different interactions (e.g. what happens when the user attempts to delete or modify the prefix). I usually try to avoid such complex controls if possible, however here is a quick implementation:
$('#textboxtext').keyup(function (e){
var prefix = "B8:27:EB:",
text = $(this).val(),
splitted, result;
if (text.indexOf(prefix) == 0)
text = text.substr(9);
else if (prefix.indexOf(text) == 0)
text = "";
text = text.replace(/:/g, '');
splitted = text.match(/.{1,2}/g) || [];
result = prefix + splitted.join(':');
$(this).val(result);
});
Demonstration
Type inside the text box and see what happens. Also note, there are all kinds of interaction that this implementation doesn't account for (e.g. right-clicking and pasting into the text box), but it's a start.
This should be pretty simple. I'm trying to use the slice method to remove the last two characters in a dynamically created string in a shopping cart.
So instead of having a product show as $28.00, I want the product to show up as $28. Since these values are coming from a database, I can't simply define the string in a variable, like I've seen in a lot of tutorials.
I've created a JSFiddle here:
http://jsfiddle.net/EbckS/
The jQuery that's not working is below:
$(".myclass").slice(0,-2);
You should use text.
$(".slice").text(function(i, text) {
return text.slice(0, -2);
});
i Reffers the index position of the element in the set
text Reffers the old text value
Refference
Very Simple. I uses this for getting number from a string you can use it too.
var height= "800px";
var newheight = height.substring(0,height.length-2); //string 800
newheight= parseFloat(newheight) || 0; //number 800
I have a table with 3 columns (contact person, sector, phone#) each sector cell would contain a lot of data numbers in range like these: (exact format without quote)
"1003, 1005-29/36/38/49, 4587-99, 3301/21, 50123, 9900-04/10-14/20/30/41-44"
Is there a way to add a filter (textbox) to the webpage for a quick look-up?
Example, if I type "9912" --> it will find the string: "9900-04/10-14/20/30/41-44" and highlight it.
note: I have no control over the table (there is no id/class for that column or entire table), searching the entire webpage will be ok, there is no duplicate info elsewhere.
Can someone point me to a good direction? jQuery?
jQuery will help you with the interaction for the textbox, but for processing the strings and extracting the data (i.e. which integers they match) you will need some heavy processing (using regular expressions, String.indexOf() and some loops). It's probably best to do all this processing on page load and cache the results somewhere, but depending on how many strings there are to process, this could lock up the user interface for a while, but assuming this isn't a problem then code a bit like this would do the job of highlighting the correct results
var dataCache = {};
$(selector to collect all your strings).each(function() {
var string = $(this).html();
var matches = yourParserWhichreturnsAnArrayOfIntegers(string);
for(var i = 0, il = matches.length;i<il;i++) {
if(dataCache[matches[i]]) {
dataCache[matches[i]].push(this);
} else {
dataCache[matches[i]] = [this];
}
}
});
$(yourtextbox).change(function() {
$(selector to collect all your strings).removeClass("highlighted");
var matches = dataCache[$(this).val()];
if (matches) {
for(var i=0,il=matches.length;i<il;i++){
$(matches[i]).addClass("highlighted");
}
}
});
If the table appears in the same location within the DOM everytime then you can still get at the data. If this is the case I think you will have to search in the expanded numbers. A regular expression for searching the compressed number format will probably be very complicated. Don't forget to keep a reference to the original data on the page so you can highlight it if a match is found.
Considering features like EditArea's and CodeMirror's autocomplete, I was wondering if, like Dreamweaver, there is a way to detect if the last word you entered is in a certain list then provide the same kind of suggestion box but with the function's arguments. I imagine you would use a regular expression on the entire field or possibly split() the whole thing (or the current line) then use the length attribute of the array to find the last bit of text, then do something involving an indexOf-like operation; however, this seems like it would get a bit resource-intensive. It almost looks like I've answered my own question, but it always helps to fully explain one's quandary, especially publicly. There's gotta be a better solution than mine. I appreciate any input. Thank you.
Put the list of words to match in an object, have the text or options to display as the value. Then on keyup or keypress you can get the last word of the text area using a function like:
function showLastWord(id){
var el = document.getElementById(id);
var lastWord = el.value.match(/\w+$/);
return lastWord? lastWord[0] : '';
}
Then check if the word is in the list and do stuff appropriately.
Edit
A small example is:
<textarea onkeyup="showHelp(this);"></textarea>
<script>
var getLastWord = (function() {
re = /\w+$/;
return function (s){
var lastWord = s.match(re);
return lastWord? lastWord[0] : '';
}
}());
var keyWords = {foo:'foo was typed',bar:'bar was typed'};
function showHelp(el) {
var lastWord = getLastWord(el.value);
// Check for matching own property of keyWords
if (keyWords.hasOwnProperty(lastWord)) {
// Do stuff
console.log(keyWords[lastWord]);
}
}
I have some lines of HTML code that are like this:
<li>Testing jQuery [First Bracket]</li>
<li>Loving jQuery [Second one]</li>
I'm trying to replace what's inside the bracket with nothing onLoad, like this:
var item = $(".lstItem").text();
var match = item.match(/\[(.*?)\]/);
item = item.replace(match[0], "");
But nothing changes. What's wrong and how to correct this?
After using jimbojw's suggestion I'm getting a Uncaught ReferenceError: text is not defined at this particular line:
oldtext = $item.text,
item is a variable containing a string, not a pointer to the literal text. If you want to change the text, you have to set it again, vis a vis $(".listItem").text(item)
edit - predicting next problem
The next problem you're going to have is that all the text gets set to the same thing. So what you really want to do is probably something like this:
$(".lstItem")
.each(function(index, item) {
var
$item = $(item),
oldtext = $item.text(),
match = oldtext.match(/\[(.*?)\]/),
newtext = oldtext.replace(match[0], '');
$item.text(newtext);
});
this will do the job for you:
you are splitting your code in too much lines, also your need to run replace for each individual element separately.
$(".lstItem").each(function() {
$(this).html(
$(this).html().replace(/\[(.*)\]/, "")
);
});
see your example in jsFiddle: http://jsfiddle.net/eKn3Q/7/
Along with jimbojw's answer $(".lstItem").text() will retrieve all the text inside of your <a/> elements. One way to handle this would be to pass a function(i,t){} into the .text() method.
$(".lstItem").text(function(i, text){
var match = text.match(/\[(.*?)\]/);
return text.replace(match[0], "");
});
Simple example on jsfiddle
also your regex could be simpler.
var item = $(".lstItem").text();
var match = /\[(.*?)\]/;
$(".listItem").text(item.replace(match,""));