Display date and time in input - javascript

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>

Related

I Use Two Forms with one Submit Button but not working

I am Using Two Forms with one Submit Button But Not Working.
1st Form of __ Name , Email , Address __ is For Blogger Platform Which Works Fine Only when Published without Radio Buttons coding putting inside the Code.
2ns Form is Multiple Radio Options which works fine only when it is separated
from the other form.
Again I Want to remind you:
These Forms are for Blogger Website Platform which coded Well With fine working only in Separated form but when I combined the two forms with one 'Submit Now' button it Stop Working
Please Solve this Coding without affecting or removing any id="" attribute.
If I remove this code id="ContactForm1_contact-form-submit" then the 1st Form Stops Working in Blogger Theme.
Is it possible to make One button working for two Forms?
document.addEventListener('click', function(event)
{
let submitBtn = document.getElementById("submitBtn");
if (event.target.type === "radio" && event.target.name === "number")
{
submitBtn.removeAttribute("disabled");
}
});
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
if(!radioObj)
return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) {
radioObj[i].checked = true;
}
}
}
.widget.ContactForm {
z-index: 1
}
.contact-form-widget {
margin-left: auto;
margin-right: auto;
width:100%;
max-width:98%;
padding: 25px 0;
border:1px solid #b2b2b2;
-webkit-border-radius: 2%;
-moz-border-radius: 2%;
border-radius:3px;
}
.contact-form-widget .form {
width: 91%;
margin: 0 auto
}
.ribbon {
font: 20px Arial;
text-transform: capitalize;
position:center;
background: #6B5F53;
color: #fff;
text-align: center;
padding:7px 0 7px 0;
margin:0 0 3px 0;
border-radius:5px;
}
.contactf-name,
.contactf-email,
.contactf-message {
text-align: left;
margin-top: 25px;
color: #000;
font-size: 13px;
font-weight:600
}
.contactf-name,
.contactf-email {
float: left;
width: 100%
}
.contact-form-name,
.contact-form-email,
.contact-form-email-message,
.contact-form-name:hover,
.contact-form-name:focus,
.contact-form-email:hover,
.contact-form-email:focus,
.contact-form-email-message:hover,
.contact-form-email-message:focus {
width: 100%;
max-width: 100%;
margin: 10px 0 0;
padding: 10px;
font-size: 12px;
color: #aaa;
border-color: #cccccc;
border-top:1px solid #666666;
border-left:1px solid #666666;
border-width: 1px;
box-shadow: none;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px
}
.contact-form-name,
.contact-form-email {
height: 35px
}
.contact-form-email-message {
height: 100px
}
.contact-form-button-submit,
.contact-form-button-submit:hover {
margin-top: 25px;
padding:0 35px 0 35px;
height: 37px;
font: bold 18px Arial;
outline: none;
letter-spacing: 1px;
color: #fff;
text-align: center;
cursor: pointer;
color: #333333;
background: #d2d2d2;
}
.contact-form-button-submit:active {
color: #333333;
border: 1px solid #d6a437;
background: #febd4b;
background: -webkit-gradient(linear, 0 0, 0 100%, from(#febd4b) to(#fed970));
background: -webkit-linear-gradient(#febd4b, #fed970);
background: -moz-linear-gradient(#febd4b, #fed970);
background: -ms-linear-gradient(#febd4b, #fed970);
background: -o-linear-gradient(#febd4b, #fed970);
background: linear-gradient(#febd4b, #fed970);
-pie-background: linear-gradient(#febd4b, #fed970)
}
.contact-form-cross {
border: medium none !important;
box-shadow: none !important;
padding: 0 !important;
height: 11px !important;
width: 11px !important;
}
input[type=radio] {
-webkit-appearance: radio;
-O-appearance: radio;
-moz-appearance: radio;
opacity:1;
}
#header .bottom-header.blog h1 {
font-size: 64px;
color: red
}
input[type=radio]:hover + label {
border: solid 1px white; padding: 5px; border-radius: 1px;
border-color : red;
color : red;
opacity:1;
}
input[type=radio]:checked + label {
border: solid 2px white; padding: 5px; border-radius: 1px;
border-color : red;
color : red;
opacity:1;
}
input[type=text] {
font-weight:bold;
}
input[type=text]:hover {
}
input[type=email]:hover {
}
<div class="widget ContactForm" id="ContactForm22">
<div class="ribbon"><strong>Your Billing Details</strong></div>
<div class="contact-form-widget">
<div class="form">
<form name="contact-form">
<div class="contactf-name">Your name <span style="color:red">*</span> :<input class="contact-form-name" id="ContactForm1_contact-form-name" name="Full Name" size="30" type="text" value="Full Name" onblur='if (this.value == "") {this.value = "Full Name";}' onfocus='if (this.value == "Full Name") {this.value = "";}' /></div>
<div class="contactf-email">E-mail address <span style="color:red">*</span> :<input class="contact-form-email" id="ContactForm1_contact-form-email" name="E-mail address" size="30" type="text" value="E-mail address" onblur='if (this.value == "") {this.value = "E-mail address";}' onfocus='if (this.value == "E-mail address") {this.value = "";}' /></div>
<div style="clear:both"></div>
<div class="contactf-message">Your Address <span style="color:red">*</span> :<textarea class="contact-form-email-message" cols="25" id="ContactForm1_contact-form-email-message" name="Hometown/ City/ Your State...." rows="5" value="" placeholder="Hometown/ City/ Your State...." value="Hometown/ City/ Your State...." onblur='if (this.value == "") {this.value = "Hometown/ City/ Your State....";}' onfocus='if (this.value == "Hometown/ City/ Your State....") {this.value = "";}'></textarea>
<form name="radioExampleForm" method="get" action="" onsubmit="return false;">
<p> <label for="number0"><input type="radio" value="http://www.paypal.com" name="number" id="number0"> Pay by Paypal</label></br>
<label for="number1"><input type="radio" value="http://www.instamojo.com" name="number" id="number1"> Pay by InstaMojo</label></br>
<label for="number2"><input type="radio" value="http://www.skrill.com" name="number" id="number2"> Pay by Skrill</label></br>
</p>
</form>
<input type="button" class="contact-form-button contact-form-button-submit" id="ContactForm1_contact-form-submit" id="submitBtn" disabled onclick="window.open(getCheckedValue(document.forms['radioExampleForm'].elements['number']), '_blank');" value="Submit Now">
</div>
</form>
</div>
</div>
</div>

Why is the input value undefined after validation?

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>

Form submit to Textarea on submit

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 want to display error message in my multiple step form in jquery

I want to display an error message in my multiple step form in jquery if
I click on next button with out filling any value it should gives error message as soon as enter value error message disappear.if i click on next bttton with out filling any value it should gives error message as soon as enter value error message disappear
function isEmail(str) { // simple email validation
return /(.+)#(.+){2,}\.(.+){2,}/.test($.trim(str));
}
function isEmpty(str) { // test for empty string
return $.trim(str) === "";
}
function validate($div) { // validates any div - will not let you leave the div if error
var $fields = $div.find("input"), hasError = false;
$fields.each(function() {
$(this).removeClass("error")
hasError = this.name=="pword" && isEmpty(this.value);
if (hasError) {
$("#pword").addClass("error").focus();
return false;
}
hasError = this.name=="email" && (isEmpty(this.value) || !isEmail(this.value));
if (hasError) {
$("#email").addClass("error").focus();
return false;
}
hasError = isEmpty(this.value); // the rest of the fields
if (hasError) {
$(this).addClass("error").focus();
return false;
}
})
return hasError?false:true;
}
$(function() {
// validate all divs on submit, but actually only necessary to validate thediv the submit is on
$("#myForm").on("submit",function(e) {
$(".page").each(function() {
if (!validate($(this))) {
e.preventDefault(); // stop submission
return false;
}
});
});
$(".nav").on("click", function() {
var $parent = $(this).closest("div");
var $nextDiv = $(this).hasClass("next") ? $parent.next() : $parent.prev();
if (validate($parent)) { // is the div this button is on valid?
$parent.fadeOut(function() { // fade it out and fade the next one in
if ($nextDiv.length) {
$nextDiv.fadeIn()
for (var i=$(".page").length;i> $nextDiv.index(); i--) {
$("#bar" + i).css({"background-color": "#D8D8D8"}); // we are going backwards
}
$("#bar" + $nextDiv.index()).css({"background-color": "#38610B"});
}
});
}
});
});
body {
margin: 0 auto;
padding: 0;
text-align: center;
background-color: #D8D8D8;
}
#wrapper {
width: 995px;
padding: 0px;
margin: 0px auto;
font-family: helvetica;
position: relative;
}
#wrapper .baricon {
display: inline-block;
border-radius: 100%;
padding: 12px;
background-color: #38610B;
color: white;
}
#wrapper .progress_bar {
width: 200px;
height: 5px;
border-radius: 20px;
background-color: #D8D8D8;
display: inline-block;
}
#wrapper form div {
margin-left: 340px;
padding: 10px;
box-sizing: border-box;
width: 300px;
margin-top: 50px;
background-color: #585858;
}
#wrapper form div p {
color: #F2F2F2;
margin: 0px;
margin-top: 10px;
font-weight: bold;
}
#wrapper form div .form_head {
font-size: 22px;
font-weight: bold;
margin-bottom: 30px;
}
#wrapper form div input[type="text"] {
width: 200px;
height: 40px;
padding: 5px;
border-radius: 5px;
border: none;
margin-top: 10px;
}
#wrapper form div input[type="button"],
input[type="submit"] {
width: 80px;
height: 40px;
border-radius: 5px;
border: 2px solid white;
background: none;
color: white;
margin: 5px;
margin-top: 10px;
}
#user_details,
#qualification {
display: none;
}
.error { background-color:pink !important}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="wrapper">
<br>
<span class='baricon'>1</span>
<span id="bar1" class='progress_bar'> </span>
<span class='baricon'>2</span>
<span id="bar2" class='progress_bar'> </span>
<span class='baricon'>3</span>
<form method="post" action="" id="myForm">
<div id="account_details" class="page">
<p class='form_head'>Account Details</p>
<p>Email Address</p>
<input type="text" name="email" id="email" placeholder='Email Address'>
<p>Password</p>
<input type="text" name="pword" id="pword" placeholder='Password'>
<br>
<input type="button" value="Next" class="nav next" />
</div>
<div id="user_details" class="page">
<p class='form_head'>User Details</p>
<p>First Name</p>
<input type="text" name="fname" id="fname" placeholder='First Name'>
<p>Last Name</p>
<input type="text" name="lname" is="lname" placeholder='Last Name'>
<p>Gender</p>
<input type="text" name="gender" id="gender" placeholder='Gender'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="button" value="Next" class="nav next" />
</div>
<div id="qualification" class="page">
<p class='form_head'>Qualification</p>
<p>Qualification</p>
<input type="text" placeholder='Qualification'>
<p>Hobbies</p>
<input type="text" placeholder='Hobbies'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="Submit" value="Submit">
</div>
</form>
</div>
You can use jQuery Steps plugin for these multiple steps form. This will be very easy to handle.

JavaScript validation for empty input field

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>

Categories

Resources