I have tried adapting a contact formula I found online but no matter what I do it simply will not function (It does not need to be fully functional but I need it for a live-RPG session so it needs to "feel" real). I have checked (with a validation script) and JavaScript works fine on my page, so something must be wrong with the contact forms code itself. I will be the first to admit I am not that skilled at JavaScript so I was hoping someone could take a look and see if they can spot the error, because I have spent hours and still can not get this form to work at all.
The form I am basing all this on (and thus the "finished" version is this one: https://codepen.io/cool_lazyboy/pen/QRjwpG
My own code is below
function validation() {
var name = document.getElementById("name").value;
var subject = document.getElementById("subject").value;
var email = document.getElementById("email").value;
var message = document.getElementById("message");
var error_message = document.getElementById("error_message");
var text;
if (name.lenght <3){
text = "Angiv venligst dit navn";
error_message.innerHTML = text;
return false;
}
return false;
}
.wrapper-kontakt{
width: 100%;
background: #fff;
padding: 25px;
border-radius: 5px;
box-shadow: 0 1px 5px rgba(104, 104, 104, 0.8);
}
.wrapper-kontakt h2{
text-align: center;
margin-bottom: 20px;
text-transform: uppercase;
letter-spacing: 3px;
color: #332902;
}
.wrapper-kontakt .input_field{
margin-bottom: 10px;
}
.wrapper-kontakt .input_field input[type="text"],
.wrapper-kontakt textarea{
border: 1px solid #e0e0e0;
width: 100%;
padding: 10px;
}
.wrapper-kontakt textarea{
resize: none;
height: 80px;
}
.wrapper-kontakt .btn input[type="submit"]{
border: 0px;
margin-top: 15px;
padding: 10px;
text-align: center;
width: 100%;
background: #fece0c;
color: #332902;
text-transform: uppercase;
letter-spacing: 5px;
font-weight: bold;
border-radius: 25px;
cursor: pointer;
}
#error_message{
margin-bottom: 20px;
background: #fe8b8e;
padding: 0px;
text-align: center;
font-size: 14px;
transition: all 0.5s ease;
}
<div class="wrapper-kontakt">
<h2>Contact us</h2>
<div id="error_message"></div>
<form action="" id="myform" onsubmit = "return validation();">
<div class="input_field">
<input type="text" placeholder="Name" id="name">
</div>
<div class="input_field">
<input type="text" placeholder="Subject" id="subject">
</div>
<div class="input_field">
<input type="text" placeholder="Email" id="email">
</div>
<div class="input_field">
<textarea placeholder="Message" id="message"></textarea>
</div>
<div class="btn">
<input type="submit">
</div>
</form>
</div>
Here the spelling of length is wrong :
Also check action="" on form . This attribute can also be problem
function validation() {
var name = document.getElementById("name").value;
var subject = document.getElementById("subject").value;
var email = document.getElementById("email").value;
var message = document.getElementById("message");
var error_message = document.getElementById("error_message");
var text;
if (name.lenght <3){
text = "Angiv venligst dit navn";
error_message.innerHTML = text;
return false;
}
return false;
}
You have a spelling mistake in your JS in the if
name.lenght <3
Should be:
name.length < 3
Related
I have a simple problem that I cannot seem to fix. I simply want to be able to display the value of the input Name field after entering your name and clicking submit. However, undefined seems to occur.
Can someone explain why this happens and how to fix? The code is below:
var name = document.querySelector('#withJS input:first-of-type'),
date = document.querySelector('#withJS input:not(:first-of-type)'),
errorMsg = document.querySelector('#withJS .errorMsg');
errorMsg.style.display='none';
function validateForm() {
alert(name.value);
/*
if(name.length == 0){
errorMsg.style.display='block';
errorMsg.textContent='Enter Name';
}
*/
}
#noJS, #withJS {
background: lightgreen;
max-width: 300px;
padding: 10px;
border: 5px solid #ccc;
}
#withJS {
background: lightblue;
margin-top: 10px;
}
.errorMsg {
background: red;
padding: 10px;
margin-top: 10px;
color: #fff;
text-transform: uppercase;
}
<div id='withJS'>
<form>
Name:<br>
<input type="text">
<br>
Date:<br>
<input type="date">
<br><br>
<input type="submit" value="Submit" onclick='validateForm()'>
</form>
<div class='errorMsg'>error message here</div>
</div>
Thanks for any help here.
The global variable name you've declared clashes with the window attribute name. Change the name of that variable, i.e: fname.
var fname = document.querySelector('#withJS input:first-of-type'),
date = document.querySelector('#withJS input:not(:first-of-type)'),
errorMsg = document.querySelector('#withJS .errorMsg');
errorMsg.style.display='none';
function validateForm() {
alert(fname.value);
/*
if(name.length == 0){
errorMsg.style.display='block';
errorMsg.textContent='Enter Name';
}
*/
}
#noJS, #withJS {
background: lightgreen;
max-width: 300px;
padding: 10px;
border: 5px solid #ccc;
}
#withJS {
background: lightblue;
margin-top: 10px;
}
.errorMsg {
background: red;
padding: 10px;
margin-top: 10px;
color: #fff;
text-transform: uppercase;
}
<div id='withJS'>
<form>
Name:<br>
<input type="text">
<br>
Date:<br>
<input type="date">
<br><br>
<input type="submit" value="Submit" onclick='validateForm()'>
</form>
<div class='errorMsg'>error message here</div>
</div>
I am attempting to create a form that outputs the entered data when "submit" is clicked to a textarea.
Currently I can get it to submit to the area below the form but am unsure how to have multiple ID's in a single textarea.
<html>
<head>
<script>
function showInput() {
document.getElementById('display').innerHTML =
document.getElementById("user_input").value;
document.getElementById('name').innerHTML =
document.getElementById("user_name").value;
document.getElementById('stepsTaken').innerHTML =
document.getElementById("user_stepsTaken").value.replace(/(?:\r\n|\r|\n)/g, '<br />');
document.getElementById('theDate').innerHTML =
document.getElementById("user_theDate").value.replace(/(?:\r\n|\r|\n)/g, '<br />');
}
</script>
</head>
<body>
<script type="text/javaScript">
function Qreplace(e) {
var textfield = document.getElementById(e);
var regex = /#test/gi;
textfield.value = textfield.value.replace(regex, "1. test\n2. test");
var regex = /#report/gi;
textfield.value = textfield.value.replace(regex, "1. report\n2. report");
}
</script>
<form action="javascript:void(0);">
<p>
<label><b>Enter a Message</b></label><p>
<input type="text" id="user_input" required><p>
<label><b>Enter a name</b></label><p>
<input type="text" id="user_name" required><p>
<textarea id="user_stepsTaken" onkeyup="Qreplace('user_stepsTaken')" placeholder="Actions taken and notes..." style="height: 91px; max-height: 350px;" required></textarea>
<label for="sme">TL/SME Assist*</label>
<br>
Yes <input required="" type="radio" onclick="javascript:smeCheck();" value="Yes" name="TL/SME" id="yesCheck">
No <input type="radio" onclick="javascript:smeCheck();" value="No" name="TL/SME" id="noCheck"><br>
<div id="ifyes" style="display:none">
<input type="text" id="smeAssist" name="smeAssist" placeholder="Name or Initials of the TL/SME that provided assistance">
<!-- Hide/Show SME additonal options based on radio check box -->
<script type="text/javascript">
function smeCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifyes').style.display = 'block';
} else document.getElementById('ifyes').style.display = 'none';
}
</script>
</div>
<div style="display:block; margin-left: 0px;">
<label for="dateStarted">Issue Started*</label>
<input type="date" id="user_theDate" name="theDate" class="select">
</div>
<input type="submit" onclick="showInput();"><br/>
</form>
<label>Your input: </label>
<p><span id='display'></span></p>
<p><span id='name'></span></p>
<div id='stepsTaken'></div>
<div id='theDate'></div>
</body>
</html>
Thank you for any help I am quite unfamiliar with Javascript.
So the end result I am trying to accomplish is have the user input to output into a textarea with the following formatting below.
Message: Message here
Name: Name here
Info: Actions Taken
Date: 2018-12-13
you should keep return false; in function showInput() as form get submitted and there will be nothing to show
or make input type="button" instead of type="submit"
I found a solution to the issue using Jquery as follows
$('#summary').click(function() {
var name = $('#clientName').val()
var message = $('#errorMessage').val()
var ret = "Name: "+name+" \n\rMessage: " + message;
console.log(ret)
$(".output-container").fadeIn();
$("#output").text(ret);
})
$("#copyForm").click(function(){
$("#output").select();
document.execCommand('copy');
$(".success").fadeIn();
});
body {font-family: Helvetica;background-color: #1E365E;}
* {box-sizing: border-box;}
input[type=text], select, textarea {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
resize: vertical;
}
input[type=submit] {
background-color: #1E365E;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=button] {
background-color: #1E365E;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=radio] {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
resize: vertical;
}
input[type=date] {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
resize: vertical;
}
input[type=submit]:hover {
background-color: #1E365E;
}
input[type=button]:hover {
background-color: #1E365E;
}
.container {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
margin: 5%;
}
.output-container {
display: none;
margin-top: 50px;
}
#output {
height: 300px;
}
.success {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div class="container">
<h2>Testing Copy</h2>
<form id="myForm" action="/action_page.php">
<label for="cName">Client Name*</label>
<input type="text" id="clientName" name="cName" placeholder="Client Name...">
<label for="errorMessage">Error Message</label>
<input type="text" id="errorMessage" name="errorMessage" placeholder="Any error messages?">
</form>
<button id="summary">View Summary</button>
<div class="output-container">
<textarea id="output">
<h2>Form Content</h2>
</textarea>
<button id="copyForm">Copy Summary</button>
</div><!-- #end output-container -->
<p class="success"><strong>Form successfully copied</strong></p>
</div>
I currently have the code below. I added a script in the HTML to display time and date in the Interview Start time input (Interview End Time not added yet.
For some reason this does not work and only shows the time for a split second before automatically deleting it.
I tried changing the location of the script, but that didn't work. How would I make the start time stay there, and also output on submit?
const idToBold = [ 'start', 'name', 'profile', 'application', 'age', 'dob', 'origin', 'language' ];
var formInfo = {};
function showInput() {
$('input').each(function(){
var input = $(this);
//here you check every <input type="text">
if(input.attr('type') == 'text'){
var value = input.val();
//check if the id is in the constant of ids that need to add the [B] tag
if(idToBold.includes(input.attr('id'))){
value = '[b]' + value + '[/b]';
}
var label = $("label[for='"+input.attr('id')+"']").text();
formInfo[label] = value;
}
//Age Check
if(input.attr('name') == 'ageCondition' && input.is(':checked')){
var message = null;
//check the value, theres: 'pass' and 'fail'.
if(input.val() == 'Yes'){
message = '[b][Color = Blue]Match[/color][/b]';
}else{
message = '[b][Color = yellow]Age and Date of Birth do not match[/color][/b]';
};
var label = $("label[for='"+input.attr('name')+"']").text();
formInfo[label] = message;
}
//Passed Interview
if(input.attr('name') == 'passCondition' && input.is(':checked')){
var message = null;
//check the value, theres: 'pass' and 'fail'.
if(input.val() == 'pass'){
message = '[b][Color = Green]User has passed the interview [/color][/b]';
}else{
message = '[Color = Red]User hase failed the interview.[/color][/b]';
};
var label = $("label[for='"+input.attr('name')+"']").text();
formInfo[label] = message;
}
});
//you can remove this, just for output purpose
var formInfoFormated = '';
jQuery.each(formInfo, function(key, value){
formInfoFormated += key + ': ' + value + '<br>';
});
$('#display').html(formInfoFormated);
}
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
body {
font-family: 'Nunito', sans-serif;
color: #384047;
}
form {
max-width: 300px;
margin: 10px auto;
padding: 10px 20px;
background: #f4f7f8;
border-radius: 8px;
}
h1 {
margin: 0 0 30px 0;
text-align: center;
}
input[type="text"],
input[type="password"],
input[type="date"],
input[type="datetime"],
input[type="email"],
input[type="number"],
input[type="search"],
input[type="tel"],
input[type="time"],
input[type="url"],
textarea,
select {
background: rgba(255,255,255,0.1);
border: none;
font-size: 16px;
height: auto;
margin: 0;
outline: 0;
padding: 15px;
width: 100%;
background-color: #e8eeef;
color: #8a97a0;
box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset;
margin-bottom: 30px;
}
input[type="radio"],
input[type="checkbox"] {
margin: 0 4px 8px 0;
}
select {
padding: 6px;
height: 32px;
border-radius: 2px;
}
.input_submit {
padding: 19px 39px 18px 39px;
color: #FFF;
background-color: #4bc970;
font-size: 18px;
text-align: center;
font-style: normal;
border-radius: 5px;
width: 100%;
border: 1px solid #3ac162;
border-width: 1px 1px 3px;
box-shadow: 0 -1px 0 rgba(255,255,255,0.1) inset;
margin-bottom: 10px;
}
fieldset {
margin-bottom: 30px;
border: none;
}
legend {
font-size: 1.4em;
margin-bottom: 10px;
}
label {
display: block;
margin-bottom: 8px;
}
label.light {
font-weight: 300;
display: inline;
}
.number {
background-color: #5fcf80;
color: #fff;
height: 30px;
width: 30px;
display: inline-block;
font-size: 0.8em;
margin-right: 4px;
line-height: 30px;
text-align: center;
text-shadow: 0 1px 0 rgba(255,255,255,0.2);
border-radius: 100%;
}
#media screen and (min-width: 480px) {
form {
max-width: 480px;
}
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src ="javascript/supportJS.js"></script>
<title>Arma Life - Interview Logger</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script>
var time = new Date();
function show(id) {
if (id == 1) {
document.getElementById('start').value=time;
}
if(id == 2) {
document.getElementById('end').value=time;
}
}
</script>
</head>
<body>
<form>
<label for="start"><b>Interview Start Time</b></label>
<input type="text" name="message" id="start">
<button id='1' onClick="show(this.id)">Click Amber</button>
<label for="name"><b>Roleplay Name</b></label>
<input type="text" name="message" id="name">
<label for="profile"><b>Profile Link</b></label>
<input type="text" name="message" id="profile">
<label for="application"><b>Application Link</b></label>
<input type="text" name="message" id="application">
<br><br>
<label for="age"><b>Age</b></label>
<input type="text" name="message" id="age">
<label for="dob"><b>Date of Birth</b></label>
<input type="text" name="message" id="dob">
<label for="ageCondition"><b>Date of Birth and Age match?</b></label><br>
<input type="radio" name="ageCondition" value="Yes">Yes<br>
<input type="radio" name="ageCondition" value="No">No<br>
<br><br>
<label for="origin"><b>Country of Origin</b></label>
<input type="text" name="message" id="origin">
<label for="language"><b>Primary Language</b></label>
<input type="text" name="message" id="language">
<br><br>
<label for="passCondition"><b>Passed?</b></label><br>
<input type="radio" name="passCondition" value="pass">Pass<br>
<input type="radio" name="passCondition" value="fail">Fail<br>
<br><br>
</form>
<input class="input_submit" type="submit" onclick="showInput();">
<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>
In HTML button elements are by default of type submit.
If you click on this button, you immediately submit the form:
<button id='1' onClick="show(this.id)">Click Amber</button>
To make this button only performs the action defined on click, without submitting the form, just give it a type of button.
<button id='1' type="button" onClick="show(this.id)">Click Amber</button>
const idToBold = [ 'start', 'name', 'profile', 'application', 'age', 'dob', 'origin', 'language' ];
var formInfo = {};
function showInput() {
$('input').each(function(){
var input = $(this);
//here you check every <input type="text">
if(input.attr('type') == 'text'){
var value = input.val();
//check if the id is in the constant of ids that need to add the [B] tag
if(idToBold.includes(input.attr('id'))){
value = '[b]' + value + '[/b]';
}
var label = $("label[for='"+input.attr('id')+"']").text();
formInfo[label] = value;
}
//Age Check
if(input.attr('name') == 'ageCondition' && input.is(':checked')){
var message = null;
//check the value, theres: 'pass' and 'fail'.
if(input.val() == 'Yes'){
message = '[b][Color = Blue]Match[/color][/b]';
}else{
message = '[b][Color = yellow]Age and Date of Birth do not match[/color][/b]';
};
var label = $("label[for='"+input.attr('name')+"']").text();
formInfo[label] = message;
}
//Passed Interview
if(input.attr('name') == 'passCondition' && input.is(':checked')){
var message = null;
//check the value, theres: 'pass' and 'fail'.
if(input.val() == 'pass'){
message = '[b][Color = Green]User has passed the interview [/color][/b]';
}else{
message = '[Color = Red]User hase failed the interview.[/color][/b]';
};
var label = $("label[for='"+input.attr('name')+"']").text();
formInfo[label] = message;
}
});
//you can remove this, just for output purpose
var formInfoFormated = '';
jQuery.each(formInfo, function(key, value){
formInfoFormated += key + ': ' + value + '<br>';
});
$('#display').html(formInfoFormated);
}
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
body {
font-family: 'Nunito', sans-serif;
color: #384047;
}
form {
max-width: 300px;
margin: 10px auto;
padding: 10px 20px;
background: #f4f7f8;
border-radius: 8px;
}
h1 {
margin: 0 0 30px 0;
text-align: center;
}
input[type="text"],
input[type="password"],
input[type="date"],
input[type="datetime"],
input[type="email"],
input[type="number"],
input[type="search"],
input[type="tel"],
input[type="time"],
input[type="url"],
textarea,
select {
background: rgba(255,255,255,0.1);
border: none;
font-size: 16px;
height: auto;
margin: 0;
outline: 0;
padding: 15px;
width: 100%;
background-color: #e8eeef;
color: #8a97a0;
box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset;
margin-bottom: 30px;
}
input[type="radio"],
input[type="checkbox"] {
margin: 0 4px 8px 0;
}
select {
padding: 6px;
height: 32px;
border-radius: 2px;
}
.input_submit {
padding: 19px 39px 18px 39px;
color: #FFF;
background-color: #4bc970;
font-size: 18px;
text-align: center;
font-style: normal;
border-radius: 5px;
width: 100%;
border: 1px solid #3ac162;
border-width: 1px 1px 3px;
box-shadow: 0 -1px 0 rgba(255,255,255,0.1) inset;
margin-bottom: 10px;
}
fieldset {
margin-bottom: 30px;
border: none;
}
legend {
font-size: 1.4em;
margin-bottom: 10px;
}
label {
display: block;
margin-bottom: 8px;
}
label.light {
font-weight: 300;
display: inline;
}
.number {
background-color: #5fcf80;
color: #fff;
height: 30px;
width: 30px;
display: inline-block;
font-size: 0.8em;
margin-right: 4px;
line-height: 30px;
text-align: center;
text-shadow: 0 1px 0 rgba(255,255,255,0.2);
border-radius: 100%;
}
#media screen and (min-width: 480px) {
form {
max-width: 480px;
}
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src ="javascript/supportJS.js"></script>
<title>Arma Life - Interview Logger</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script>
var time = new Date();
function show(id) {
if (id == 1) {
document.getElementById('start').value=time;
}
if(id == 2) {
document.getElementById('end').value=time;
}
}
</script>
</head>
<body>
<form>
<label for="start"><b>Interview Start Time</b></label>
<input type="text" name="message" id="start">
<button id='1' type="button" onClick="show(this.id)">Click Amber</button>
<label for="name"><b>Roleplay Name</b></label>
<input type="text" name="message" id="name">
<label for="profile"><b>Profile Link</b></label>
<input type="text" name="message" id="profile">
<label for="application"><b>Application Link</b></label>
<input type="text" name="message" id="application">
<br><br>
<label for="age"><b>Age</b></label>
<input type="text" name="message" id="age">
<label for="dob"><b>Date of Birth</b></label>
<input type="text" name="message" id="dob">
<label for="ageCondition"><b>Date of Birth and Age match?</b></label><br>
<input type="radio" name="ageCondition" value="Yes">Yes<br>
<input type="radio" name="ageCondition" value="No">No<br>
<br><br>
<label for="origin"><b>Country of Origin</b></label>
<input type="text" name="message" id="origin">
<label for="language"><b>Primary Language</b></label>
<input type="text" name="message" id="language">
<br><br>
<label for="passCondition"><b>Passed?</b></label><br>
<input type="radio" name="passCondition" value="pass">Pass<br>
<input type="radio" name="passCondition" value="fail">Fail<br>
<br><br>
</form>
<input class="input_submit" type="submit" onclick="showInput();">
<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>
Ok so to keep your content from disappearing remove the form tags. From what I see your have to form element present but you're not using it for their intended purpose. The form tag is trying to do a POST (which is why everything looks like it disappearing) when you click your "Click Amber" button. The form thinks that your button is there to do a "Submit".
Here is more information about html form elements:
https://www.w3schools.com/html/html_forms.asp
You can add type="button" to the "Click Amber" button to prevent your form from submitting on that press. As been said, your form is submitting which is clearing out your page.
Your output code already works correctly.
<button id='1' type="button" onClick="show(this.id)">Click Amber</button>
I have made a contact form. In this form I have added input validations like email for email text box and maximum length for phone number 10 in the contact textbox. But these validations are not working in my case.
What I'm doing wrong?
AJAX Call
function myformsubmit() {
var name = document.getElementById("name").value;
var mail = document.getElementById("mail").value;
var contact = document.getElementById("contact").value;
var reason = document.getElementById("reason").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1=' + name + '&mail1=' + mail + '&contact1=' + contact+ '&reason1=' + reason;
if (name == ''||mail == ''|| reason == ''||contact == ''){
alert("Please Fill all fields");
}else{
// AJAX code to submit form.
$.ajax({
type : "POST",
url : "http://test1.com/wp-content/themes/suave/theme_option/1.php",
data : dataString,
cache : false,
success : function(html) {
alert(html);
window.location="http://test1.com";
}
});
}
return false;
}
#media screen and (max-width: 972px) and (min-width: 100x) {
.exitpopup-modal-window {
display: none;
}
}
#exitpopup-modal .modal-body {
padding: 0px;
}
.modal-body {
padding: 0px;
}
.second img {
width: 369px;
height: 404.6px;
margin-top: -1%;
}
.first form {
display: table;
margin-left: 34px;
margin-top: 43px;
}
.row1 {
font-size: 10px;
font-family: inherit;
display: table-row;
border: 2px solid red;
}
.row1 #name,
#mail,
#contact {
color: black;
width: 260px;
height: 34px;
padding: 6px 12px;
border-radius: 3.9px;
border-color: #777;
display: table-cell;
}
.row1 textarea {
width: 260px;
height: 110px;
color: black;
border-color: #777;
display: table-cell;
}
.row1 #submit {
width: 152px;
height: 44px;
margin-left: 15%;
background-color: #337ab7;
color: white;
border-color: none;
}
.row1 #submit:hover {
width: 152px;
height: 44px;
margin-left: 15%;
background-color: white;
color: #337ab7;
border-color: none;
}
.second,
.first {
float: left;
}
.clearfix {
clear: both
}
.first span {
margin-left: 25%;
font-family: inherit;
font-size: 15px;
padding-top: 3px;
}
<div class="exitpopup-modal-window">
<div class="second">
<img src="http://www.buildzar.com/listing-assets/images/home-new/get-quote/bg-lead-form-web.png">
</div>
<div class="first">
<span>We are there to help you</span>
<form id="form" name="theform">
<div class="row1">
<input id="name" type="text" placeholder="Your name *" required>
<br>
<br>
</div>
<div class="row1">
<input type="email" id="mail" placeholder="Your email *" required>
<br>
<br>
</div>
<div class="row1">
<input id="contact" type="number" maxlength="10" placeholder="Your phonenumber*" required>
<br>
<br>
</div>
<div class="row1">
<textarea id="reason" rows="5" placeholder="Any reason to leave ?*" required></textarea>
<br>
<br>
</div>
<div class="row1">
<input id="submit" onclick="myformsubmit()" type="button" value="Submit">
</div>
</form>
</div>
<div class="clearfix"></div>
Your button type should be submit.
<input id="submit" type="submit" value="Submit">
And within for tag you should have action
<form id="form" name="theform" action="javascript:myformsubmit()">
Make New function and call this from your function myformsubmit.
function checkvalidate() {
var flag = false;
if (name == ''||mail == ''|| reason == ''||contact == ''){
flag = false;
}
else
{
flag = true;
}
return flag;
function myformsubmit() {
var flag = checkvalidate();
if(flag == true)
{
success code.
}
else
{
error message
}
}
I have this input field
<input name="question"/> I want to call IsEmpty function when submit clicking submit button.
I tried the code below but did not work.
any advice?
function IsEmpty() {
if (document.form.question.value == "") {
alert("empty");
}
return;
}
Question: <input name="question" /> <br/>
<input id="insert" onclick="IsEmpty();" type="submit" value="Add Question" />
<script type="text/javascript">
function validateForm() {
var a = document.forms["Form"]["answer_a"].value;
var b = document.forms["Form"]["answer_b"].value;
var c = document.forms["Form"]["answer_c"].value;
var d = document.forms["Form"]["answer_d"].value;
if ((a == null || a == "") && (b == null || b == "") && (c == null || c == "") && (d == null || d == "")) {
alert("Please Fill In All Required Fields");
return false;
}
}
</script>
<form method="post" name="Form" onsubmit="return validateForm()" action="">
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>
An input field can have whitespaces, we want to prevent that.
Use String.prototype.trim():
function isEmpty(str) {
return !str.trim().length;
}
Example:
const isEmpty = str => !str.trim().length;
document.getElementById("name").addEventListener("input", function() {
if( isEmpty(this.value) ) {
console.log( "NAME is invalid (Empty)" )
} else {
console.log( `NAME value is: ${this.value}` );
}
});
<input id="name" type="text">
See the working example here
You are missing the required <form> element. Here is how your code should be like:
function IsEmpty() {
if (document.forms['frm'].question.value === "") {
alert("empty");
return false;
}
return true;
}
<form name="frm">
Question: <input name="question" /> <br />
<input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question" />
</form>
I would like to add required attribute in case user disabled javascript:
<input type="text" id="textbox" required/>
It works on all modern browsers.
if(document.getElementById("question").value.length == 0)
{
alert("empty")
}
Add an id "question" to your input element and then try this:
if( document.getElementById('question').value === '' ){
alert('empty');
}
The reason your current code doesn't work is because you don't have a FORM tag in there. Also, lookup using "name" is not recommended as its deprecated.
See #Paul Dixon's answer in this post : Is the 'name' attribute considered outdated for <a> anchor tags?
You can loop through each input after submiting and check if it's empty
let form = document.getElementById('yourform');
form.addEventListener("submit", function(e){ // event into anonymous function
let ver = true;
e.preventDefault(); //Prevent submit event from refreshing the page
e.target.forEach(input => { // input is just a variable name, e.target is the form element
if(input.length < 1){ // here you're looping through each input of the form and checking its length
ver = false;
}
});
if(!ver){
return false;
}else{
//continue what you were doing :)
}
})
<script type="text/javascript">
function validateForm() {
var a = document.forms["Form"]["answer_a"].value;
var b = document.forms["Form"]["answer_b"].value;
var c = document.forms["Form"]["answer_c"].value;
var d = document.forms["Form"]["answer_d"].value;
if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {
alert("Please Fill All Required Field");
return false;
}
}
</script>
<form method="post" name="Form" onsubmit="return validateForm()" action="">
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>
if(document.getElementById("question").value == "")
{
alert("empty")
}
Just add an ID tag to the input element... ie:
and check the value of the element in you javascript:
document.getElementById("question").value
Oh ya, get get firefox/firebug. It's the only way to do javascript.
Customizing the input message using HTML validation when clicking on Javascript button
function msgAlert() {
const nameUser = document.querySelector('#nameUser');
const passUser = document.querySelector('#passUser');
if (nameUser.value === ''){
console.log('Input name empty!');
nameUser.setCustomValidity('Insert a name!');
} else {
nameUser.setCustomValidity('');
console.log('Input name ' + nameUser.value);
}
}
const v = document.querySelector('.btn-petroleo');
v.addEventListener('click', msgAlert, false);
.container{display:flex;max-width:960px;}
.w-auto {
width: auto!important;
}
.p-3 {
padding: 1rem!important;
}
.align-items-center {
-ms-flex-align: center!important;
align-items: center!important;
}
.form-row {
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
margin-right: -5px;
margin-left: -5px;
}
.mb-2, .my-2 {
margin-bottom: .5rem!important;
}
.d-flex {
display: -ms-flexbox!important;
display: flex!important;
}
.d-inline-block {
display: inline-block!important;
}
.col {
-ms-flex-preferred-size: 0;
flex-basis: 0;
-ms-flex-positive: 1;
flex-grow: 1;
max-width: 100%;
}
.mr-sm-2, .mx-sm-2 {
margin-right: .5rem!important;
}
label {
font-family: "Oswald", sans-serif;
font-size: 12px;
color: #007081;
font-weight: 400;
letter-spacing: 1px;
text-transform: uppercase;
}
label {
display: inline-block;
margin-bottom: .5rem;
}
.x-input {
background-color: #eaf3f8;
font-family: "Montserrat", sans-serif;
font-size: 14px;
}
.login-input {
border: none !important;
width: 100%;
}
.p-4 {
padding: 1.5rem!important;
}
.form-control {
display: block;
width: 100%;
height: calc(1.5em + .75rem + 2px);
padding: .375rem .75rem;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #495057;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ced4da;
border-radius: .25rem;
transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
button, input {
overflow: visible;
margin: 0;
}
.form-row {
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
margin-right: -5px;
margin-left: -5px;
}
.form-row>.col, .form-row>[class*=col-] {
padding-right: 5px;
padding-left: 5px;
}
.col-lg-12 {
-ms-flex: 0 0 100%;
flex: 0 0 100%;
max-width: 100%;
}
.mt-1, .my-1 {
margin-top: .25rem!important;
}
.mt-2, .my-2 {
margin-top: .5rem!important;
}
.mb-2, .my-2 {
margin-bottom: .5rem!important;
}
.btn:not(:disabled):not(.disabled) {
cursor: pointer;
}
.btn-petroleo {
background-color: #007081;
color: white;
font-family: "Oswald", sans-serif;
font-size: 12px;
text-transform: uppercase;
padding: 8px 30px;
letter-spacing: 2px;
}
.btn-xg {
padding: 20px 100px;
width: 100%;
display: block;
}
.btn {
display: inline-block;
font-weight: 400;
color: #212529;
text-align: center;
vertical-align: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-color: transparent;
border: 1px solid transparent;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
border-radius: .25rem;
transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
input {
-webkit-writing-mode: horizontal-tb !important;
text-rendering: auto;
color: -internal-light-dark(black, white);
letter-spacing: normal;
word-spacing: normal;
text-transform: none;
text-indent: 0px;
text-shadow: none;
display: inline-block;
text-align: start;
appearance: textfield;
background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59));
-webkit-rtl-ordering: logical;
cursor: text;
margin: 0em;
font: 400 13.3333px Arial;
padding: 1px 2px;
border-width: 2px;
border-style: inset;
border-color: -internal-light-dark(rgb(118, 118, 118), rgb(195, 195, 195));
border-image: initial;
}
<div class="container">
<form name="myFormLogin" class="w-auto p-3 mw-10">
<div class="form-row align-items-center">
<div class="col w-auto p-3 h-auto d-inline-block my-2">
<label class="mr-sm-2" for="nameUser">Usuário</label><br>
<input type="text" class="form-control mr-sm-2 x-input login-input p-4" id="nameUser"
name="nameUser" placeholder="Name" required>
</div>
</div>
<div class="form-row align-items-center">
<div class="col w-auto p-3 h-auto d-inline-block my-2">
<label class="mr-sm-2" for="passUser">Senha</label><br>
<input type="password" class="form-control mb-3 mr-sm-2 x-input login-input p-4" id="passUser"
name="passUser" placeholder="Password" required>
<div class="help">Esqueci meu usuário ou senha</div>
</div>
</div>
<div class="form-row d-flex align-items-center">
<div class="col-lg-12 my-1 mt-2 mb-2">
<button type="submit" value="Submit" class="btn btn-petroleo btn-lg btn-xg btn-block p-4">Entrar</button>
</div>
</div>
<div class="form-row align-items-center d-flex">
<div class="col-lg-12 my-1">
<div class="nova-conta">Ainda não é cadastrado? Crie seu acesso</div>
</div>
</div>
</form>
</div>
My solution below is in es6 because I made use of const if you prefer es5 you can replace all const with var.
const str = " Hello World! ";
// const str = " ";
checkForWhiteSpaces(str);
function checkForWhiteSpaces(args) {
const trimmedString = args.trim().length;
console.log(checkStringLength(trimmedString))
return checkStringLength(trimmedString)
}
// If the browser doesn't support the trim function
// you can make use of the regular expression below
checkForWhiteSpaces2(str);
function checkForWhiteSpaces2(args) {
const trimmedString = args.replace(/^\s+|\s+$/gm, '').length;
console.log(checkStringLength(trimmedString))
return checkStringLength(trimmedString)
}
function checkStringLength(args) {
return args > 0 ? "not empty" : "empty string";
}
<pre>
<form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form>
</pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name", "req", "Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js file
Combining all the approaches we can do something like this:
const checkEmpty = document.querySelector('#checkIt');
checkEmpty.addEventListener('input', function () {
if (checkEmpty.value && // if exist AND
checkEmpty.value.length > 0 && // if value have one charecter at least
checkEmpty.value.trim().length > 0 // if value is not just spaces
)
{ console.log('value is: '+checkEmpty.value);}
else {console.log('No value');
}
});
<input type="text" id="checkIt" required />
Note that if you truly want to check values you should do that on the server, but this is out of the scope for this question.
The following code worked for me perfectly:
<form action = "dashboard.php" onsubmit= "return someJsFunction()">
<button type="submit" class="button" id = "submit" name="submit" >Upload to live listing</button>
</form>
<script type="text/javascript">
function someJsFunction(){
const input = document.getElementById('input1');
if(input.value === ""){
alert ("no input?"); // This will prevent the Form from submitting
return false;
}else{
return true; // this will submit the form and handle the control to php.
}
}
</script>