I want to perform an action after the user typed in a textbox. I will be using onkeyup in the textbox.
i want a condition, that will allow the user to perform a task, only if the typed word is a dictionary word or a proper word.
Eg :
if the user types hello, then alert the word Hello.
if the user types helr, then alert that this is not a dictionary word.
HTML :
<input type="text" onkeyup="chk();"/>
<span id="indicate"></span>
Javascript :
function chk() {
if(spellcheck()) {
document.getElementById("indicate").innerHTML = "Correct Word";
}
else {
document.getElementById("indicate").innerHTML = "Wrong Word";
}
}
Please Help me defining the function spellcheck() which will return 1 or 0.
I want this to be performed in client side itself, using javascript.
Thanks in advance.
Returning 1 and 0 is not good for JavaScript. Better return true and false from the function. Now, you can define your dictionary in form of array and then check if the input word is present in dictionary or not.
var dictionary = ['Hello', 'Welcome', 'Bye'];
function spellcheck(value) {
var returnVal = false;
var length = dictionary.length;
for (var inc = length - 1; inc >= 0; inc--) {
if(value.toUpperCase() === dictionary[inc].toUpperCase()) {
returnVal = true;
break;
}
}
return returnVal;
}
You can see full example here http://jsbin.com/IgaPEBi/3/edit?html,js,output
You can use the Typo.js dictionary
To use Typo, simply include the typo.js file in your extension's background page, and then initialize the dictionary like so:
var dictionary = new Typo("en_US");
var is_spelled_correctly = dictionary.check("hello");
or http://www.javascriptspellcheck.com/ for an auto suggestions box.
Make a call to an API dictionary service, there are some opensource ones:
wiktionary
glosbe.com
dictionary-api
When the user finishes typing you can use a function to make an async call (AJAX with JS or Jquery) to the APIs endopoint; if the object in the response is not void or null or just states there are no words in the dictionary, your function can return 0, else 1.
Usually the endpoint address is something like URL/action/*word* , where action is what you want to know and word is the actual word you look for.
Related
Hopefully you all don't get pissed at me for such a seemingly simple question..
Basically, I have a PDF form that I'm scripting with javascript.
I have a bunch of check boxes that I would like to set required and/or not required based on other inputs and I'm trying to repeat code as little as possible, especially since there's a ton of inputs.
Right now, the best way I can accomplish what I'm attempting is by setting a function for each instance of inputs as follows:
function setWalkwayNotRequired() {
this.getField("sidewalkAsphalt").required = false;
this.getField("sidewalkConcrete").required = false;
this.getField("sidewalkPavers").required = false;
this.getField("sidewalkCondition").required = false;
}
I would then call this function based on the input of a certain checkbox:
if (this.getField("sidewalkNone").value == "Yes") {
setSidewalkNotRequired();
}
Then all of the above-mentioned fields would be set to not required.
I feel like there should be a way to create a single "setRequired" or "setNotRequired" function to take a parameter of the field in question.
In my mind that would look something like this:
function setRequired(a, b, c, d) {
this.getField(a).required = true;
this.getField(b).required = true;
this.getField(c).required = true;
this.getField(d).required = true;
}
I would then call on that function for all instances, for example, walkways (like that above) or driveways, etc. like so:
if (this.getField("sidewalkNone").value == "Off") {
setRequired('"sidewalkAsphalt"', '"sidewalkConcrete"', '"sidewalkPavers"', '"sidewalkCondition"');
}
Again, in my mind what would then be output based on the above code once the function is called is something like:
if (this.getField("sidewalkNone").value == "Off") {
this.getField("sidewalkAsphalt").required = true;
this.getField("sidewalkConcrete").required = true;
this.getField("sidewalkPavers").required = true;
this.getField("sidewalkCondition").required = true;
}
Doing it the way I did in the first code block would require me to create separate functions for each set of checkboxes, creating a lot of code in an already huge file. The second way would allow me to use 1 function over and over throwing the field names as parameters depending on where I'm at in the PDF.
I'm also not very clear on if it's even legal to declare the parameters as I did with the '"..."' quotes; I did that because I need the double quotes inside the this.getField().
Again, I'm sorry if this is novice, I've just been trying to play with the code for a while now and can't get it to work.
Any input would be amazing.
You could just pass in an Array of field names:
function setRequired( fieldNames, isRequired = true ) {
for( var i = 0; i < fieldNames.length; i++ ) {
var fieldName = fieldNames[i];
this.getField( fieldName ).required = isRequired;
}
}
Usage:
if( this.getField("sidewalkNone").value == "Off" ) {
setRequired( [ "sidewalkAsphalt", "sidewalkConcrete", "sidewalkPavers", "sidewalkCondition" ] );
}
If you use hierarchical naming with dot notation, you can set properties on the parent to affect all children. For example, if you name the fields "sidewalk.Asphalt", "sidewalk.Concrete", and "sidewalk.Pavers"...
this.getField("sidewalk").required = true;
... will set all the children to be required.
I'm working on some Cypress assertions that is looking at a value to contain a string. Right now it's a success if the data shows "AM" but I'd also like for it to be correct if it shows "PM".
cy.get('.v-list__tile__content')
.then(($info) => {
expect($info, 'Delivery Information').to.have.length(3)
expect($info.eq(0), 'Address').to.contain('Chicago')
expect($info.eq(1), 'Time').to.contain('AM')
expect($info.eq(2), 'Year').to.contain('2019')
})
The data is actually showing Address, full time, and then year. Is there an assertion that allows for checking contains against two/multiple strings? Maybe a version of oneOf but with contains? I'm struggling to find documentation that allows for something like that. I think doing a conditional would defeat the purpose since I want to assert it's either AM/PM. Typically the data will come back like 12:00 PM so unfortunately I can't hit on the number and do an assertion there.
My JS is mediocre but maybe doing
arr = ["AM", "PM"];
var el = document.getElementByClassName('.v-list-tile__content')[1];
var txt = el.includes(arr);
So how do I do an assertion in Cypress on contains for multiple strings?
You could try using something along these lines in a for loop.
let arr;
let element;
arr = ["AM", "PM", "Dog", "Cat", "Bug", "Whatever"]
element = '.v-list-tile__content'
function checkAgainstArr(arr, element) {
let i;
for (i = 0; i < arr.length; i++) {
if (cy.get(element).contains(arr[i])) {
return true;
} else {
if (i === arr.length) {
return false;
}
}
}
}
expect(checkAgainstArr).to.be.true;
Basically, it checks how long the array is (here, it's 6), and then tries that many times to compare the element's text against each item in the array. If it finds it, it returns true. Then, you can call that function (with two parameters, array and element) and check for truthy/falsy.
I am trying to use a custom function developed in Google Script to validate a value in the spreadsheet.
However I get a response: There is a problem "Enter a value that satisfies the formula: =validateContent()"
The function itself has not been called at all.
Am I pushing Google Spreadsheet validation too far here with custom function?
I was expecting my function to return true or false, is that how it is suppose to work?
function validateContent() {
var val = SpreadsheetApp.getActiveSpreadsheet().getActiveCell().getValue();
if (val == value) return true;
return false;
}
First, to validate the current cell input it is useful to follow the pattern suggested by google:
=ISODD(C8)
In your case:
=validateContent(C8)
The validation generator is smart enough to translate the cell reference correctly to all other cells! I.e if this validation is applied to C8:C100 the validation of cell C42 will read =ISODD(C42).
Still, I have found that custom functions seem not to work in validation! See the following example:
In this screenshot the cell G2 uses a custom validation function (=ssvDataVerify(G2)), which evaluates to TRUE but is shown as invalid (red corner)! As a proof, the data value of cell I2 is =ssvDataVerify(G2). Now the validation if I2 is =I2, which now is shown as correctly validated!
I conclude that currently custom functions are not implemented to work with validation.
Currently, functions cannot be used in validations, but there is a workaround:
Use your custom function in some cell, let's say B2: =validateContent(A2).
Add a validation to cell A2 with the criteria Custom Formula is -> =B2.
I also believe that custom functions don't work for data validation.
I created a function to check a string value , against a list of RegExp and it didn't worked:
function vaidate(){
var range = SpreadsheetApp.getActive().getRange('A1');
var validation = SpreadsheetApp.newDataValidation().requireFormulaSatisfied('=checkValid(A1)').build();
range.setDataValidation(validation);
}
function checkValid(text){
var regexs = [/\|{2,}/g,/\.{2,}/g,];
var valid = true;
for(var i=0;i<regexs.length;i++){
if(testString(text,regexs[i])){
valid = false;
break;
}
}
return valid;
}
function testString(str, regex){
try{
var localRegex = regex;
return localRegex.test(str);
}catch(e) {
return false;
}
}
Here you go :)
The idea is to build the validation rule once the cell is edited
function onEdit(e){
const isValid = validateValue(e.value);
const rule = SpreadsheetApp
.newDataValidation("Yep")
// You can use any function but i believe you only need to use "EQ" with boolean
.requireFormulaSatisfied('=EQ("'+isValid+'","TRUE")')
// Your help message
.setHelpText('Please Enter "123" :P')
// Building the rule
.build();
e.range.setDataValidation(rule);
}
function validateValue(value){
// do what ever you want ;)
return value === "123";
}
I'm having a pretty simple issue I think but I cannot get it solved.
On form submit I want to compare the values of two hidden input types and if any match is found return an alert to the user and prevent submit. Pretty much the hidden input type values will be 1-3, could be 1, 12, 123, 13 etc. So if 1 and 123, throw an alert.
So I've tried something like this, but I'm obviously confused about what I'm doing hehe.
var new_products = $('#new_products');
var array_new_products = jQuery.makeArray(new_products);
var existing_products = $('#existing_products');
var array_existing_products = jQuery.makeArray(existing_products);
$("#my_form").submit(function(e) {
if (jQuery.inArray(existing_products, new_products) >= 0) {
e.preventDefault();
alert ("This Promotion matches one or more products already associated to this Group. If you continue the existing Promotion will be cancelled and replaced with the currently selected Promotion!");
}
return true;
});
I'm open to doing this by comparing strings and returning matches or anything really. I'm just pretty new to Jquery. Thanks in advance.
$.each($('#new_products').val().split(''), function(i, char) {
var existing = $('#existing_products').val();
if (existing.indexOf(char) != -1)
alert('mathces found');
});
checks if any of the characters in the returned value from #new_product exists in the value returned from #existing_products ?
This is probably easy for someone.
I am returning a list of campaignIDs (12,45,66) via JSON to a javascript variable
var campaignList = res.DATA.CAMPAIGNS
Now, given a specified campaignID passed in the URL
var campaignId ='<cfoutput>#url.campaignID#</cfoutput>'
I want to check if the returned list contains this campaignID
Any help much appreciated.
Plenty of ways to do it, but I like nice data structures, so ...
Split the list on comma, then loop over list, looking for value:
function campaignExists(campaignList,campaignId) {
aCampaignList = campaignList.split(',');
for (i=0;i<aCampaignList.length;i++) {
if (aCampaignList[i]==campaignId)
return true;
}
return false;
}
Since Array.indexOf sadly isn't cross browser, you're looking at something like:
// assume there is no match
var match_found = false;
// iterate over the campaign list looking for a match,
// set "match_found" to true if we find one
for (var i = 0; i < campaignList.length; i += 1) {
if (parseInt(campaignList[i]) === parseInt(campaignId)) {
match_found = true;
break;
}
}
If you need to do this repeatedly, wrap it in a function
Here's a bit of a "out of the box" solution. You could create a struct for your property id's that you pass into the json searilizer have the key and the value the same. Then you can test the struct for hasOwnProperty. For example:
var campaignIDs = {12 : 12, 45 : 45, 66 : 66};
campaignIDs.hasOwnProperty("12"); //true
campaignIDs.hasOwnProperty("32"); //false
This way if the list is pretty long you wont have to loop through all of the potential properties to find a match. Here's a fiddle to see it in action:
http://jsfiddle.net/bittersweetryan/NeLfk/
I don't like Billy's answer to this, variables within the function have been declared in the global scope and it is somewhat over complicated. If you have a list of ids as a string in your js just search for the id you have from user input.
var patt = new RegExp("(^|,)" + campaignId + "(,|$)");
var foundCampaign = campaignList.search(patt) != -1;