I have a textbox where i want to have an autocomplete that lets the user search through addresses. The user must be able to type in different words and the autocomplete must search through them to narrow its list.
I've been trying and reading the documentation, but nothing seems to do the trick as it always searches on the whole string instead of the words. Am i missing something?
Example:
When the user enters 'Mathias Antwerp' he must see all the addresses that contain those words. In the example it must show 1 row which is the second one.
<script>
var addresses = [
{ name: "Frederick Dereave Gentstreet 4 Gent" },
{ name: "Mathias Derian Meilaan 9 Antwerp" },
{ name: "Mathias Hors frelaan 5 Kortrijk" }
];
$(document).ready(SetAutoComplete);
function SetAutoComplete() {
$("#testveld").autocomplete(emails,
{
matchContains: "word"
}
);
}
</script>
<input type="text" id="testveld" style='width:300px'/>
I altered the code of matchSubset in jquery.autocomplete.js which enables the behavior i was looking for.
function matchSubset(s, sub) {
var arraySub=sub.split(" ");
if (!options.matchCase)
s = s.toLowerCase();
var i = s.indexOf(sub);
if (options.matchContains == "word"){
i = s.toLowerCase().search("\\b" + sub.toLowerCase());
}
//addition for split words
if (options.matchContains == "splittedword"){
for(itemindex=0;itemindex<arraySub.length;itemindex++){
i = s.toLowerCase().search(arraySub[itemindex].toLowerCase());
if(i==-1){
break;
}
}
}
if (i == -1) return false;
return i == 0 || options.matchContains;
};
AFAIK, you will have to to do some processing on your own to parse the string into words. You can do this using jquery or if you plan to get the addresses from server side then use some server side language.
Related
I am using indexOf to see if an email contains anything other than a particular text.
For example, I want to check if an email DOES NOT include "usa" after the # symbol, and display an error message.
I was first splitting the text and removing everything before the # symbol:
var validateemailaddress = regcriteria.email.split('#').pop();
Then, I check if the text doesn't include "usa":
if(validateemailaddress.indexOf('usa')){
$('#emailError').show();
}
Something with the above check doesn't seem right. It works - I can enter an email, and if it does not include 'usa', then the error message will show.
Regardless, when I add an additional check, like if the email does not include "can", then the error message shows no matter what.
As follows:
if(validateemailaddress.indexOf('usa') || validateemailaddress.indexOf('can')){
$('#emailError').show();
}
As stated, using the above, the error message will show regardless if the email includes the text or not.
All I want to do is check if the email includes 'usa' or 'can', and if it doesn't, then show the error message.
How can I make this work?
Here is a simple JavaScript function to check if an email address contains 'usa' or 'can'.
function emailValid(email, words) {
// Get the position of # [indexOfAt = 3]
let indexOfAt = email.indexOf('#');
// Get the string after # [strAfterAt = domain.usa]
let strAfterAt = email.substring(indexOfAt + 1);
for (let index in words) {
// Check if the string contains one of the words from words array
if (strAfterAt.includes(words[index])) {
return true;
}
}
// If the email does not contain any word of the words array
// it is an invalid email
return false;
}
let words = ['usa', 'can'];
if (!emailValid('abc#domain.usa', words)) {
console.log("Invalid Email!");
// Here you can show the error message
} else {
console.log("Valid Email!");
}
You can do something like that, using includes:
const validateEmailAdress = (email) => {
const splittedEmail = email.split('#').pop();
return (splittedEmail.includes('usa') || splittedEmail.includes('can'))
}
console.log("Includes usa: ", validateEmailAdress("something#gmail.usa"))
console.log("Includes can: ", validateEmailAdress("something#gmail.can"))
console.log("Does not includes: ", validateEmailAdress("something#gmail.com"))
There are several ways to check, if a string contains/does not contain a substring.
String.prototype.includes
'String'.includes(searchString); // returns true/false
String.prototype.indexOf
// returns values from -1 to last postion of string.
'String'.indexOf(searchString);
// In combination with ~ this can work similar to includes()
// for strings up to 2^31-1 byte length
// returns 0 if string is not found and -pos if found.
~'String'.indexOf(searchString);
With the help of Regular Expressions:
// substring must be escaped to return valid results
new RegExp(escapedSearchString).test('String'); // returns true/false if the search string is found
'String'.match(escapedSearchString); // returns null or an array if found
So overall you can use allmost all methods like:
if ('String'.function(searchString)) {
// 'String' includes search String
} else {
// 'String' does not include search String
}
Or in case of indexOf:
if ('String'.indexOf(searchString) > -1) {
// 'String' includes search String
} else {
// 'String' does not include search String
}
// OR
if (~'String'.indexOf(searchString)) {
// 'String' includes search String
} else {
// 'String' does not include search String
}
I believe this regular expression match is what you're looking for
System.out.println(myString.matches("(.)#(.)usa(.*)"));
We're displaying five input fields to user. He can type some information in them. After that, we need to find out if his input is correct. For that purpose we use an array of possible correct values.
Like:
var input = document.getElementById("input").value;
input = input.toLowerCase();
inputPos = possibleInputs.indexOf(input);
inputPosArray.push(inputPos);
The code for analysis looks like that for now:
function arrayLookup() {
var inputCorrect = true;
inputPosArray.forEach(function(item, i, inputPosArray) {
if (inputPosArray[i] == -1) {
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
wrongInputsArray.push(wrongInput);
inputCorrect = false;
} else {
null;
}
});
if (inputCorrect == false) {
alert("Wrong input! Check field " + wrongInputsArray);
} else {
nextStep();
}}
For now it correctly finds out if input is wrong and alerts user.
The problem is in "wrongInputsArray" - it doesn't display output correctly. E.g. if user has typed wrong information in 2nd field, it will print out "2".
But if he has made mistakes in 2nd and 5th field, he gets "Wrong input! Check field 2,2" alert.
Please show me what am I doing wrong.
Kindly yours,
Richard
You are using this code to insert the wrong asnwers:
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
If two questions has the same answer, indexOf will return always the first match. Try just using this:
wrongInput = i + 1;
Where am I going wrong? Even one error would help please.
I have an HTML input and a submit button. The idea is to:
Submit search string
Get string value.
Compare string value to regex.
If legit, find instances of the string in the DOM.
Then scroll to the first instance of the matched string as it sits in the DOM.
$("#submit").on("click", function () {
//regex to be compared against
var search = new RegExp();
search = /(^\w[A-z]+)$|(^\d[0-9\.x\.X\.m\.M]+)/;
//grab the string value from the search input
var userin = $("#searchin").val();
var compare = userin.test(search);
if (compare === true) {
var treebody = $('html, body').contents().filter(function (userin) {
if ($('html, body').contents() === userin) {
$('html, body').animate({'scrollTop' : $(treebody).position().top}, 700)
} else {
alert("Please search again or scroll down to find your desired content");
}
});
} else {
alert("Sorry, we couldn't match your search. Please try a region or place or a billboard size e.g. 9x13 ");
}
});
Change the line
var compare = userin.test(search);
it should be
var compare = search.test(userin);
Also check you regular expression. Here is a good reference RegEx.
I have a piece of HTML that creates a web form with three text fields (name, group and number), all of which are validated using JavaScript to check that there is data inputted into them. In the last text field, I need to introduce an additional bit of JavaScript to check that the data inputted by the user is also four digits long (for example 2947 or 94Q3). As a complete JavaScript novice, I'm not sure how I would do this! Would I have to create a variable that could take the value of the inputted data, then count the digits of the variable, or could I do it directly from the field? Here is the Javascript section of my code:
function validateForm() {
var result = true;
var msg = ””;
if (document.Entry.name.value == ””) {
msg += ”You must enter your name\n”;
document.Entry.name.focus();
document.getElementById(‘name’).style.color = ”red”;
result = false;
if (document.Entry.group.value == ””) {
msg += ”You must enter the group\n”;
document.Entry.group.focus();
document.getElementById(‘group’).style.color = ”red”;
result = false;
}
if (document.Entry.number.value == ””) {
msg += ”You must enter the number\n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color = ”red”;
result = false;
}
if (msg == ””) {
return result;
} {
alert(msg)
return result;
}
}
If possible, could you tell me what code I would need to insert? Thank you!
Place this block in your conditions list:
if (document.Entry.number.length!=4) {
msg+=”You must enter 4 digits \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
if (document.Entry.number.value==””) {
msg+=”You must enter the number \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
change this to
if (document.Entry.number.length != 4){
msg+="Number must be exactly 4 characters \n";
document.Entry.number.focus();
document.getElementById('number').style.color="red";
result = false;
}
I know this type of question has been asked before, which is how I came up with my regular expression in the first place, but my coding doesn't seem to be working.
I'm combining 2 things, firstly I'm trying to restrict a multiline textbox to 6000 characters and have this work on key up, which it does nicely. However, as part of this I also want to strip out HTML tags BEFORE checking the length, which is the bit that's not working. My code is below:
function TruncateNotes(text) {
var notesfield = document.getElementById(text.id);
//strip html tags such as < and > out of the text before checking length
stripHTML(text);
var maxlength = 6000;
if (notesfield.value.length > maxlength) {
notesfield.focus();
notesfield.value = text.value.substring(0, maxlength);
notesfield.scrolltop = notesfield.scrollHeight;
return false;
}
else {
return true;
}
}
function stripHTML(text) {
var notesfield = document.getElementById(text.id);
notesfield.value.replace(/<.*?>/g, "");
}
My feeling is that's something to do with the regular expression as I'm not very good with those. Any suggestions?
JavaScript '.replace' does not modify the original string, it returns a string with the values replaced. This means you'll have to assign it back to notesfield.value after the operation:
notesfield.value = notesfield.value.replace(/<.*?>/g, "");