How change HTML document after false onsubmit without manual page reloading - javascript

I want to change HTML document elements when the onsubmit event handler returns false.
Inside function validate() a cookie is set (BTW, is there simpler way than cookie?).
Onload event handler checkIfFalseSubmit() checks cookie and runs function changeDocument() that changes document.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>How change document after false onsubmit without manual page reloading</title>
<script type="text/javascript">
function validate() {
// http://www.javascripter.net/faq/settinga.htm
var today = new Date();
var expire = new Date();
expire.setTime(today.getTime() + 1000*5000);
document.cookie = "cookie1=a; expires=" + expire.toGMTString();
alert ("Always false - just for testing");
return false;
}
function changeDocument() {
myDiv.innerHTML = "Form validation failed";
}
// http://stackoverflow.com/questions/10730362/javascript-get-cookie-by-name
function getCookie(name) {
var parts = document.cookie.split(name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
function checkIfFalseSubmit() {
if ( getCookie("cookie1") == "a")
changeDocument();
}
</script>
</head>
<body onload="checkIfFalseSubmit()">
<div id="myDiv">Before Submit</div>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post" name="f" onsubmit="return validate();" >
<input type="text" name="myName" /><br/>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Problem is that onload happens only when I manually reload page.
Without reloading the alert is shown but the document remains unchanged.
Is there another event that I should use instead of onload for my purpose?
Is there another way to get my goal?

I think it is overly convoluted. You don't have to use cookies and and body onload event. Just keep validate() called on form submit and changeDocument() to display your message.
Inside of validate() if validation failed call changeDocument() before returning false.

Related

How do I get my redirect to run successfully when a user selects choice between two radio buttons?

I cannot get my redirect to successfully work on the users choice selected between two radio buttons.
I have tried both the window.location.href and the window.location.replace to try get me redirect to work. All files are saved the same folder as the current file but neither option is successfully redirecting onsubmit of the form after a users chooses between two options given in the radio buttton the is supposed to link to one of two simple math functions. Note that the function also includes a cookie that remembers the users radio button selection.
//* calling math function according to checked radio button.
//* creating cookie to remember users choice finish
window.onload = function() {
if (document.cookie.length != 0) {
var nameValueArray = document.cookie.split("="); //*splits cookie at =
to
return correct boolen value 'true'
document.button = nameValueArray[1]; //* creates array between button
choices
getElementById("converter").value = nameValueArray[1];
}
}
function myFunction() {
var buttonChoiceGrams = document.getElementById("grams").checked;
var buttonChoiceOunces = document.getElementById("ounces").checked;
if ((buttonChoiceGrams == false) && (buttonChoiceOunces == false)) {
var msg = alert('You must select your weight conversion choice!');
} else if (buttonChoiceGrams == true) {
alert(buttonChoiceGrams);
document.buttonChoiceGrams = buttonChoiceGrams;
document.cookie = "buttonGrams" + true + ";expires=Wed, 1 Jan 2020
01: 00: 00 UCT;
";
window.location.replace = "grams_to_ounces.html"; //* redirect to math
function selected in radio button
} else if (buttonChoiceOunces == true) {
alert(buttonChoiceOunces);
document.buttonChoiceOunces = buttonChoiceOunces;
document.cookie = "buttonOunces" + true + ";expires=Wed, 1 Jan 2020
01: 00: 00 UCT;
";
window.location.replace = "ounces_to_grams.html"; //* redirect to math
function selected in radio button
}
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Weight converter selection</title>
</head>
<!--radio button weight convertion choices-->
<body>
<form action="" method="POST" id="converter" onsubmit="myFunction()">
<label><strong>Weight conversions:</strong></label>
<br /> <br/>
<input type="radio" name="converter" value="grams" id="grams" />Grams to Ounces
<br />
<input type="radio" name="converter" value="ounces" id="ounces" />Ounces to Grams
<br /> <br/>
<div id="msg"></div>
<input type="submit" value="Okay" />
</form>
</body>
</html>
Try using the full file path and window.location.href
window.location.href="file://host/path/grams_to_ounces.html"
In my example above you will need to replace the host/path/ with your own file structure.
Here is what happens in your situation:
User submits form
myFunction() is executed
The browser continues processing submission and thus goes to URL defined in <form action="...">
How to fix it?
return false; at the end of myFunction(). This will interrupt further processing of form submission. Redirects with window.location will start having an effect.

Why won't the form value show up?

I am creating a simple form, and I want to write to the console the value of the input once the form has been submitted and successfully validated. However, when I go to test my current progress, I input a random piece of text and nothing shows up, even in the console. Here is the code I have now (excluding any commented out code):
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script language="Javascript">
window.onload = function() { // So the DOM can be defined
function validateForm() {
var form = document.forms['encrypt']['text'];
if(form == "") {
alert("Enter piece of text to encrypt");
return false;
} else {
console.log(form.value);
}
}
}
</script>
</head>
<body>
<form name="encrypt" action="#" onsubmit="return validateForm()">
Text: <input type="text" name="text">
<input type="submit" name="Submit and Encrypt!">
</form>
</body>
</html>
Even when I type nothing and submit the form, the alert doesn't pop up. There was other posts related to form problems, but they don't have any relation to mine. Is there something wrong with my code? What is the problem and how can I fix it?
Edit: I realized window.onload only executes the code inside of it when the window is loading. After that, all functions cease to exist. In addition to removing the onload handler, I had to relocate the validation function within the body.
Your validateForm function is only visible within your onload function. Additionally, you were comparing the form to an empty string, not the value within the text field in the form. The console.log would also not have been visible, because the page refreshes before you can see it.
Below is the code with those three things fixed.
<html>
<head>
<meta charset="utf-8" />
<script>
function validateForm() {
var text = document.forms['encrypt']['text'].value;
if(text == "") {
alert("Enter piece of text to encrypt");
return false;
} else {
alert("Entered '" + text + "', refreshing now.");
return true;
}
}
</script>
</head>
<body>
<form name="encrypt" action="#" onsubmit="return validateForm()">
Text: <input type="text" name="text">
<input type="submit" name="Submit and Encrypt!">
</form>
</body>
</html>
There's no reason to wrap this function in an onload event handler. And doing so is limiting the scope of the function definition so that the code which tries to call it can't actually see it. (That is, after onload completes, the function you defined is no longer in scope and ceases to exist.)
Just remove the handler and define the function directly:
<script language="Javascript">
function validateForm() {
var form = document.forms['encrypt']['text'];
if(form == "") {
alert("Enter piece of text to encrypt");
return false;
} else {
console.log(form.value);
}
}
</script>
The problem is your function validateForm() is not accessible in the scope when you click the submit. You can verify this by call this function in the console.
In your code, it's defined inside the window.onload, so please move the function out of it.
Try to remove window.onload = function() { and just keep the validateForm function.

I'm trying to make a specific input into a text area call a specific javascript function, but it won't work

So to give a little bit of detail, I'm trying to make an interactive fiction game or text adventure. I have a form where all the "commands" for the game will be typed. I'm working on the first command which is the string "start" to call a prompt. Just to test the code, I have the prompt say "success!" when done correctly. What's happening though, is as soon as I open the web browser to test, the prompt triggers before I even type a command. Here's the code.
<html>
<head>
<script type="text/javascript" src="scripts/engine.js"></script>
</head>
<body>
<form id="testForm"> <input type="text" name="">
</form>
</body>
</html>
And then here's the javascript.
var input = document.getElementById("testForm");
if (input = "start") {
prompt("Success!");
}
Try this:
<html>
<head>
<script type="text/javascript" src="scripts/engine.js"></script>
</head>
<body>
<form id="testForm">
<input type="text" id="myInput">
</form>
<script>
var myForm = document.getElementById("testForm");// get the form element.
var myInput = document.getElementById("myInput");// get the input element
myForm.onsubmit = function() { // when the form is submitted, execute this function.
if (myInput.value == "start") { // if the value of the input equals 'start', show prompt.
prompt("Success!");
}
return false; //return false, so the form doesn't get submitted.
};
</script>
</body>
</html>
Edit:
Added submit event handler, that returns false, so the form does not get submitted.
You need to check the value of the input like so
var input = document.getElementById("inputID");
var value = input.value;
The code will always be ran straight away because it has no event handler. You could add a button which triggers it
document.getElementById('button').addEventListener('click', function () {
var input = document.getElementById("inputID");
if (input.value === 'start') {
// Do something
}
});
Or if you prefer on the forms submit event:
document.getElementById('testForm').addEventListener('submit', function () {
var input = document.getElementById("inputID");
if (input.value === 'start') {
// Do something
}
});

validation not working for js

<html>
<head>
</head>
<body>
<form class="form-horizontal cmxform" id="validateForm" method="get" action="../../course_controller" autocomplete="off">
<input type="text" id="course_name" name="course_name" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:validate_course_name();">
<label id="course_name_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<button type="submit" name="user_action" value="add" class="btn btn-primary" onClick="javaScript:validate();" >Save</button>
<button type="reset" class="btn btn-secondary">Cancel</button>
</form>
<script type="text/javascript">
/**** Specific JS for this page ****/
//Validation things
function validate_course_name(){
var TCode = document.getElementById('course_name').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
course_name_info.innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
course_name_info.innerHTML=" ";
return true;
}
}
function validate(){
validate_course_name();
}
</script>
</body>
</html>
So this the code ...I am applying alpha numeric validation on one field but even if i give invalid input like some other characters the form is getting submitted where am i doing it wrong?
i am very new to this web so any help will be appreciated:)
There are several issues here. First, you are never returning the result, so even if the function results in false, it is not returned to the form so the form goes on its merry way. To fix, you can add an onsubmit to the form tag, or even better attach an onsubmit event to the form.
onsubmit="return validate();"
Second, you only need the one function, calling a function from another function is not necessary here, and results in an additional level of difficulty since you will need to return the result to the wrapper function, which will then need to return that result to the form.
//Validation things
function validate() {
var TCode = document.getElementById('course_name').value;
if (/[^a-zA-Z1-9 _-]/.test(TCode)) {
course_name_info.innerHTML = "Please Enter Only Alphanumeric or _,-,' ' ";
return false;
} else {
course_name_info.innerHTML = " ";
return true;
}
}
Here is a working fiddle of your example: http://jsfiddle.net/duffmaster33/nCKhH/
Your validate() function should return the result of the validation. Currently the result of validate_course_name is discarded. In other words, it should look something like this
function validate(){
return validate_course_name();
}
Also you might want to move the validation to
<form onsubmit="return validate()" ...
You need to wrap course_name_info with a getElementById
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
and then change the style of the label so the font isn't white on white background.
Hope that fixes it.

How to grab the onSubmit event for a form?

I want to know how to grab the onsubmit event from a form to do some form validation, because I don't have access to it directly. (I am writing a Wordpress plugin for comments, so don't have direct access to the form tag or the submit button.)
I got so frustrated trying to do this for my plugin that I have written a Hello World version below. I want it to show the 'Hello World' alert when I load the page, and the "form submitted" alert when I click on the submit button. Instead, it shows both pop ups when the page loads.
Here is my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>Test</h2>
<form action="#" method="post" id="commentform">
<p><input type="text" name="author" id="author" size="22" tabindex="1" />
<label for="author"><small>Name (required)</small></label></p>
<p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />
</form>
<script type="text/JavaScript">
<!--
alert("Hello world");
var formCheck = document.getElementById("commentform");
formCheck.onSubmit = doMapping();
function doMapping() {
alert("form submitted");
return false;
}
-->
</script>
</body>
</html>
Change this:
formCheck.onSubmit = doMapping()
to this:
formCheck.onSubmit = doMapping
When you add parenthesis to the end of a function you execute that function. When you assign a function (or pass it as a parameter to another function) you need to omit the parenthesis as that is the way to retrieve a function pointer in JavaScript.
Edit: You will also need to move the declaration of the doMapping function above the assignment of that function to the onsubmit event like this (good catch tvanfosson!):
function doMapping() {
alert("form submitted");
return false;
}
formCheck.onSubmit = doMapping();
However if the doMapping function is not used elsewhere you can declare the doMapping function as an anonymous function like this:
formCheck.onSubmit = function() {
alert("form submitted");
return false;
}
which seems a bit cleaner to me.
Using jQuery.
$(document).ready( function() {
$('#commentform').submit( function() {
alert('form submitted');
return false;
});
});
Thank you! Actually I solved it another way, using both Andrew's suggestion and the window.onload event - I think the problem was partly because the element hadn't actually loaded.
window.onload = function(){
if (document.getElementById("commentform")){
document.getElementById("commentform").onsubmit = doMapping;
}
}
function doMapping(){
alert("form submitted");
return false;
}

Categories