How to get split function to work properly? [duplicate] - javascript

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 4 months ago.
i am trying to create a function that takes a form input (in this case the name), splits it using the space, and then sends either an error message or an all good message. however, it fails to acknowledge conditions for some reason? it always says that its correct even if i only input a name.
function validateName(){
var nameVal = document.getElementById("yourname");
var nameParts = nameVal.toString().split(" ");
if (nameParts.length<2) {
document.getElementById("yourname").nextSibling.innerHTML = "Please enter your First and Last Name.";}
else {
document.getElementById("yourname").nextSibling.innerHTML = "Thank you for entering your First and Last Name!";
}
}
ive tried changing the code in various ways but there is always some error.

Looks like you forgot to add .value in the first line of your function like this document.getElementById("yourname").value.
function validateName(){
var nameVal = document.getElementById("yourname").value;
var nameParts = nameVal.toString().split(" ");
if (nameParts.length<2) {
document.getElementById("yourname").nextSibling.innerHTML = "Please enter your First and Last Name.";}
else {
document.getElementById("yourname").nextSibling.innerHTML = "Thank you for entering your First and Last Name!";
}
}

Related

How can I adapt this javascript to return a postcode less the last 2 characters? [duplicate]

This question already has answers here:
How do I chop/slice/trim off last character in string using Javascript?
(25 answers)
Closed 7 years ago.
function() {
var address = $("#postcode").val();
var postcode = address.split(' ');
postcode = "Postcode:"+postcode[(postcode.length-2)];
return postcode;
}
This js pulls a postcode value from an online form when the user runs a query. I need to know how I get it to deliver the postcode less the last 2 characters. for example, SP10 2RB needs to return SP102.
Use substring() or substr() or slice().
You have to slice the string and return what you want:
return postcode.slice(0, -2);
// example
postcode = "sample";
// output
"samp"
You can use this function:
function postCode(address)
{
var tmpAddr = address.replace(' ','');
tmpAddr = tmpAddr.substr(0, tmpAddr.length-2);
return tmpAddr;
}
alert(postCode('SP10 2RB'));

ServiceNow Script onSubmit not working properly

I am using ServiceNow platform. I am writing a Catalog Client Script to validate form fields on a Catalog Item record producer.
I am stopping the submission of the form by using return false if validation does not pass inspection.
I have tested this by entering invalid data (group name with special characters or a group name that exists already) and it catches the issue and shows the error message. I can enter invalid data and submit multiple times and it works.
However, the issue:
The script seems to "stop" running after I first enter invalid data and submit, and then I correct the data press the submit button again. It just sits there and does nothing. I have to reload the form again which is not desirable.
What is going on with the control flow? How can I cleanly stop the form if the data is invalid, but then allow the user to correct the mistake and press the submit button again to proceed?
I can tell that the script doesn't run again because I have an alert box popping up that says "script run" every time the script runs. It just stops running at some point after submitting invalid data first and then entering some valid data and pressing submit.
function onSubmit() {
g_form.hideAllFieldMsgs('error');
alert("script run");
//Group Name contain letters numbers and dashes only
var group_name = g_form.getValue('u_group_name');
// Group name regular expression
var regGrpName = /^([A-Za-z0-9\-]+)$/;
// Check name against regular expression
if (regGrpName.test(group_name) == false) {
g_form.showFieldMsg('u_group_name', "Group Name must contain only letters, numbers or dashes. ", 'error');
//Do not submit
//g_form.submitted = false;
return false;
}
//Check if google group already exists
var rec = new GlideRecord('u_google_user_accounts');
rec.addQuery('u_account_email', new_group_email);
rec.query();
while (rec.next()) {
g_form.showFieldMsg('u_group_name',rec.u_account_email + " already exists as an account.",'error');
return false;
}
//Group Members Email List separated by commas
// Hide error message
//g_form.hideErrorBox('u_group_members');
var group_members = g_form.getValue('u_group_members');
// Comma separate list
var member_split = group_members.split(',');
// Loop over list of email addresses
for (var n = 0; n < member_split.length; n++) {
// Trim whitespace
var member_info = trim ? member_split[n].trim() : member_split[n];
// Email validation regular expression
var regEmail = /^\w+((-\w+)|(\.\w+))*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
// Check each item against regular expression
if (member_info.search(regEmail) == false) {
g_form.showFieldMsg('u_group_members', "Group Members contains an invalid email address. " + member_info, 'error');
//Do not submit
//g_form.submitted = false;
return false;
} else if (member_info.search(validRegExp) == true) {
g_form.setValue('u_group_members', group_members);
}
}
return true;
}
I'm glad you found a solution above, but I wanted to leave a comment as well, to ask if you've tried a try{} catch{} block to handle invalid data?
I think I have solved the issue. I made a completely separate function that checks the validation. The onSubmit calls the validation function and checks the return value. If the return value is false then it stops the form. Otherwise it is submitted even after multiple attempts with invalid data. I think this will do the trick. Let me know if anyone can see any issues. Thanks for the help.
function onSubmit() {
var isValid = checkGoogleGroup();
if (isValid == false) {
g_form.submitted = false;
return false;
}
}
function checkGoogleGroup() {
g_form.hideAllFieldMsgs('error');
//Group Name contain letters numbers and dashes only
var group_name = g_form.getValue('u_group_name');
// Group name regular expression
var regGrpName = /^([A-Za-z0-9\-]+)$/;
// Check name against regular expression
validGroupName = regGrpName.test(group_name);
if (validGroupName == false) {
g_form.showFieldMsg('u_group_name', "Group Name must contain only letters, numbers or dashes. ", 'error');
//Do not submit
return false;
}
//Check if google group already exists
var rec = new GlideRecord('u_broad_user_accounts');
rec.addQuery('u_account_email', new_group_email);
rec.query();
while (rec.next()) {
g_form.showFieldMsg('u_group_name',rec.u_account_email + " already exists as an account.",'error');
return false;
}
//Group Members Email List separated by commas
var group_members = g_form.getValue('u_group_members');
// comma separate list
var member_split = group_members.split(',');
// loop over list of email addresses
for (var n = 0; n < member_split.length; n++) {
// trim whitespace
var member_info = trim ? member_split[n].trim() : member_split[n];
// validation regular expression
var validRegExp = /^\w+((-\w+)|(\.\w+))*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
// check each item against regular expression
if (member_info.search(validRegExp) == -1) {
g_form.showFieldMsg('u_group_members', "Group Members contains an invalid email address. " + member_info, 'error');
return false;
}
}
}

