Finding which forms are filled out on submit - javascript

I need to use unobtrusive javascript/jquery to check if input fields have been filled out. If they are I need to display what input field that was. Not the value.
Here is the input form
<div class="inputCol">
<div class="formItem first-name">
<label>First Name:</label>
</div>
<div class="inputCol">
<input maxlength="40" size="35" id="firstName" name="firstName" class="imput_value" type="text" />
</div>
<div class="formItem last-name">
<label>Last Name:</label>
</div>
<div class="inputCol">
<input maxlength="40" size="35" id="lastName" name="lastName" class="imput_value" type="text" />
</div>
<div class="formItem email">
<label>Email:</label>
</div>
<div class="inputCol">
<input maxlength="40" size="35" id="email" name="email" class="imput_value" type="text" />
</div>
<div class="inputCol">
submit
</div>
So on click of the submit button I need it to alert "First Name, Email" if just the first name and email had input in them. These inputs do not need to be validated. As long as the field is not empty it should display that that input has been submitted.
This is the code I currently have, don't really know where to go from here:
$('a.submit_button').click(function(){
var validate= false;
$('input.imput_value').each(function(){
if($(this).val() != '' || $(this).attr('checked'))
validate = true;
});
if(validate){
var dataFilled = $(this).closest('.formItem').find('input').text().trim();
alert(dataFilled);
return false;
}
});

$('a.submit_button').click(function(){
var filledInputs = '';
$('input.imput_value').each(function(){
if($(this).val() !== '' || $(this).attr('checked')){
filledInputs += $(this).attr('name') + ', ';
}
});
if(filledInputs !== ''){
alert(filledInputs);
}
});
Should do what you want.

Related

How to check all the form fields were given to enable the submit button?

I need to enable the submit button, only when all the Input values were given.
I have a form like the below in my blade file.
<form method="POST" id="contactForm">
<div class="row">
<div class="col-6">
<input type="text" name="name" id="name" value=""/>
<div class="error">Error Message</div>
</div>
<div class="col-6">
<input type="text" name="email" id="email" value=""/>
<div class="error">Error Message</div>
</div>
<div class="col-12">
<textarea name="body" id="message" rows="5"> Enter your message</textarea>
<div class="error">Error message</div>
</div>
<div class="col-12">
<input type="submit" value="Submit" class="primary" id="buttonSubmit" disabled/>
</div>
</form>
Added the required attribute inside the controller.
In controller:
public function store()
{
$data = request()->validate([
'name' => 'required',
'email' => 'required|email',
'body' => 'required',
]);
}
The problem is, even if I add the name field and click the button , the submit button is disabled on click.
The button should be disabled, only when all the input fields were given.
Script:
const button = document.querySelector("#buttonSubmit");
const buttonExpirationDataKey = 'button-disabled-expiration';
button.addEventListener("click", () => {
var form = document.getElementById("contactForm");
var fields = ["name", "email","body"];
var i, l = fields.length;
var fieldname;
for (i = 0; i < l; i++) {
fieldname = fields[i];
if(form[fieldname].value !== ""){
button.disabled = true;
let now = new Date();
let expirationTime = 1000 * 5; // 5 secs to disable the submit button
let expirationDate = new Date(now.getTime() + expirationTime);
localStorage.setItem(buttonExpirationDataKey, expirationDate);
button.dataset.enabledAt = expirationDate;
}
else {
button.disabled = false;
}
return false;
}
});
The for loop iterates over each input element, if the particular input element have a value and then If we click the submit. The button is disabled and stored in the local storage.
How to check all the form input and the textarea has values and then after clicking the submit button, the button should be disabled for 5 secs.
https://jsfiddle.net/1vgzj8oc/
How could I do this? Could anyone please help?
You can simply add the required attributes to the HTML
<input type="text" name="name" id="name" value="" required/>
But if you choose to do it with jS, you can do it this way...
<input type="text" name="name" id="name" value="" class="requiredInput"/>
<input type="submit" value="Submit" class="requiredInput primary" id="buttonSubmit" disabled/>
const requiredInputs = document.querySelectorAll(".requiredInput");
requiredInputs.forEach(function(input) {
// Logic
});
You can add required attribute. added link for reference
[https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required]
<form method="POST" id="contactForm">
<div class="row">
<div class="col-6">
<input type="text" name="name" id="name" value="" required/>
<div class="error">Error Message</div>
</div>
<div class="col-6">
<input type="text" name="email" id="email" value="" required/>
<div class="error">Error Message</div>
</div>
<div class="col-12">
<textarea name="body" id="message" rows="5" required> Enter your message</textarea>
<div class="error">Error message</div>
</div>
<div class="col-12">
<input type="submit" value="Submit" class="primary" id="buttonSubmit" disabled/>
</div>
</form>

