How to change textContent via javascript? - javascript

I have a registration form page, and there is empty div i want to use to display errors. To check forms before triggering php script i use javascript:
function errorHandler(){
var loginIn;
var passIn;
loginIn = document.forms["regForm"]["login"].value;
passIn = document.forms["regForm"]["password"].value;
if (loginIn == "" || loginIn == null) {
alert("LOGIN CANNOT BE EMPTY");
return false;
}
}
It works fine, and alert message do appear when i call them like this:
<form name="regForm" action= "save_user.php" onsubmit="return errorHandler()" method="post">.
But there is as i mentioned before a div inside of the form: div id ="errorArea"></div> and when i try to put a text inside of this div like this:
function errorHandler(){
var loginIn;
var passIn;
var erorAreaMessage;
loginIn = document.forms["regForm"]["login"].value;
passIn = document.forms["regForm"]["password"].value;
erorAreaMessage = document.getElementById('errorArea').textContent;
if (loginIn == "" || loginIn == null) {
erorAreaMessage = "LOGIN CANNOT BE EMPTY";
return false;
}
}
Nothing happens, can someone explain me why?

You need to put the value inside the <div>. That can done by setting the innerHTML or textContent property to your error-message.
Try this -
...
if (loginIn == "" || loginIn == null) {
document.getElementById('errorArea').textContent = "LOGIN CANNOT BE EMPTY";
return false;
}}

Related

How can I use conditional logic with JavaScript form validation?

I have the following JavaScript function which is triggered by an onclickevent and is working fine.
<script>
function validateForm() {
let xgame_name = document.forms['myForm']['game_name'].value;
if (xgame_name == '') {
alert('Game Name must be filled out');
return false;
}
let xdev_name = document.forms['myForm']['developer_name'].value;
if (xdev_name == '') {
alert('Developer Name must be filled out');
return false;
}
let xdev_email = document.forms['myForm']['email'].value;
if (xdev_email == '') {
alert('Developer Email must be filled out');
return false;
}
let xdemo_rom = document.forms['myForm']['demo_rom'].value;
if (xdemo_rom == '') {
alert('Demo Rom must be uploaded');
return false;
}
let xpromo_image = document.forms['myForm']['promo_image'].value;
if (xpromo_image == '') {
alert('Promo must be uploaded');
return false;
}
}
</script>
I am trying to add this so if one of the radio buttons with a value of 1 is selected on the form it will check an additional field to see if there is a value and show an alert.
let xcartridge = document.forms['myForm']['cartridge'].value;
if (xcartridge == '1') {
let xcover_art = document.forms['myForm']['cover_art'].value;
if (xcover_art == '') {
alert('If Cartridge is selected you must proved Cover Art');
return false;
}
}
This follows the same syntax of the above code example that is working but this does not send an alert but rather the form validation does not work at all. How can I get the alert to show when one fields condition is met, where it is 1 and that prompts an alert on an additional field?

return false wont stop refreshing the page plus no error messages printed

This is my html code where i call a validate function to check for empty fields in a form.
<form id="myForm" onsubmit= "doThese()">
And here is my javascript function which checks if any fields are empty and prints a message returning false or if everything is ok switches to the next page.
<script>
function doThese(){
var i = document.getElementById("txt_name").value;
var y= document.getElementById("lname").value;
var b=document.getElementById("txt_email").value;
var c=document.getElementById("pass1").value;
var d=document.getElementById("pass2").value;
var mess.document.getElementById("errorMsg");
if(i==null || i== "",y==null || y== "",b==null || b== "",c==null || c== "",d==null || d== ""){
mess.style.color= "#ff6666";
mess.innerHTML="Please fill all the fields";
return false;
}
else{
parent.location='arxiki.html';
}
}
</script>
I've tried anything i could find but nothing would work.The page is still refreshing and no error messages would be printed even if when i submitted the form with all empty fields.Im thinking that it doesnt reach the function in the first place but i can't find a reason for that.. Any ideas ??
Following Code will work fine for you
HTML Form Code
<form id="myForm" onsubmit="return doThese();">
Java Script
<script>
function doThese(){
//Response.Write("alert('Check Point One!');");
var i = document.getElementById("txt_name").value;
var y= document.getElementById("lname").value;
var b=document.getElementById("txt_email").value;
var c=document.getElementById("pass1").value;
var d=document.getElementById("pass2").value;
var mess=document.getElementById("errorMsg");
//Response.Write("alert('Check Point two!');");
if(i==null || i== ""|| i== " "||y==null || y== ""||b==null || b== ""|| b== " "||c==null || c== ""|| c== " "||d==null || d== ""|| d== " ")
{
//Response.Write("alert('Check Point three!');");
mess.style.color= "#ff6666";
mess.innerHTML="Please fill all the fields";
return false;
}
else{
parent.location='arxiki.html';
}
}
</script>
Replacements
Replace , with || in IF Condition
Add another condition xxx== " " Because sometimes it seems to be empty but field have a space in it
onsubmit="return doThese();" Instead of onsubmit="doThese()"
Un-comment the //Response.Write("alert('______');"); to check if the function reached at this point