check for alpha only colors using javascript

I am trying to check for alpha only charachters only on a webpage using javascript
Javascript
function AlphaOnly(x,fieldname) {
var valueToCheck=x.value;
var letters = /^[A-Za-z]+$/;
if(valueToCheck.length == 0) {
alert("Please Enter a " + fieldname);
x.focus();
return false;
}
else if(valuetoCheck.match(/[\W_]/)){
alert("Alpha only");
}
else if(letters.test(valuetocheck)) {
alert("its working");
}
}
It works if the field is empty but cant get it to work if its not alpha charachters entered
Also want to change the color of an element
function ChangeColor(x) {
x.style.backgroundColor="red";
}
I didnt put in the html as the functions are being called, they just wont do what they are suppose to.
Any help would be appreciated
Thanks
Rachael
The valueToCheck variable is not keeping consistent case, and that appears to be causing the problem here, because javascript's variable names are case-sensitive.
This fiddle shows a working example with nothing changed but the variable name fixed: http://jsfiddle.net/jt3RC/

Javascript Approved Number in RegExp [duplicate]

This question already has answers here:
Validate decimal numbers in JavaScript - IsNumeric()
(52 answers)
Closed 8 years ago.
I'm trying to change a value user enters to a true number (ex. 15 or 144.38). If it has unapproved characters (ex. $,) then they should be stripped. Also if user enters value with multiple periods (ex. 43.14.14) then I want to clear entire value. I was able to do step 1 but can't figure step 2, please advise. Here's my code so far
http://jsbin.com/otawiVa/1
function myFunction()
{
var str = document.getElementById("number_field").value;
var res = str.replace(/[^0-9.}]/g,"");
document.getElementById("approved_number").innerHTML=res;
}
change your function to
function myFunction()
{
var str = document.getElementById("number_field").value;
var res = str.replace(/[^0-9.}]/g,"");
if (res.indexOf('.') !== res.lastIndexOf('.')) {
document.getElementById("approved_number").innerHTML="";
} else {
document.getElementById("approved_number").innerHTML=res;
}
}
Example here:
http://jsbin.com/UNOHoYek/1
See http://jsbin.com/OKoJuloQ/3/ for a possible answer.
Changing user input without providing feedback is probably not a good idea.
Better to just handle what can be taken as a number and report the rest.
window.alert is just one way to report it.
The important bits are the conversion to Number and testing against NaN.
CODE (also available via link above)
<!DOCTYPE html>
<html>
<body>
<input type="text" value="" id="number_field">
<button onclick="myFunction()">Submit</button>
<p id="approved_number"></p>
<script>
function myFunction() {
try {
var str = document.getElementById("number_field").value;
// var res = str.replace(/[^0-9.}]/g,"");
var res = str;
if (Number.isNaN(Number(res))) {
window.alert(res + " is not a number (NaN)\nOnly digits, decimal point,\nand exponent (e.g. 3.2e4) are allowed");
} else {
document.getElementById("approved_number").innerHTML=Number(res).toString(10);
}
} catch (exception) {
window.alert(exception);
}
}
</script>
</body>
</html>

Javascript replace function won't remove the string [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 8 years ago.
I have no idea why this doesn't work, but doing some validation functions and trying to output a dynamic message to an alert when they hit submit and forgot to fill out a field. It works only on the second click of the submit button, as far as removing the string, everything else works when it should.
Here's the code:
var fname = $('#fname');
var lname = $('#lname');
function validatefname(){
var a = fname.val().length;
if(a < 2) {
fname.prev().addClass("error");
if(msg.search("First Name") == -1) {
msg+= "-Please enter your First Name\n";
}
return false;
} else {
fname.prev().removeClass("error");
msg.replace(/Please enter your First Name\n/g, "");
return true;
}
}
fname.blur(validatefname);
fname.keyup(validatefname);
step4submit.click(function(){
if(validatefname()) {
step4form.submit();
return true
} else {
msg+= "\nPlease fill out the fields marked in red";
alert(msg);
msg = "";
return false;
}
});
String.replace returns a new string, rather than editing the string that makes the replace call.
You need
msg = msg.replace( blah )
In JavaScript, Strings are immutable, they can never change. So if you are calling a function to modify a string in some way, that function will return a new string with your changes, rather than modify the original string.
Change the line that is performing the replacement to save the result of the replacement back into the original variable, like so:
msg = msg.replace(/Please enter your First Name\n/g, "");
(there are various performance and safety reasons for this, but that is for another day/another question).
Try changing
msg.replace(/Please enter your First Name\n/g, "");
to
msg = msg.replace(/Please enter your First Name\n/g, "");

Categories

Resources