onsubmit form validation. Form submits even though there are errors

I created a registration page, and each field requires entry and validation. I used the onsubmit event to call my js function to validate the form if the field is empty, however it still submits even though it has not been validated properly.
function validate() {
var streetName = document.getElementById("sN").value;
if (streetName == "" || streetName == null || streetName == undefined) {
window.alert("Sorry");
return false;
}
}
<form name="myForms" action="https://httpbin.org/post " method="post" class="form" onsubmit="return validate()">
<div id="fN">
<label>First Name</label>
<input type="text" name="firstName" placeholder="Enter first name" required>
</div>
<br>
<div class="lN">
<label>Last Name</label>
<input type="text" name="lastName" placeholder="Enter last name" required="">
</div>
<br>
<div class="sN">
<label>Street name</label>
<input type="text" name="streetname" placeholder="Enter your street name">
</div>
// Somemore inputs
<input class="buttons" type="submit" name="submit" value="Sign up" onclick="validate()">
</form>
I expect a window to pop up saying "this entry is wrong and for this reason", but it submits anyway
EDIT: I apologize I should've been clearer in my post. I will use required in some of the inputs, however I will eventually need to write js code to ensure a phone number is all digits and password = passwordconfirm and a postal code is an actual postal code. In the JS file I just showed what I basically tried doing.
Several things
You have validate on the submit AND on the form submit
You should NEVER call anything in a form "submit" since it will hide the submit event/method
You need to get the correct field
Give the form an ID and use unobtrusive code like this
window.addEventListener("load", function() {
document.getElementById("myForm").addEventListener("submit", function(e) {
var errors = false;
var streetName = this.streetname.value.trim(); // no more action needed
if (!streetName) errors = true;
// more validations
if (errors) {
window.alert("Sorry");
e.preventDefault();
}
});
});
<form id="myForm" action="https://httpbin.org/post " method="post" class="form">
<div id="fN">
<label>First Name</label>
<input type="text" name="firstName" placeholder="Enter first name" >
</div>
<br>
<div class="lN">
<label>Last Name</label>
<input type="text" name="lastName" placeholder="Enter last name" >
</div>
<br>
<div class="sN">
<label>Street name</label>
<input type="text" name="streetname" placeholder="Enter your street name">
</div>
<input class="buttons" type="submit" name="SubmitButton" value="Sign up">
</form>
var streetName = document.getElementById("sN").value;
There is no element with that id in the document.
There is an element with sN as its class name, but getElementById won't find an element by its class and the value of <div class="sN"> will always be undefined. It is the input that will have a value.

How to hide/show a text-box base on other text-box in Laravel 4?