Form is submitting even after failing Javascript validation?

I have a form called here:
<span class="aligncenter button">Submit</span>
And I have a JavaScript function here:
if (myForm == 'newIncident')
{
var vDemAge = document.forms['newIncident']['demAge'].value;
var vBibNumber = document.forms['newIncident']['bibNumber'].value;
// Run through validations before submitting form
validateTime();
validateDate();
validateAge();
validateGender();
validateLocation();
validateType();
validateDisposition();
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}
else
{
document.getElementById(myForm).submit();
}
So I have each of the validations as a separate function that I am calling in sequence when submitting the form. If I comment out the "document.getElementById(myForm).submit();", the validations run as expected. However, if I leave it uncommented, it submits every time even if the validations fail. How can I stop this from happening?
Thanks!
EDIT:
So this is one of the validations I'm running. They're all structured the same way. Somewhere I should be returning a boolean true/false? How exactly would I insert that in this one below?
function validateDisposition()
{
var vIncidentDisposition = document.forms['newIncident']['incidentDisposition'].value;
if (vIncidentDisposition == '')
{
document.forms['newIncident']['incidentDisposition'].className = 'required';
}
else
{
document.forms['newIncident']['incidentDisposition'].className = 'formborder';
}
}
assuming your validation functions return a bool, you should have something like
if( validateTime() && validateDate() && validateAge()... etc ) {
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}
I got it working! The boolean idea put me on the right path. Thanks!
I just added a "return true" and "return false" to each of the validations, then used the answer above with the "&&" if to build the logic into the myform "if". If it doesn't pass all of them the else does a "return false". Works like a charm!

How do I use two document.InnerHtml in javascript?

I am trying to write a simple script to allow for a second box to open at the bottom of the screen when the form returns false. What I really wanted, is the form to jump to the top of the form when it returns false, but this code below is my second choice. But when I try to add a document.getElementById("...").innerHTML = ... for the second one, the form returns true every time and this doesn't work.
This code works with only one:
if (firstname == null || firstname == "") {
document.getElementById("err_firstname").innerHTML = "<span class='errorbar'>*Required Field</span>";
return false;
}
And this code is what I am trying to accomplish but not working; I need to not allow just one html box to open, but both:
if (firstname == null || firstname == "") {
document.getElementById("err_firstname").innerHTML = "<span class='errorbar'>*Required Field</span>";
document.getElementById("err_allerrors").innerHTML = "<span class='errorbar'>*You Must Fill Out All Required Fields</span> ";
return false;
}

Make a submit button outside the form element - isn't working

I want to make a button outside the form element that will check whether or not the inputs has been filled, if they are, then submit the form, if not, do something else (like prompting an alert or something).
I have made this fiddle, and it will not work:
http://jsfiddle.net/fe9Nk/
HTML:
<form action="javascript:alert('submitted');" method="post">
<input type="text" id="inp_name">
<input type="text" id="inp_address">
<input type="text" id="inp_zipcode">
<input type="text" id="inp_city">
<input type="submit" value="Submit form">
</form>
CLICK ME TO SUBMIT FORM OUTSIDE FORM ELEMENT
Javascript:
var bas_name = $("#inp_name").val();
var bas_address = $("#inp_address").val();
var bas_zipcode = $("#inp_zipcode").val();
var bas_city = $("#inp_city").val();
$("#to-top").click(function() {
if(bas_name == "" && bas_address == "" && bas_zipcode == "" && bas_city == "") {
alert("nonoonnono!");
} else {
$("form").submit();
}
});
The issue here is the variable scope. You can do this:-
$("#to-top").click(function () {
var bas_name = $("#inp_name").val();
var bas_address = $("#inp_address").val();
var bas_zipcode = $("#inp_zipcode").val();
var bas_city = $("#inp_city").val();
if (bas_name == "" && bas_address == "" && bas_zipcode == "" && bas_city == "") {
alert("nonoonnono!");
} else {
$("form").submit();
}
});
FIDDLE DEMO
This issue occurred since, you have kept all the variables outside the click event. So, it will always store the empty values on page load and thus your code doesn't works.
But, while clicking the anchor tag, you need to get the current values in the textboxes and then do all the validations.
Hope, you got my point!
You have to get the value after the click
$("#to-top").click(function() {
var bas_name = $("#inp_name").val();
var bas_address = $("#inp_address").val();
var bas_zipcode = $("#inp_zipcode").val();
var bas_city = $("#inp_city").val();
if(bas_name == "" && bas_address == "" && bas_zipcode == "" && bas_city == "") {
alert("nonoonnono!");
} else {
$("form").submit();
}
});
Try this
$(document).on("click", "#to-top", function() {
//Your code
});
Might want to look into the form funcion onsubmit, where you can call the js function what you wrote and return true or false. Here is a simple example:
http://www.w3schools.com/js/js_form_validation.asp
After that, it's easy to call the form submit from wherever you want with jQuery.
$("#myForm").submit();
or with javascript:
document.getElementById("myForm").submit();

Categories

Resources