Notes Domino web form, validating onblur what was entered in a field. Field is set as a number but I want to catch what was entered immediately if it is not a number. Then I want to clear what was entered and put the focus right back in the field. I get the code to run, and the alert comes up correctly but the focus does not happen, nor does the value get removed.
function checkNumeric(fld, nm) {
debugger;
var x;
x = document.getElementById(fld).value;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x)) {
document.getElementById(fld).value = '';
alert("Non-numeric entry of '" + x + "' in : " + nm +", please try again.");
document.getElementById(fld).focus();
}
}
Be also sure that the event handler which calls this is set to prevent default. Otherwise it might be the element get the focus but is removed afterwards by the event handler emediatly.
function checkNumeric(fld, nm) {
//debugger;
var x;
if (typeof fld !== "string") {
alert("fld is not a string");
}
if (typeof nm !== "string") {
alert("nm is not a string");
}
var elm = document.getElementById(fld);
if (elm) {
x = elm.value;
if (isNaN(x)) {
elm.value = '';
alert("Non-numeric entry of '" + x + "' in : " + nm + ", please try again.");
elm.focus();
}
}
}
Related
I'm running a form which contains a textbox for the entry of a PIN code.
When typing the code in, each character is replaced with an * and the actual value entered is put into a new variable.
Click 'Submit' or 'Enter' and it works fine. (code below).
However, when I paste the code into the textbox, (id=user_pin_code) the characters are not replaced with * and the values are not entered to that other variable (PINcode), which means that, when I click 'Submit' or hit Enter key, the value is not passed to the next script.
It seems I need the onmouseup or onmouseout event to trigger the JS (to change the chars to ****** and to put the actual characters into 'PINcode' ) but, those two events don't seem to work which means the new variable is not populated.
Any guidance or pointers would be much appreciated.
<script>
\$(document).ready(function(e) {
var actualTextEntered = "";
\$("#user_pin_code").keyup(function(e) {
var x = document.getElementById("user_pin_code").value;
actualTextEntered += x.replace(/\\*/g,"");
//actualTextEntered += x.replace(/*/g,"");
addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
//console.log( 'key = ' + key );
if ( key === "Backspace" ) {
// Do something
actualTextEntered = '';
x='';
}
if ( key === "Return" ) {
//console.log( 'key pressed = ' + key);
}
});
document.getElementById("user_pin_code").value = "";
for (var i=0;i<actualTextEntered.length;i++)
{
document.getElementById("user_pin_code").value += "*";
document.getElementById("PINcode").value = actualTextEntered;
}
});
});
</script>);
Check this code if it works:
<script>
\$(document).ready(function(e) {
var actualTextEntered = "";
\$("#user_pin_code").keyup(function(e) {
var x = document.getElementById("user_pin_code").value;
actualTextEntered += x.replace(/\\*/g,"");
//actualTextEntered += x.replace(/*/g,"");
\$("#user_pin_code").keydown(function(event) {
const key = event.key; // const {key} = event; ES6+
//console.log( 'key = ' + key );
if ( key === "Backspace" ) {
// Do something
actualTextEntered = '';
x='';
}
if ( key === "Return" ) {
//console.log( 'key pressed = ' + key);
}
});
document.getElementById("user_pin_code").value = "";
for (var i=0;i<actualTextEntered.length;i++)
{
document.getElementById("user_pin_code").value += "*";
document.getElementById("PINcode").value = actualTextEntered;
}
});
});
</script>);
I have 2 functions that work fine on their own. Using them in a form. I can call them in one onclick event, however I would like to place both in one script with the first called validate() but only call second function display() if information is correct. So if validate() is called and info not correct they get an alert and returns to form true, if info correct then display() is called. Any help appreciated.
function validate() {
// Get the value of the input field with id="QTY"
var x = document.forms["confirm"]["QTY"].value;
// If x is Not a Number or less than one
if (isNaN(x) || x < 1 ) {
alert("Quantity - Minimum 1 required please");
return true;
}
}
function display()
{
var x=document.confirm.qty.value;
var y=document.confirm.price.value;
var z=document.confirm.total.value;
var confirm = window.confirm('Quantity:' + x + '\nPrice Each: ' + y + '\nTotal Price: ' + z + '\n\nConfirm your order?' );
}if(result)
{
// user has pressed ok
}
else
// user has pressed cancel
{
document.getElementById("myform").reset();
}
It is customary to have validate return true if the validation passes.
function validate() {
// Get the value of the input field with id="QTY"
var x = document.forms["confirm"]["QTY"].value;
// If x is Not a Number or less than one
if (isNaN(x) || x < 1 ) {
alert("Quantity - Minimum 1 required please");
return false;
}
return true;
}
function display()
{
var x=document.confirm.qty.value;
var y=document.confirm.price.value;
var z=document.confirm.total.value;
var confirm = window.confirm('Quantity:' + x + '\nPrice Each: ' + y + '\nTotal Price: ' + z + '\n\nConfirm your order?' );
if(confirm)
{
// user has pressed ok
}
else
// user has pressed cancel
{
document.getElementById("myform").reset();
}
}
if (validate()) { display(); }
If you give us more information about the html and glue code we could help better.
This question already has answers here:
JavaScript code to stop form submission
(14 answers)
Closed 7 years ago.
I would like to get the value in each text field in the form so I can use it to be placed as an argument in another function that needs the arguments to be objects that have certain attributes. Every time I press submit, I am not getting the values in the fields and then the page refreshes, leaving me no time to read the error message. I have looked on a few other posts but none of the provided solutions worked. How can I stop the page from refreshing and also, where am I going wrong in trying to get the values inside of the text fields? (The dictionary object references other objects that contain the info I am looking for.)
<form id="add-key">
<h4>Key Signature</h4>
<li><input id="key_name" type="text" name="key-name" value="name" class="small-input"></li>
<li><input id="key_accidental" type="text" name="key-accidental" value="acc." class="small-input"></li>
<li><input id="key_type" type="text" name="key-type" value="type" class="small-input"></li>
<li><input name="Submit" type="submit" value="Add" onClick="keySelect()"></li>
</form>
var dictionary = {notes: notes, accidentals: accidentals, durations: durations, clefs: clefs, keySignatures: keySignatures, octaves: octaves, qualities: qualities, values: values, websitePages: websitePages};
function keySelect() {
var theKeyName = $('#key_name').val();
var theAccidentalName = $('#key_accidental').val();
var theKeyType = $('#key_type').val();
var newKey = {};
var keyAccidentals = {"sharp":"#", "#":"#", "flat":"b", "b":"b"};
if (dictionary.notes[theKeyName]) {
newKey.note = theKeyName.toLowerCase();
} else {
alert("Need a valid key name.");
console.log(theKeyName);
}
if (keyAccidentals[theAccidentalName]) {
newKey.accidental = theAccidentalName.toLowerCase();
} else {
alert("Not a valid accidental.");
console.log(theAccidentalName);
}
if (theKeyType == "major" || theKeyType == "minor") {
newKey.quality = theKeyType.toLowerCase();
console.log("yes " + theKeyType);
} else {
alert("The key must be major or minor.");
console.log(theKeyType);
}
if (keyAccidentals[theAccidentalName]) {
var theKeySignature = newKey.note + newKey.accidental + " " + newKey.quality;
} else {
var theKeySignature = newKey.note + " " + newKey.quality;
}
var reference = keySignatures[theKeySignature];
console.log(reference);
allKeySig(reference);
}
You need to prevent default behavior on clicking submit:
function keySelect(e) {
e.preventDefault();
var theKeyName = $('#key_name').val();
var theAccidentalName = $('#key_accidental').val();
var theKeyType = $('#key_type').val();
var newKey = {};
var keyAccidentals = {"sharp":"#", "#":"#", "flat":"b", "b":"b"};
if (dictionary.notes[theKeyName]) {
newKey.note = theKeyName.toLowerCase();
} else {
alert("Need a valid key name.");
console.log(theKeyName);
}
if (keyAccidentals[theAccidentalName]) {
newKey.accidental = theAccidentalName.toLowerCase();
} else {
alert("Not a valid accidental.");
console.log(theAccidentalName);
}
if (theKeyType == "major" || theKeyType == "minor") {
newKey.quality = theKeyType.toLowerCase();
console.log("yes " + theKeyType);
} else {
alert("The key must be major or minor.");
console.log(theKeyType);
}
if (keyAccidentals[theAccidentalName]) {
var theKeySignature = newKey.note + newKey.accidental + " " + newKey.quality;
} else {
var theKeySignature = newKey.note + " " + newKey.quality;
}
var reference = keySignatures[theKeySignature];
console.log(reference);
allKeySig(reference);
}
I want to hide my website content exception made when ?token_code=12345678 is used in URL. This is the code that's not working correctly, it hides website but never shows it:
I'm calling script by www.example.com/?authtoken=12345678
So when that parameter is included in URL it should show website. But it's not displaying it. It's only hiding it.
PS. I'm using cookies to remember "token" :)
HTML:
<body data-token="12345678"> </body>
JS:
//setCookie and readCookie
function SetCookie(e, t, n) {
var r = new Date;
var i = new Date;
if (n == null || n == 0) n = 1;
i.setTime(r.getTime() + 36e5 * 24 * n);
document.cookie = e + "=" + escape(t) + ";expires=" + i.toGMTString()
}
function ReadCookie(e) {
var t = " " + document.cookie;
var n = t.indexOf(" " + e + "=");
if (n == -1) n = t.indexOf(";" + e + "=");
if (n == -1 || e == "") return "";
var r = t.indexOf(";", n + 1);
if (r == -1) r = t.length;
return unescape(t.substring(n + e.length + 2, r))
}
function DeleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
//capitalzies string
function capitalize(str) {
var first = str.charAt(0).toUpperCase();
str = str.replace(/^.{1}/, first);
return str;
}
// get's the GET paramters like so --> $_GET('var1');
function getVar(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return (false);
}
// Checks for one of TWO access short codes
// includeOnly && excludeOnly
// If includeOnly is not NULL, then ONLY include
// categories mentioned in that varaible.
// Also, cookie the data, that it's saved.
// Of course, if anyone re-visits the site, and
// re-writes the GET paramter, it'd delete all
// previous data in the cookie.
var token_code = ["authtoken", "excludeOnly"];
var asc = ""; //this is used to select the CURRENT access short code
var tokenValues = [];
//first check if there are ANY get params.
if (getVar(token_code[0]) != false) {
//before writing the inlcude only, delete EXCLUDE only
DeleteCookie(token_code[1]);
SetCookie(token_code[0], getVar(token_code[0]));
}
if (getVar(token_code[1]) != false) {
//before writing the EXCLUDE only, delete include only
DeleteCookie(token_code[0]);
SetCookie(token_code[1], getVar(token_code[1]));
}
//Try and reaad the cookie (there should be a cookie named "includeOnly" or "excludeOnly -- both from token_code)
//includeOnly is present?
if (ReadCookie(token_code[0]).toString().length > 0) {
//defines what the user wants to do. Exlcude or include? when token_code[0] it's include!
asc = token_code[0];
var tokens = ReadCookie(asc).toString();
tokenValues = decodeURIComponent(tokens).split(',');
//loop through each category.
//hide every category and it's children
$("[data-token]").hide();
$.each(tokenValues, function (index, value) {
//show every category, and it's childen, for the values
$("[data-token='" + value + "']").show();
});
}
//excludeOnly is present?
if (ReadCookie(token_code[1]).toString().length > 0) {
//defines what the user wants to do. Exlcude or include? when token_code[0] it's include!
asc = token_code[1];
var tokens = ReadCookie(asc).toString();
tokenValues = decodeURIComponent(tokens).split(',');
//loop through each category.
//hide every category and it's children
$("[data-token]").show();
$.each(tokenValues, function (index, value) {
//show every category, and it's childen, for the values
$("[data-token='" + value + "']").hide();
});
}
is there an easier way to do this?
In the bottom of your code, were the comment says to show, it runs .hide().
Could that be a problem?
//show every category, and it's childen, for the values
$("[data-token='" + value + "']").hide();
I have to make a small javascript function that adds a prefix and suffix to a selected text within a textbox.
This is what I have so far:
function AddTags(name, prefix, suffix) {
try
{
var textArea = document.getElementById(name).value;
var i = 0;
var textArray = textArea.split("\n");
if (textArray == null) {
document.getElementById(name).value += prefix + suffix
}
else {
for (i = 0; i < textArray.length; i++) {
textArray[i] = prefix + textArray[i] + suffix;
}
document.getElementById(name).value = textArray.join("\n");
}
}
catch (err) { }
}
Now this function adds the provided prefix and suffix to every line, but I need to find out how to break up my textbox's text in Text before selection, Selected text and Text after selection.
Anybody any experience on this?
EDIT:
TriniBoy's function set me on the right track. I didn't need the whole suggestion.
This is the edited version of my original code:
function AddTags(name, prefix, suffix) {
try
{
var textArea = document.getElementById(name);
var i = 0;
var selStart = textArea.selectionStart;
var selEnd = textArea.selectionEnd;
var textbefore = textArea.value.substring(0, selStart);
var selected = textArea.value.substring(selStart, selEnd);
var textAfter = textArea.value.substring(selEnd);
if (textAfter == "") {
document.getElementById(name).value += prefix + suffix
}
else {
document.getElementById(name).value = textbefore + prefix + selected + suffix + textAfter;
}
}
catch (err) { }
}
Thx TriniBoy, I'll mark your leg-up as answer.
Based on your demo and your explanation, hopefully I got your requirements correct.
See code comments for a break down.
See demo fiddle here
var PreSuffApp = PreSuffApp || {
selText: "",
selStart: 0,
selEnd: 0,
getSelectedText: function (id) {
var text = "",
docSel = document.selection, //For IE
winSel = window.getSelection,
P = PreSuffApp,
textArea = document.getElementById(id);
if (typeof winSel !== "undefined") {
text = winSel().toString(); //Grab the current selected text
if (typeof docSel !== "undefined" && docSel.type === "Text") {
text = docSel.createRange().text; //Grab the current selected text
}
}
P.selStart = textArea.selectionStart; //Get the start of the selection range
P.selEnd = textArea.selectionEnd; //Get the end of the selection range
P.selText = text; //Set the value of the current selected text
},
addTags: function (id, prefix, suffix) {
try {
var textArea = document.getElementById(id),
P = PreSuffApp,
range = P.selEnd - P.selStart; //Used to calculate the lenght of the selection
//Check to see if some valuable text is selected
if (P.selText.trim() !== "") {
textArea.value = textArea.value.splice(P.selStart, range, prefix + P.selText + suffix); //Call the splice method on your text area value
} else {
alert("You've selected a bunch of nothingness");
}
} catch (err) {}
}
};
//Extend the string obj to splice the string from a start character index to an end range, like an array.
String.prototype.splice = function (index, rem, s) {
return (this.slice(0, index) + s + this.slice(index + Math.abs(rem)));
};