Goal
show email confirm when a user start editing the email section.
hide the email confirm text-box if the user doesn't touch it.
Don't do anything if the user only edit the username part.
Edit Form
username* __________________________
email* __________________________
email confirm* _____________________
HTML/BLADE
<div class="form-group">
<label class="col-sm-3 control-label required ">Username </label>
<div class="col-sm-9 form-group float-label-control ">
{{ Form::text('username', isset($user->username) ? $user->username : '' , array('id'=>'form-field-icon-2')); }}
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label required ">Email </label>
<div class="col-sm-9 form-group float-label-control ">
{{ Form::text('email', isset($user->email ) ? $user->email : '' , array('id'=>'form-field-icon-2')); }}
</div>
</div>
HTML
<label> Username </label><br>
<input type="text" name="username"><br>
<label> Email </label><br>
<input type="text" name="email" id="email"><br>
<label id="l-email-conf" > Email Confirm </label><br>
<input type="text" name="email_confirm" disabled="disabled" id="email-conf">
JS
$('#l-email-conf').hide();
$('#email-conf').hide();
$('#email').on('input', function (event) {
var text = $(this).val();
if (text === '') { // If email is empty
$('#email-conf').prop('disabled', true);
} else {
$('#email-conf').prop('disabled', false);
$('#email-conf').show();
$('#l-email-conf').show();
}
});
JSFiddle
Inline javascript could be an elegant solution if you don't want to write a function.
onkeyup and onkeydown events will do the job and you don't need jQuery
<form>
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email" onkeyup="this.parentNode.nextElementSibling.style.display = 'block';" onkeydown="this.parentNode.nextElementSibling.style.display = 'none';"/>
</p>
<p id="confirm-email">
<label for="confirm">Confirm email</label>
<input type="text" name="confirm" id="confirm"/>
</p>
</form>
CSS:
#confirm-email {
display: none;
}
Example: jsFiddle
Say this is your HTML -
<input type="text" name="username">
<input type="text" name="email" id="email">
<input type="text" name="email_confirm" disabled="disabled" id="email-conf">
<script>
// Use jQuery event handlers
$('#email').on('input', function (event) {
var text = $(this).val();
if (text === '') { // If email is empty
$('#email-conf').prop('disabled', true);
} else {
$('#email-conf').prop('disabled', false);
}
});
</script>
jsFiddle
P.S. - U can toggle hide/show instead of disabling also.

jQuery's val() returns empty string on bootstrap popover input field

I have a bootstrap popup form with a few input fields. I've added a submit button to the form, that triggers client-side JS validation. However, when the button is clicked, the current value of the input fields is not captured by jQuery's val() method: I just get an empty string.
Here is the markup:
<div class="popover fade right in" style="top: -154.5px; left: 249px; display: block;">
<div class="arrow">
</div>
<h3 class="popover-title">New Job Site contact</h3>
<div class="popover-content">
<form class="popover-form form-horizontal" id="newjobsite_contact_form" accept-charset="utf-8" method="post" action="http://dev.temperature/home/#">
<div class="form-group">
<div class=" required ">
<input type="text" class="form-control" id="popover-first_name" required="1" placeholder="First name" value="" name="first_name">
</div>
<div class=" required ">
<input type="text" class="form-control" required="1" placeholder="Surname" value="" name="surname">
</div>
<div class=" required ">
<input type="text" class="form-control" required="1" placeholder="Phone" value="" name="phone">
</div>
<div class="">
<input type="text" class="form-control" placeholder="Mobile" value="" name="mobile">
</div>
<div class="">
<input type="email" class="form-control" placeholder="Email" value="" name="email">
</div>
<div class="">
<input type="url" class="form-control" placeholder="Website" value="" name="website">
</div>
</div>
<div class="popover_buttons">
<button class="btn btn-success" onclick="submit_newjobsite_contact(); return false;" type="button" id="newjobsite_contact_submit">Submit</button>
<button class="btn btn-warning" onclick="close_newjobsite_contact(); return false;" type="button" id="newjobsite_contact_cancel">Cancel</button>
</div>
</form>
</div>
</div>
Here is the JS:
function submit_newjobsite_contact() {
errors_found = validate_popover_form($('#newjobsite_contact_form'));
if (errors_found.length == 0) {
// Form values submitted to PHP code through AJAX request here
} else {
error_msg = "Please check the following errors:\n";
$(errors_found).each(function(key, item) {
error_msg += "- "+item.message+"\n";
});
alert(error_msg);
}
}
function validate_popover_form(form_element) {
found_errors = [];
$('span.error').remove();
form_element.find('select,input').each(function(key, item) {
if ($(item).attr('required') && $(item).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(item).attr('name'), message: "A value for "+$(item).attr('placeholder')+" is required"});
}
console.log($(item).val()); // More validation here, just putting debugging code instead
});
return found_errors;
}
What am I doing wrong? All other attributes for these input fields are being correctly retrieved by jQuery, just not the value after I've typed text into them.
The answer to this problem couldn't be found here because I didn't post the whole source JS, which is too large. What really happened is that I accidentally cloned the popover form, which led to a duplication of the input fields.
form_element.find('select,input').each(function(key, item) {
if ($(item).attr('required') && $(item).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(item).attr('name'), message: "A value for "+$(item).attr('placeholder')+" is required"});
}
I Modified it to:
form_element.find('select,input').each(function(key, item) {
if ($(this).data('required') == '1' && $(this).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(this).attr('name'), message: "A value for "+$(this).attr('placeholder')+" is required"});
}
Try using data attributes so instead of using required="1" use data-required="1"
<input type="text" class="form-control" required="1" placeholder="Surname" value="" name="surname">
so your input should be like this:
<input type="text" class="form-control" data-required="1" placeholder="Surname" value="" name="surname">

