Creating custom spell checking for html - javascript

Is it possible to use some custom functions for spell checking in html inputs? For example I have an input where values are divided by spaces (or commas, doesn't matter) and a function which receives tokens from it. That function decides if token is spelled correctly (in my case there would be some regular expression) and returns true/false value and based on that some words would be underlined. In my head it looks something like this:
<input type="text" onCheck="checkToken">
<script>
function checkToken(token) {
const oneCrazyRegex = /[a-b]/;
return oneCrazyRegex.test(token);
</script>
Or taking whole input:
function spellCheckInput(line) {
// line is an array of tokens
return line.map(tok => checkToken(tok));
}
Is it possible to do with js/css/html or not?
P.S. onCheck is example only, I know that this attribute is not valid

Yeah you can use regex for cleaning up text but you have to remember that people can fabricate any kind of input they want since the checks would be happening client-side, and anyone can just pop open a console and send anything they want.

Related

Add parameters to url with onSubmit using a Javascript function

I want to add html parameters to the url with onsubmit. I have 2 forms(1 GET, 1 POST), want to use 1 button to submit them both(Using the POST form button) When the submit button is pressed use onSubmit to call a javascript function, where parameters are "appended" to the url.
I was thinking about doing something like this:
function onSubmitForm() {
url = "localhost:8080/test/index.php?Title=document.getElementsByName('title')[0].value";
//I don't know how to actually call the url.
}
EDIT
I got what I wanted:
Appending form input value to action url as path
First, you have to concatenate the string's static and dynamic parts. Then, you can redirect.
function onSubmitForm() {
window.location = "localhost:8080/test/index.php?Title=" +
document.querySelector('title').textContent;
}
NOTES:
Only form fields have a .value property. If you are trying to get
the text within an element, you can use .textContent.
.getElementsByName() scans the entire document and makes a
collection of all the matching elements. That's wasteful when you
know you want only the first one and, in the case of <title>, there
is only ever going to be one of those in a document anyway. Use
.querySelector() to locate just the first matching element.
ES6
NOTES :
Don't forget to use Babel for converting your code in ES5.
I purpose to you this solution :
function onSubmitForm() {
window.location = `localhost:8080/test/index.php? Title=${document.querySelector('title').textContent}`
}
This way of doing with backtick is even simpler than in ES5, let me explain, before we had to concatenate with the sign + ourVariable + the continuation of our string of character.
Here we have more of that. And we can write on several lines as well.
Then ${} is used to pass a variable inside
Documentation if you want : Literal template string

Regex replacement with prompting/callback UI

I'm trying to write a function that takes a long string of text, identifies place holders within the text, and prompts the user to supply a value that should take the place of the placeholder. The markup for the placeholders looks similar to markdown used for images or links:
some text, some more text, ?[name][description] more text, not just commas
Where name and description are arbitrary runs of text. When I've found these placeholders, I want to pop up a nicely formatted dialog, using the names and descriptions, and have the user supply a replacement value.
I already have a nice function (called htmlPrompt) available where you hand it a piece of HTML (for the main part of the prompt), has a text box, and then calls a callback function you've supplied with the result (or null if Cancel is pressed), with the following signature:
function (htmlText, inputStartValue, callback)
Before plugging in this function, I wrote the rough and ready:
myText = myText.replace(/(\?\[(.+)\][ ]?(?:\n[ ]*)?\[(.+)\])/g,
function (wholematch, m1, m2, m3) {
var repValue = prompt(m2);
if (repValue == null)
{
return m1;
}
return repValue;
});
Which uses the DOM built-in prompt method - which doesn't really do an adequate job for me, when it comes to formatting.
However, I can't think of a way of plugging in htmlPrompt - it only simulates a modal dialog and provides the final result by calling callback.
I did think of trying to manually do the replacements, using the results from match rather than replace - but so far as I can see, the values returned by match are just strings - they don't give you anything useful (such as the location of the match within the overall text).
Or do you think I'm going about this completely wrong? The overall flow I want is:
Find each placeholder in the text
Prompt the user for a replacement, using both the name and description values
Replace the placeholder expressions in the text with the user supplied value.
For each of the name and description tupples:
First use match to read name and desription.
Prompt user.
Then use replace to replace those.

Pass multiple values with onClick in HTML link

Hi Im trying to pass multiple values with the HTML onclick function. Im using Javascript to create the Table
var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
But in my Javascript function the userName is undefined and the valuationId is a string with the valuationId and the UserName combined
function ReAssign(valautionId, userName) {
valautionId;
userName;
}
If valuationId and user are JavaScript variables, and the source code is plain static HTML, not generated by any means, you should try:
Re-Assign
If they are generated from PHP, and they contain string values, use the escaped quoting around each variables like this:
<?php
echo 'Re-Assign';
?>
The logic is similar to the updated code in the question, which generates code using JavaScript (maybe using jQuery?): don't forget to apply the escaped quotes to each variable:
var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
The moral of the story is
'someString(\''+'otherString'+','+'yetAnotherString'+'\')'
Will get evaluated as:
someString('otherString,yetAnotherString');
Whereas you would need:
someString('otherString','yetAnotherString');
Solution: Pass multiple arguments with onclick for html generated in JS
For html generated in JS , do as below (we are using single quote as
string wrapper).
Each argument has to wrapped in a single quote else
all of yours argument will be considered as a single argument like
functionName('a,b') , now its a single argument with value a,b.
We have to use string escape character backslash() to close first argument
with single quote, give a separator comma in between and then start next argument with a
single quote. (This is the magic code to use '\',\'')
Example:
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
$Name= "'".$row['Name']."'";
$Val1= "'".$row['Val1']."'";
$Year= "'".$row['Year']."'";
$Month="'".$row['Month']."'";
echo '<button type="button" onclick="fun('.$Id.','.$Val1.','.$Year.','.$Month.','.$Id.');" >submit</button>';
enclose each argument with backticks( ` )
example:
<button onclick="updateById(`id`, `name`)">update</button>
function updateById(id, name) {
alert(id + name );
...
}
Please try this
for static values--onclick="return ReAssign('valuationId','user')"
for dynamic values--onclick="return ReAssign(valuationId,user)"
That is because you pass string to the function. Just remove quotes and pass real values:
Re-Assign
Guess the ReAssign function should return true or false.
A few things here...
If you want to call a function when the onclick event happens, you'll just want the function name plus the parameters.
Then if your parameters are a variable (which they look like they are), then you won't want quotes around them. Not only that, but if these are global variables, you'll want to add in "window." before that, because that's the object that holds all global variables.
Lastly, if these parameters aren't variables, you'll want to exclude the slashes to escape those characters. Since the value of onclick is wrapped by double quotes, single quotes won't be an issue. So your answer will look like this...
Re-Assign
There are a few extra things to note here, if you want more than a quick solution.
You looked like you were trying to use the + operator to combine strings in HTML. HTML is a scripting language, so when you're writing it, the whole thing is just a string itself. You can just skip these from now on, because it's not code your browser will be running (just a whole bunch of stuff, and anything that already exists is what has special meaning by the browser).
Next, you're using an anchor tag/link that doesn't actually take the user to another website, just runs some code. I'd use something else other than an anchor tag, with the appropriate CSS to format it to look the way you want. It really depends on the setting, but in many cases, a span tag will do. Give it a class (like class="runjs") and have a rule of CSS for that. To get it to imitate a link's behavior, use this:
.runjs {
cursor: pointer;
text-decoration: underline;
color: blue;
}
This lets you leave out the href attribute which you weren't using anyways.
Last, you probably want to use JavaScript to set the value of this link's onclick attribute instead of hand writing it. It keeps your page cleaner by keeping the code of your page separate from what the structure of your page. In your class, you could change all these links like this...
var links = document.getElementsByClassName('runjs');
for(var i = 0; i < links.length; i++)
links[i].onclick = function() { ReAssign('valuationId', window.user); };
While this won't work in some older browsers (because of the getElementsByClassName method), it's just three lines and does exactly what you're looking for. Each of these links has an anonymous function tied to them meaning they don't have any variable tied to them except that tag's onclick value. Plus if you wanted to, you could include more lines of code this way, all grouped up in one tidy location.
function ReAssign(valautionId, userName) {
var valautionId
var userName
alert(valautionId);
alert(userName);
}
Re-Assign

Passing HTML input form contents for calculation

I am trying to make a graph of a simple function y=k*x+b.
A user enters a function into the input field, for example:
1/3*x+3
and when he/she clicks the submit button, a JavaScript function is supposed to take this input value as an actual calculation sequence and assign a variable to it (I only need to get certain y values here, so the x variable has its limits):
for (x=1;x<=40;x++)
{
result = window.document.menu.inputFunction.value;
}
The above code doesn't work. No wonder why - I am just a beginner at this. However, is this really harder than it looks, or am I missing out something? I considered trying regular expressions for this at one point, but my head hurts by even thinking about using them.
Any ideas?
You could eval it:
result = eval(window.document.menu.inputFunction.value);
There are obviously some limitations to this approach:
The user must enter a valid javascript expression
The user must use x as variable name because that's what you are using in the loop
The code is vulnerable because the user can enter and execute any javascript expression he likes
For a more robust solution you might consider using a javascript mathematical expression evaluator.

vb.net passing a value of text box in javascript function

MotherTongueTxtBox.Attributes.Add("onblur","val_Length(MotherTongueTxtBox.text,"hi friends",Length);")
in the above statement val_length s a javascript function in tat function the first parameter shd b the contents of the text box ,the second parameter s a string type,
is the statement correct i think it s wrong can u suggest a correct valid statement please
I had a little trouble understanding your question, but I think you're asking that the first parameter be the textbox text, and the second be the length of the textbox text. This I think should work:
MotherTongueTxtBox.Attributes.Add("onblur","val_Length(this.value,this.value.length)");
Remember that the above will render the html like:
<input type="text" onblur="val_Length(this.value, this.value.length)" />
In your original statement, the resulting (incorrect) html would have been something like:
<input type="text" onblur="val_Length(,0)"/>
Since MotherTongueTxtBox.Text and .Length would have been string.empty and 0 respectively (unless it already had initial values...)
EDIT:
Thanks for marking as solution. Just as a side note, one thing you may want to consider, is you don't need to pass this.value.length in as a parameter, since you're already passing in this.value. You could determine the length within your function. Just an idea though like this:
MotherTongueTxtBox.Attributes.Add("onblur","val_Length(this.value, 'Hi')");
And then in your javascript function:
function val_Length(value, myString) {
var length = value.length;
....
}

Categories

Resources