i would like to have a sorting routine for 5 words to sort alphabetical (From A-Z and Z-A), what I came up with (with help from some sites) was this. (excuses, I couldn't post a screen capture due not enough rep)
Script:
Function Sorter(){
var routine=["Banana","Milkshake","Work","bladiebla","Progress"];
routine.sort();
(routine.reverse();) if possible
var x=document.GetElementById("demo");
x.innerHTML=routine;}
this works, and is set in work by a button (not in this code). however what i want is that i can fill in the words myself on my site. i have used prompt tags and input tags but they dont seem to work (when i do it).
could anyone please help me out with this.
what i would like: i would like to be able to use prompt tags (or input tags) to put the words in the array and then sort the words alphabetically A-Z and backwards Z-A.
if someone would want to help me out with this then i would like that,
thanks in advance, Dim
I assume that you want to add the value entered in input box into an array and list the values in asc/desc order. I have created the jsFiddle it might be helpful.
$('input').bind('keyup', function(e) {
if(e.keyCode == 13 && $.trim(this.value)) {
routine.push(this.value);
Sorter();
this.value = '';
}
});
var routine=["Banana","Milkshake","Work","bladiebla","Progress"];
function Sorter() {
routine.sort();
var x = document.getElementById("demo");
x.innerHTML = routine.join('<br>');
}
Sorter();
Related
I'm trying to write a function that validates number depending on the country. With each country, using intl-input, I obtain different class. Depending on that class inside the PrestaShop checkout module I am trying to implement the different amount of characters in phone input.
Result is something like this:
function validatePhoneNumber(s)
{
if ($('div').hasClass("opt216")) {
var reg = /^\+(?:[0-9] ?){10}$/;
}else {
var reg = /^\+(?:[0-9] ?){10,14}$/;
}
return reg.test(s);
}
What I have in this is every country has the same amount of characters (10) and if the statement doesn't seem to work. So, I thinking, is making this regex variable and changing it on if statement actually allowed?
Thanks everyone, I figured out what was wrong - i had few opt216 classes in document, so i went another way with attribute selection, something like that
if ($('#iti-item-216').attr('aria-selected') == 'true')
I have a web page with a form on it. The "submit" button is supposed to remain deactivated until the user fills in all the necessary fields. When they fill in a field, a checkmark appears next to it. When all the checkmarks are there, we're good to go.
A checkmark might be set by code like this:
if (whatever) checkLocation.innerHTML = CHECKMARK;
Here's the code I'm using to do the final check. It just loops through all the locations where there may be checkmarks. If it finds a location without a mark, it disables the submit button and leaves. If it gets through them all, it activates the button and returns true.
function checkSubmitButton() {
var button = document.getElementById(SUBMIT_BUTTON);
for (var i=0; i<CHECK_LOCATIONS.length; i++) { // should be for-each, but JS support is wonky
var element = document.getElementById(CHECK_LOCATIONS[i]);
console.log(CHECK_LOCATIONS[i] +": " +element.innerHTML);
// if found unchecked box, deactivate & leave
if (element.innerHTML != CHECKMARK) {
button.disabled = true;
return false;
}
}
// all true--activate!
console.log("ACTIVATING BUTTON!");
button.disabled = false;
return true;
}
Here's the problem: this works so long as the const CHECKMARK contains something simple, like "X". But specs call for a special HTML character to be used: in this case ✓, or ✓. When I do the comparison (in the if line) it ends up comparing the string "✓" to the string "✓". Since these two are not equal, it doesn't recognize a valid checkmark and the button never activates. How can I compare the contents of the HTML element my constant? (And hopefully make the code work even if down the road somebody replaces the checkmark with something else.)
Thanks.
There is no problem with the check character and it behaves exactly like the X character. The problem is, that your html have the checkmark character stored as html entity in hex string. If you compare checkmark to checkmark it works just fine: https://jsfiddle.net/m7yoh026/
What you can do in your case is to make sure the CHECKMARK variable is the actuall checkmark character, not the html entity.
Other option is to decode the html entity: https://jsfiddle.net/m7yoh026/3/
var CHECKMARK = '✓'
var decoded_checkmark = $('<textarea />').html(CHECKMARK).text();
console.log($('div')[0].innerHTML)
if ($('div')[0].innerHTML == decoded_checkmark) {
$('body').append('checkmark recognized<br>')
}
You can convert a character to its HTML entity equivalent like so:
var encoded = raw.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
Well, here's what I ended up doing: I made a function called encodeHtml() that takes a character or string, writes it to a brand new div, and then returns what's contained in that div:
function encodeHtml(character) {
var element = document.createElement("div");
element.innerHTML = character;
return element.innerHTML;
}
Then I can compare to what it returns, since it automatically changes "✓" to "✓", and will work with any unforeseen changes to that character. It's a bit of a kludge, but it works. (It's still not clear to me why JavaScript does this automatic conversion...but there are many design choices in which JavaScript mystifies me, so there you go.)
Thanks all for the help.
My first post on here. I have a function on a website whereby a randomly generated French phrase is displayed, challenging the reader to translate it into English in a text box. On clicking on a button, the text entered is compared to all the possible answers (there are multiple correct translations for a given phrase). I've looked around for answers on this but nothing seems to suit my situation.
Here's the jQuery:
var correctAnswer = function(){$('#correctmessage').show('fast');$('#errormessage').hide('fast');}
var wrongAnswer = function(){$('#errormessage').show('fast');$('#correctmessage').hide('fast');}
$('#1').find('button').on('click', function(){
var text = $(this).parent().find('.translatefield').val();
var compareText = "I went to the cinema";
var compareText2 = "I have been to the cinema";
if (text == compareText || text == compareText2) {
correctAnswer();
}
else {
wrongAnswer();
}
});
So I wondered if I can put the 'compare' variables into one variable i.e. 'I went to the cinema OR I have been to the cinema OR etc etc' within one variable for tidiness. But mainly I need to know how I can call that variable within the if so that it also accepts the answer without accented characters and regardless of upper or lower case... I hope this is clear! Thanks for any help you can give, this has been irritating me for a while!
As commented by Mark Holland, use arrays for the compare phrases.
If you are using jQuery anyway, you could use jQuery.inArray().
https://api.jquery.com/jQuery.inArray/
var compareText = ['i went to the cinema','i have been to the cinema'];
if ($.inArray(text.toLowerCase(), compareText)) {
... do stuff
}
To ignore the accents, use a solution like this:
String.prototype.removeAccents = function(){
return this
.replace(/[áàãâä]/gi,"a")
.replace(/[éè¨ê]/gi,"e")
.replace(/[íìïî]/gi,"i")
.replace(/[óòöôõ]/gi,"o")
.replace(/[úùüû]/gi, "u")
.replace(/[ç]/gi, "c")
.replace(/[ñ]/gi, "n")
.replace(/[^a-zA-Z0-9]/g," ");
}
Credits to Luan Castro
Perform a find/match with javascript, ignoring special language characters (accents, for example)?
As mentionned by Mark Holland, arrays would answer your first question.
JS arrays
To ignore accents, a quick search gave me this answer:
Replace accents
And to ignore lower/uppercase, a quick search gave me this answer.
Ignore case
How about setting the strings into one array and iterate this array to compare with the answer?
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]);
}
}