Prevent elements from clearing after failed validation on nested .NET master page

The validation works perfectly, but if the validation fails, the form clears all data.
How can I validate the form without causing the user to have to re-enter all the data again? Due to the nature of the redirect, I need the html form to render exactly as it does now.
HTML:
<div class="formHalf">
<label for="first_name">
First Name*</label>
<input id="first_name" maxlength="40" name="first_name" size="20" type="text" class="text" />
</div>
<div class="formHalf">
<label for="last_name">
Last Name*</label>
<input id="last_name" maxlength="80" name="last_name" size="20" type="text" class="text" />
</div>
<div class="formWhole">
<label for="company">
Company</label>
<input id="company" maxlength="40" name="company" size="20" type="text" class="text" />
</div>
<div class="formWhole">
<label for="address">
Address</label>
<input id="address" maxlength="80" name="address" size="20" type="text" class="text" />
</div>
<div class="formHalf">
<label for="city">
City</label>
<input id="city" maxlength="40" name="city" size="20" type="text" class="text" />
</div>
<div class="formHalf">
<label for="state">
State/Province</label><input id="state" maxlength="20" name="state" size="20" type="text"
class="text" />
</div>
<div class="formHalf">
<label for="zip">
Zip</label><input id="zip" maxlength="20" name="zip" size="20" type="text" class="text" />
</div>
<div class="formHalf">
<label for="country">
Country</label><input id="country" maxlength="40" name="country" size="20" type="text"
class="text" />
</div>
<div class="formHalf">
<label for="email">
Email*</label><input id="email" maxlength="80" name="email" size="20" type="text"
class="text" />
</div>
<div class="formHalf">
<label for="phone">
Phone*</label><input id="phone" maxlength="40" name="phone" size="20" type="text"
class="text" />
</div>
<div class="formWhole">
<label for="description">
Description</label><textarea name="description"></textarea>
</div>
<div class="formWhole">
<input type="submit" name="formSubmit" id="formSubmit">
</div>
</div>`
SCRIPT:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#formSubmit").click(function () {
for (i = 0; i < 1; i++) {
var isValid = validateForm();
if (isValid) { }
$("form").attr("action", "https://www.other web site that redirects back to my page after logging form");
}
});
});
function validateForm() {
var message = "";var message2="";
var elements = new Array("first_name", "last_name", "phone", "email");
var userElement = new Array(" First Name", "Last Name", "Phone Number", "E-Mail Address");
for (i = 0; i < elements.length; i++)
{
var x = document.getElementById(elements[i]).value;
if (x == null || x == "") {
if (message != "")
message += ", "; message += userElement[i];
}
if (i == 3 && x != null && x != "") {
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
message2 += "The email address is not valid.";
}
}
if (i == 2 && x != null && x != "") {
var checknumber = x.replace(/[^0-9]/g, '');
if (checknumber.length != 10 && checknumber.length != 11) {
message2 += "The phone number is needs to be in format 123-456-7890 or 1-234-567-8901.";
}
}
// email and phone validation
}
if (message != "" || message2 != "") {
if (message != "") {
message += " must be filled out.";
}
message += message2;
alert(message);
return false;
}
return true;
}
</script>`
The easiest way is just to catch the POST or GET value's on the server's side. When using PHP for example you can refill the First name by adding the following the corresponding input-tag:
value="<?=$_POST['first_name']?>"
You should change the POST tot GET if it's a get-action. Don't forget to additionally validate at the server's side.
if the extension of your page is aspx then add the runat="server" attribute to each data input tag and then you will have the data persisted !

Categories