Im trying to validate a form for an assignment and have hit a wall, apologies in advance if I miss the obvious Im quite new to programming.
Im trying to validate multiple form fields to check for erroneous data before the form is submitted. I have a separate function in an external file for each type of field that holds a regex and checks the input and acts on the result.
My problem is that I built the functions to need parameters to work.
At the moment I have the functions placed in the onblur section of each field to validate and provide feedback as the user progresses through the form. Now when I want to build a master function to call all the functions in the onsubmit section of the form my referencing wont work, I must be missing something trivial but I've gone over the code again and again.
Sample onblur code:
<tr><td>Any number</td>
<td><input type="text" id="anyNumber" name="anyNumber" size="10" maxlength="4"
onblur="validateNumber('anyNumberP', 'anyNumber', anyNumber.value);"/>
</td>
<td>
<p style="display:inline;" id='anyNumberP'> </p>
Sample External File Function:
function validateNumber(pId, id, value){
var inputCorrectMsg = "<--Input is Valid";
var inputIncorrectMsg = "<--Error: Please enter a number.";
var regEx = /\d\d\d\d/;
var trimValue = value.replace(/^\s+|\s+$/, '');
var trimValue1 = trimValue.replace(/^0+/g, '');
var result = regEx.test(trimValue1);
if (result == true){
feedbackColour(pId, id, result, inputCorrectMsg);
} else{
feedbackColour(pId, id, result, inputIncorrectMsg);
}
return result;
}
What I need to be able to do from the external file:
function lastCheck(){
var result1 = validateNumber('anyNumberP', 'anyNumber', anyNumber.value);
var result2 = validateOtherStuff('etc', 'etc', 'etc');
if(result1 && result2 = false){
return false;
}else{
return true;
}
}
I tried the referencing the function like above but it wont work in my master function. Wether its the reference to the function or the variables passed to the function im not sure. If anyone can help id REALLY appreciate it, thanks!
Related
I THINK i have managed to write a script. I just can not make a textfield in HMTL to enter the missing data. It it supposed to receive the keyword from a text field on submit click and navigate to the URL.
I have tried multiple ways of forms and everything. Should have installed VB.net and this would have been done in 5 min.
function urlMaker(keyword) {
var base = "https://www.example.com/list.php?q=";
var ending = "&dhd=1&hdd=low&dtt=list";
var url;
url = base + keyword + ending;
window.location.assign(url);
}
In short words:
I need to know how to create a HTML page with a textfield and a submit button. When I submit it takes the text from the field and run the function and feeds it with the keyword from the textfield. When function has ran it redirects browser.
I'm guessing you have a form like this.
Just attach a submit event-listener to it:
document.querySelector("#search").addEventListener("submit", urlMaker)
function urlMaker(event) {
let keyword = document.querySelector("#keyword").value;
let base = "https://www.example.com/list.php?q=";
let ending = "&dhd=1&hdd=low&dtt=list";
let url;
event.preventDefault();
url = base + keyword + ending;
window.location.href = url;
}
<form id="search">
<input type="text" id="keyword" />
<button type="submit">Search</button>
</form>
So I have a HTML form with a keypress event listener recording the charCode of the key pressed and then convert that charCode to a String of the letter related to the key.
Each time a letter is entered to the form, a new entry is created in input_array[].
I have each letter in the alphabet stored as a SVG within JS variables in a different part of my main.js file and I would like to be able to read what letters have been stored in input_array[] and then display the SVG appropriate to that letter on a new page once the form has been submitted.
I've tried using the method below to extract the data from the array, but it fires on the first keypress and therefore I can't get all of the array data to then display the 4 letters. I also feel like there has to be a more efficient way.
var letter_one = input_array[0];
var letter_two = input_array[1];
var letter_three = input_array[2];
Here's a JSFiddle, to show a basic version of what I'm trying to do. If you open the console you will see how input_array[] is being created.
I'm still very new to this language, so any help would be greatly appreciated.
As you suspected, this is much simpler than you're making it :)
When the form is submitted you can just snag the value from the input:
function handleSubmit() {
var val = document.getElementById('user_input').value;
validate(val);
console.log(val);
var letter_one = val[0];
var letter_two = val[1];
var letter_three = val[2];
var letter_four = val[3];
return false; // stops POST for dev
}
https://jsfiddle.net/1htpm6ag/
That being said, if you are actually doing this on a POST then on the page you are POSTing to you'll have to snag this from the POSTed form data, which is entirely different. Are you trying to do this in client side JS or a POST handler?
If I am understanding you correctly is sound like you want to do the following.
On Page 1 user enters text into textfield.
On Submit send that text to page 2.
On Page 2 convert that text into an array of letters to associate with SVG paths to display.
If the above is the case you need a lot less javascript.
Page 1: Should only have your form with your text box and a submit button so the data is submitted to the next page using the GET method.
Page 2: Here is where you will need the Javascript to retrieve that data sent across and process it into your array of letters. I would also filter for non-letter characters as well.
I have created an example form in the code below that submits to itself and then the javascript script tag will pull the variable from the url and process it into an array of letters. In your case you would move the Javascript to page 2.
<script type="text/javascript">
(function(){
function getParamValue(param) {
var urlParamString = location.search.split(param + "=");
if (urlParamString.length <= 1) return "";
else {
var tmp = urlParamString[1].split("&");
return tmp[0];
}
}
function isLetter(c) {
return c.toLowerCase() != c.toUpperCase();
}
var user_input = getParamValue('user_input');
var char_array = null;
if(user_input !== ''){
char_array = user_input.split("");
char_array = char_array.filter(isLetter);
for(var i in char_array){
console.log('Char ' + i + ' = ' + char_array[i]);
}
}
})();
</script>
<body>
<form id="user_form" class="" action="?" method="GET">
<input type="text" name="user_input" />
<input type="submit" value="submit">
</form>
</body>
I'm making a form to change the password.
I ask for the current password and then there are two fields to put the new password.
I have two problems:
First: I need to check if the two fields of the new password are equal.I used onsubmit to check that.If they are the same, submit.If not it should show a message saying something.The problem is that it doesn't display.This is the code:
function checkform(){
var pass=myForm.pass.value;
var new=myForm.new.value;
var new=myForm.new2.value;
if(new!=new2){
document.getElementById("message").style.display='block';
document.getElementById("pass").value=" ";
document.getElementById("new").value=" ";
document.getElementById("new2").value=" ";
return false;
}else{
return true;
}
}
When I insert diferent new passwords it still submits, but if I delete that document.getElementById it doesn't submit.
Second problem: I have a php page (not using frameworks, just php) that is a class.When I want to acess a function of that class all I need to do is
include("class.php");
$my = new the_class(); $response= $my->check();`
The check() function retrives the password, so then I can check if the value from the field pass is the same as the $response.But how can I put this on the function checkform()? It doesn't work this way.
Don't take the variable name as new its a keyword it is reserved for creating an instance, so better take some other name to the variable and you may get what you're looking for.
**You Try below code**
function checkform(){
var pass=myForm.pass.value;
var new=document.getElementById("new").value();
var new=document.getElementById("new2").value();
if(new!=new2){
document.getElementById("message").style.display='block';
document.getElementById("pass").value=" ";
document.getElementById("new").value=" ";
document.getElementById("new2").value=" ";
return false;
}else{
return true;
}
}
I'm having a problem with a dynamically updated form in Google Apps Script. The form is in an HTML template (say index.html) as follows:
<form id="login">
<p>Enter username and password below, or use the links to the right for more services:</p>
<input type="text" placeholder="username" id="username" name="username" />
<input type="password" placeholder="password" id="password" name="password"/>
<input type="button" value="Login" onclick="google.script.run.withSuccessHandler(form_login).processForm(this.parentNode)" id="login_button" />
</form>
There is also a div designated for the output:
<div id="output">test value</div>
And a javascript function to update said div:
function form_login(msg) {
var div = document.getElementById('output');
div.innerHTML = div.innerHTML+msg;
}
The function within the gs file that deals with this is as follows:
function form_login(formObject) {
//connect to users spread sheet
var userssheet = SpreadsheetApp.openById("SPREADSHEET-ID-STRING");
//get variables handed over and existing on page
var username = formObject.username;
var pass = formObject.password;
//get where data range in spreadsheet
var searchrange = userssheet.getActiveSheet().getDataRange();
//check if username exists and return password (change to check if password and username are correct and)
if (find(username, searchrange)) {
var enteredpassword = searchrange.getCell(find(username, searchrange),4).getValue();
var message = (username+" Found! Password is "+enteredpassword); //get password value
} else {
var message = (username+" Not Found!");
}
//check if password entered is correct
if (enteredpassword) {
if (enteredpassword==pass) {
message = message + "Correct Password";
} else {
message = message + "Incorrect Password";
}
}
return message;
}
(Obviously I'm still building the functionality).
The problem, which will probably turn out to be an obvious oversight on my part, is with the gs function. Whatever it returns is outputted as 'undefined' into the HTML. Even when i change return message; in the function to something like return "hello";, I still get undefined appended to the output div (I tried using toString(); in the javascript function, but that didn't change anything).
Any ideas? What am I missing?
Found out what the problem was, and as I assumed, it was a mistake on my side. The button action (which I copied then edited from developers.google.com/apps-script/guides/html/communication#forms was:
onclick="google.script.run
.withSuccessHandler(form_login)
.processForm(this.parentNode)"
The problem was that I forgot to change processForm to the new gs function name: form_login. I changed it (to do_form_login, and changed the function name in the code to avoid confusion with the javascript code), and it worked like a charm (:
Note: Thanks Sandy for the help, you made me scrutinize the code and find out this mistake.
I have just started with JavaScript and want to validate a form. All the tutorials I've found create an alert for feedback, but I'd like to use onblur and give an error message next to the field. I managed to do the two functions separately but can't merge them. I'd really appreciate your help!
This is what I came up with, but it doesn't do what I need:
function validateFirstName()
{
var x=document.forms["demo"]["firstname"].value;
if (x==null || x=="" || x==)
{
function addMessage(id, text)
{
var textNode = document.createTextNode(text);
var element = document.getElementById(id);
element.appendChild(textNode);
document.getElementById('firstname').value= ('Firstname must be filled out')
}
return false;
}
}
So the following is a simple way to validate a form field by checking the value of an input when the form is submitted. In this example the error messages are just sent to the div element about the form but this should still help you out.
The HTML code looks something like this:
<div id="errors"></div>
<form onSubmit="return validate(this);">
<input type="text" name="firstName" placeholder="What's your first name?">
<button type="submit" value="submit">Submit</button>
</form>
The Javascript code looks something like this:
function validate(form) {
var errors ='';
if(form.firstName.value =="") {
errors += '<li>Please enter your first name</li>';
}
if(errors !='') { //Check if there are any errors, if there are, then continue
var message = document.getElementById("errors"); //assigns the element with the id of "errors" to the variable "message"
message.innerHTML = "<ul>" + errors + "</ul>"; //adds the error message into a list with the error message into the HTML
return false;
} else {
return true;
}
}
Once you understand this you should be able to figure the rest out on your own or go to http://www.w3schools.com/ and check out the javascript section to help you out.
I'm not sure what you really looking for. If I understood right (and I can be very wrong) you are looking for something like:
var x = undefined; // Can be undefined, null, or empty string
if (x==null || x=="" || x==undefined) { // do no forget to check for undefined
function addMessage(id, text) {
// Your validation code goes here
alert(id + text);
};
addMessage(1234, "Mandatory field!");
}
Note, there are several ways to do it. I just showing the simplest way I can think of...