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

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, "");

Related

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

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!";
}
}

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;
}
}
}

JavaScript First Letter Capitalisation Not Working

Firstly, this is my first time working with JavaScript so it is probably just me missing something very simple.
All I want to do is get the value of a text box and make an alert with the first letter capitalised. I have everything working, the first letter isn't actually being capitalised.
This is how I am calling the function:
else
{
input = document.getElementById("search").value;
'input'.search();
alert(input);
}
This is the function it self:
function search(string)
{
return string.charAt(0).toUpperCase();
}
this is the correct code
else
{
input = document.getElementById("search").value;
input =search(input);
alert(input);
}
Try this:
input = search(input);
Instead of:
'input'.search();
You aren't changing input at all. Try:
else
{
input = document.getElementById("search").value;
alert(search(input));
}
If you want to permanently change input Try:
else
{
input = document.getElementById("search").value;
input = search(input);
alert(input);
}
A couple of things wrong here,
firstly,
search(input)
instead of
'input'.search()
secondly,
string is immutable so you'll have to do,
input = search(input);
alert(input);
.
.
.
function search(str) {
return (str.replace(str.charAt(0), str.charAt(0).toUpperCase()));
}
Your question is not pretty clear to me, but I assume that you want, if your input string is "hello" , you want the output as "Hello".
Try this
call the method and alert the message:-
alert(search(input));
in the method:-
return Character.toUpperCase(input.charAt(0)) + input.substring(1);
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase()+this.slice(1);
}
var searchField = document.getElementById("search");
var query = searchField.value;
searchField.value = query.capitalize();
function search(query) {
// query api or something...
}
The answers are correct, but you will have only the first letter in the alert box.
If you don't want only the first letter, here is the solution:
function search(string)
{
return string.substring(0,1).toLocaleUpperCase() + string.substring(1);
}
From https://stackoverflow.com/a/30123193/2379208

Javascript to verify specific String from textbox

Here what the textbox result looks like,
Please add the following DNS entries
144.68.238.87 name.domain
144.68.238.88 name.domain
144.68.238.89 name.domain
The goal is to validate name.domain by making sure that the user replace name.domain to server name on textbox before submit it. If the user doesn't replace name.domain with their server name, then it will send alert message and return false until user replace it correctly.
Here is my codes,
function DomainValidate() {
var arrayOfLines = document.getElementById('txt').value.split('/n');
arrayOfLines.shift(); //use shift to skip the first line
for (i = 0; i < arrayOfLines.length; i++) {
//somewhere here need to split to get name.domain and then verify it
var domainName = arrayOfLines[i].split(" ", 2);
if(domainName.Equals("name.domain")
{
alert("You must replace name.domain to your new server name");
return false;
}
}
}
I am not sure if these are correct since I couldn't debug the javascript.
First issue I can see is that your character for the newline is incorrect. It should be \n not /n. Second issue I see is that i is a global variable, when it should be local. Third issue is that arrayOfLines[i].split(' ', 2); returns an array, but you are treating it like it returns a string on the next line if (domainName.Equals('name.domain').
With those corrections your code would look more like this:
function domainValidate() {
var arrayOfLines = document.getElementById('txt').value.split('\n');
arrayOfLines.shift(); //use shift to skip the first line
for (var i = 0; i < arrayOfLines.length; i++) {
var line = arrayOfLines[i].trim();
// Grab the second part of the split line, which represents the domain name
var parts = line.split(' ');
var domainName = parts[parts.length - 1];
if (!domainName || domainName === 'name.domain') {
alert("You must replace name.domain to your new server name");
return false;
}
}
}
As far as I can tell without testing, this should work as expected. The best way to test this though is with jsfiddle. Add your html and this script and call it to see if it produces the expected result.
Easiest way that I think
Suppose the id of textbox is domainTxt
src = document.getElementById("domainTxt");
if(verifyInput(src.value)){
//submit your form here
} else
{
return false;
}
function verifyInput(txtVal){
if(txtVal.indexOf("name.domain") >-1){
return false;
}else {
return true;
}
}

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/

Categories

Resources