How do I use two document.InnerHtml in javascript? - 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;
}

Related

How to add more than 2 conditions in an If/Else statement in Javascript?

Me again.
So I have been working on this basic search functionality where I am comparing the value entered as text with a list of other values and doing an action based on it.
In simpler words. I am making a search where the logic compares the value with other strings and if the comparison is successful then show and hide and vice versa if the condition is false.
Now the other condition i want to implement is that when the text bar(where the user will enter the value) is empty then both the divs should be shown. Below is my code for this:
HTML where I am getting the value from: - Im using the onchange to get the value - oninput is not working :(
<label>Find your location:</label>
<input type="text" class="form-control" id="search_input" placeholder="Type address..."
onChange="myFunction()"/>
And This is my JS code
<script>
function myFunction() {
var inzone = document.getElementById("inzone");
var outzone = document.getElementById("outzone");
if(document.getElementById("search_input").value == null
||document.getElementById("search_input").value == "")
{
outzone.style.display = "";
inzone.style.display = "";
}
else if (document.getElementById("search_input").value === 'something something')
{
outzone.style.display = "none";
inzone.style.display = "";
}
else {
inzone.style.display = "none";
outzone.style.display = "";
}
document.getElementById("search_input").value == null will never be true. The value property of an HTMLInputElement is always a string. It may be "", but not null or undefined (the two things == null checks).

SweetAlert pop-up message with JavaScript when the fields are filled

I wanted to make Sweetalert to work only if all the fields are filled. I tried more versions of code, I found answers here on the forum but nothing helped. Now if I do not fill all of the fields and I click on the submit I get notification message because of HTML, but the pop-up appears too.
As you can see here, altough I got the pop-up, I did not fill the last input field.
function Sweetalert1(){
var name = document.getElementById("name");
var message = document.getElementById("message");
var email = document.getElementById("email");
if ((name != "" && message != "" && email != "") {
Swal.fire(
'Köszönjük!',
'Megkaptuk a leveledet és hamarosan válaszolunk!',
'success'
}
}
You need to get the value of your form inputs. Currently, your name, message and email are all Elements and thus none of them equal "". So your if statement really looks like:
if (true && true && true) {
// code..
}
Instead, you can get the values from your input elements:
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var email = document.getElementById("email").value;
This way you are getting the text inputted into the input fields, not the elements themselves.

Why can't I seem to get this function to implement properly?

I've got some code in an external .js file that goes like this:
function creditConfirm (){
textboxVType = document.getElementById('textboxType');
textboxVName= document.getElementById('textboxName');
textboxVNumber = document.getElementById('textboxNumber');
textboxVCode = document.getElementById('textboxCode');
textboxVAmount = document.getElementById('textboxAmount');
if (textboxVType && textboxVName && textboxVNumber && textboxVCode && textboxVAmount =! " "){
alert("Accepted");
//All items made null
}
else{
alert("Try again");
}
}
Then I also have some HTML code that goes like this:
<p1> Credit card type: </p1>
<input type = "text" id "textboxType">
<h1> </h1>
<p1> Name: </p1>
<input type = "text" id "textboxName">
<h1> </h1>
<p1> Number: </p1>
<input type = "text" id "textboxNumber">
<h1> </h1>
<p1> Security code: </p1>
<input type = "text" id "textboxCode">
<h1> </h1>
<p1> Donation amount: </p1>
<input type = "text" id "textboxAmount">
<button onclick="creditConfirm()">Confirm</button>
What I'm trying to do is if all the items are filled out to print the first text and if one is missing to print the second text and allow them to try again. However, when I go onto the website either fill out all the boxes or leave one unfilled and click the confirm button nothing happens. I'm at a very basic level of JavaScript and our teacher seemingly refuses to teach us so I may have just missed a really obvious mistake, can anyone spot anything that would lead to this not working
You are not checking the elements for values in your if statement properly.
In an if statement that has && (or ||) conditions, each condition must be complete and stand on its own.
Additionally, to check a form field for data, you must check its value property.
You also had =! instead of !=.
if(textboxVType.value !="" &&
textboxVName.value != "" &&
textboxVNumber.value !="" &&
textboxVCode.value !="" &&
textboxVAmount.value != "") {}
you're checking if the dom elements are truthy (that will always be true as long as you declare them in your html) rather then check if they have a value set
change your if to
if (textboxVType.value && textboxVName.value && textboxVNumber.value
&& textboxVCode.value && textboxVAmount.value){
alert("Accepted");
}
1) Operator =! doesn't exist. != does.
2) textboxVType textboxVName textboxVNumber textboxVCode textboxVAmount =! " " are 4 distinct conditions. You can't factorise condition such way. Instead, you have to write that way textboxVType.value != " " && textboxVName.value != " " && textboxVNumber.value != " " && textboxVCode.value != " " && textboxVAmount.value != " " The .value is used to access the value of the DOM elements you got.
3) If you want to check if a textbox is empty rather use != "" instead of != " " (that will only check if the textbox contains only a space)
While I appreciate you're just starting with JS, and this might be slightly above your comfort zone, you might be interested in a shortcut to writing down and checking all the values of the input ids separately:
Here we pick up all the inputs using querySelectorAll, and then check the value of each one with some. If any of them are empty then Accepted is alerted, otherwise Try Again.
function creditConfirm() {
const inputs = document.querySelectorAll('input');
const emptyField = [...inputs].some(input => input.value === '');
if (!emptyField) {
alert("Accepted");
} else {
alert("Try again");
}
}
Short demo on JSFiddle.

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 to change textContent via 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;
}}

Categories

Resources