HTML / js. Need two different forms on one page submits separately - javascript

I can't find any answer then ask:
I have to different forms on the page: the one is "ask for call" (placed on every page on the site) and the second is a simple "contact form" (placed only on contact page).
Both are validates without problems, do they are created for also good on the different page. Both has fields which are required. They has different names and IDs.
The error occurs when user on the contact page. There are two forms together. By the order contact is first. And when I use it, a mail sends.
But when I try to send call request with the second form on the page, it doesn't action because on the first form required wasn't filled or didn't match restrictions.
Why submit button from the second form takes data from the first?
Below forms in the order on the contact page and processing functions.
First form (contact)
<form id="message" name="contact_message" onsubmit="return false;" method="post">
<div class="hover">
<label for="message-name">Введите ваше имя:</label>
<input id="message-name" name="name" type="text" placeholder="Имя" title="Пожалуйста, введите ваше имя." required>
</div>
<div class="hover">
<label for="message-email">Введите ваш email адрес:</label>
<input id="message-email" name="email" type="email" placeholder="xxx#xxx.xx" title="Пожалуйста, введите корректно ваш email." required>
</div>
<div class="hover">
<label for="message-text">Введите ваше сообщение:</label>
<textarea id="message-text" name="text" placeholder="Текст сообщения" title="Пожалуйста, введите текст сообщения. Минимум 9 символов." minlength="9" required></textarea>
</div>
<input type="hidden" name="type" value="contact_page">
<button id="submit-contact" class="empty blue button medium" type="submit">Отправить</button>
<div class="c-clearfix"></div>
</form>
The second form
<form id="call-ask-form" name="call-ask-form" class="full-width" onsubmit="return false;" method="post">
<label for="phone-name">Ваше имя</label>
<input id="phone-name" type="text" name="name" placeholder="Введите ваше имя" minlength="2" required>
<label for="phone-phone">Ваш номер телефона (только цифры)</label>
<input id="phone-phone" type="text" name="phone" placeholder="+41234567890" maxlength="16" required>
<label for="phone-time">Время в формате ЧЧ:ММ, с 9 до 17 в будние дни, когда вы ожидаете звонок.</label>
<input id="phone-time" type="text" name="text" placeholder="ЧЧ:ММ" maxlength="5">
<input id="type" name="type" type="hidden" value="call_ask">
<button form="call-ask-form" id="call-submit" class="filled green medium full-width button" type="submit">Отправить запрос</button>
</form>
JS
And here the page_type variable gets data from the first form every time I push submit on the second form. And switch cases on CONTACT, but CALL REQUEST.
$(document).ready(function() {
$("#submit, #call-submit").click(function() {
var proceed = true;
var page_type = $('input[name=type]').val();
//validation
if(proceed)
{
var form;
//choosing type of a message
switch (page_type) {
case 'contact_page' :
// preparing data from CONTACT form
break;
case 'call_ask' :
// preparing data from CALL REQUEST form
break;
case 'calculator' :
break;
default :
}
// ajax post data
$.post('/assets/components/mailer2.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error" style="background-color: red; color: white;">' + response.text + '</div>';
} else {
output = '<div class="success" style="background-color: green; color: white;">' + response.text + '</div>';
}
$(form).append(output).slideDown();
}, 'json');
}
});
Why this happens? Kindly asking you for help.

In the line $('input[name=type]').val();, this will always try to find the value of the first input matching the name criteria on the whole page.
But, note that both of your forms have inputs with the same name.
Javascript will not be very friendly when multiple elements have the same name. Instead, you will either need to rename them or ensure that you better reference which one you are trying to get:
The below code will get you the correct page_type: (Note that in events, this will be set to the current element which in the below case will be one of the <form /> tags which you can use to only traverse it's children using $(this).find(...) as opposed to $(...))
$('form').on('submit', function(e){
var page_type = $(this).find('input[name=type]').val();
alert(page_type);
e.preventDefault();
})

Related

How to show form validation errors in inputs NOT one by one in popups?

I have a very simple form here with 2 required inputs.
When you click submit button without filling them - there are popups saying that you should do it. The problem is that popups are showed one by one - for example, if both inputs arent filled, only the first input will have this popup. And when the first one is filled only then it goes to the second and vice versa.
Is there any way to show all the fields that are not filled/filled incorrect during the validation at the same moment? So the user sees immediately everything he/she has to fill?
I am quite new to this, so please help me find the solution in pure JS (if it is about JS).
Here is the code:
<html lang="eng">
<head>
<title>Title</title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
<form id="mainForm" action="#" method="POST">
<div>
<div>
<label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
<input id="first_name" name="first_name" type="text" value="" required=""
oninvalid="setCustomValidity('Enter first name')" oninput="setCustomValidity('')"
placeholder="Enter first name">
<p class="error_message"></p>
</div>
<div>
<label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
<input id="lastName" name="lastName" type="text" value="" required=""
oninvalid="setCustomValidity('Enter last name')" oninput="setCustomValidity('')"
placeholder="Enter last name">
<p class="error_message"></p>
</div>
<div class="">
<input class="email_btn btn btn-block" type="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
The code you provided is using a built in function of JavaScript, setCustomValidity(). This most likely is the reason for the pop-up. Instead we can write a custom function to show a little paragraph/span with the text instead.
Here we have a HTML form, but with a call for the custom function validateFields(), when clicking the Submit button:
<form class="" action="your-post-page.html" method="post" id="my-form-id" name="my-form-name" onsubmit="return validateFields()" target="_blank" class="validate" novalidate="">
<input id="name_1" type="text">
<br><br>
<input id="name_2" type="text">
<br><br>
<input id="name_3" type="text">
<br><br>
<input type="submit" name="" value="SUBMIT FORM">
</form>
<p id="error_messages" style="background-color: red; color: white;"></p>
The JS that makes it happen:
(custom function that reacts to inputs being empty and lets the user know which fields need fixing, put code before the </html> tag in your html-page)
<script type="text/javascript">
function validateFields() {
// reference to the message paragraph we aim to fill with error messages.
var error_text_output_element = document.getElementById("error_messages");
var fields_to_check = ["name_1", "name_2", "name_3"]; // enter the IDs of all fields you want to check for errors in this list.
var fields_human_names = ["Name 1", "Name 2", "Name 3"]; // these are just the human readable names for the fields.
var check_field;
var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
var errors_exist = 0;
for (var i = 0; i < fields_to_check.length; i++) {
check_field = document.forms["my-form-id"][fields_to_check[i]].value;
if (check_field == "") {
if (errors_exist === 0) {
error_message += fields_human_names[i]; // first time we add a field, no comma.
} else {
error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
}
errors_exist += 1; // increment with one for each error that occurs.
}
}
if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.
error_text_output_element.innerHTML = error_message;
return false; // stops the sending of the form in the post procedure.
}
} // end message_class function.
</script>
Now lastly, here is your own code with this example:
<html lang="eng">
<head>
<title>Title</title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
<form id="mainForm" action="#" method="POST" onsubmit="return validateFields()" >
<div>
<div>
<label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
<input id="first_name" name="first_name" type="text" value="" placeholder="Enter first name">
<p class="error_message"></p>
</div>
<div>
<label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
<input id="lastName" name="lastName" type="text" value="" placeholder="Enter last name">
<p class="error_message"></p>
</div>
<div class="">
<input class="email_btn btn btn-block" type="submit" value="Submit">
</div>
<!-- here I added a new box for the error messages in your code -->
<div class="">
<p id="error_messages" style="background-color: red; color: white;"></p>
</div>
</div>
</form>
</body>
<script type="text/javascript">
function validateFields() {
// reference to the message paragraph we aim to fill with error messages.
var error_text_output_element = document.getElementById("error_messages");
var fields_to_check = ["first_name", "lastName"]; // enter the IDs of all fields you want to check for errors in this list.
var fields_human_names = ["First name", "Last name"]; // these are just the human readable names for the fields.
var check_field;
var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
var errors_exist = 0;
for (var i = 0; i < fields_to_check.length; i++) {
check_field = document.forms["mainForm"][fields_to_check[i]].value;
if (check_field == "") {
if (errors_exist === 0) {
error_message += fields_human_names[i]; // first time we add a field, no comma.
} else {
error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
}
errors_exist += 1; // increment with one for each error that occurs.
}
}
if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.
error_text_output_element.innerHTML = error_message;
return false; // stops the sending of the form in the post procedure.
}
} // end message_class function.
</script>
</html>
That was with custom scripting to get a box that you can style and enhance yourself, in this case below the form. But if you are okay with some default (and perhaps not unified styling, due to browser differences) you can also just remove the JavaScript function you had in your original code, the setCustomValidity(''). That will leave you with a generic message using the already present attribute required="", which produces this:
To achive that behaviour, change your tags for each field to look like this instead:
<input id="first_name" name="first_name" type="text" value="" required="" placeholder="Enter first name">

Hide/locking a <form> button until form is completely filled with validation

I make my JSON script with a form and a button, but when I demo it on someone, they can press the submit button whenever they like. Here is my code:
<form action="action_page.php" method="GET">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"<br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"<br><br>
</form>
All I need now is validation and how to lock or hide the button. I tried using <script> with function and getElementById but I simply do not know how to lock it. Here is the message that will be inputted when it is locked and the form isn't completed:
You have not finished the information input for the survey. Please
input "Your First Name" and "Your Last Name" to enter the survey.
When they finish, I will input a loading icon until fully loaded.
Code Language(s)
I use fiddles to make my code, so I use:
HTML
JSON
Pinch of jQuery (loading icon)
Answer Expectations
In my answers, I need:
Recommended Code Language
Code for note purposes
Crossed out attributes
Attributes before coding explanations
EDIT: I just noticed that I can use the disabled boolean attribute here, so all I need is validation to disable the boolean attribute so they can press the button.
Hello I recommend JavaScript but it is not secure at all. However its the most effective in this case. Here is the code: (Note that i changed the html too)
<form action="action_page.php" method="get" >
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" onkeyup="inputEntries()"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname" onkeyup="inputEntries()"><br><br>
<button type="submit" name="submit" id="submit_btn" disabled="true">submit</button>
</form>
<script>
var fname_var = document.getElementById("fname");
var lname_var = document.getElementById("lname");
var submit_btn_var = document.getElementById("submit_btn");
function inputEntries(){
if(lname_var.value != "" && fname_var.value != "")
submit_btn_var.disabled = false;
else
submit_btn_var.disabled = true;
}
</script>
What it does is that if both input fields are empty the button is not clickable but if both are it can be clicked. hope it helped!
You can use either pure javascript or jQuery to validate.
In the below code you would see we are first binding a change event to the input field and getting its values. If both values are present, the disabled attribute of the submit button is removed. Else the opposite.
<p id="msg">You have not finished the information input for the survey. Please input "*Your First Name*" and "*Your
Last Name*" to enter the survey.</p>
<form action="action_page.php" method="GET">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"<br><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"<br><br><br>
<button type="submit" id="btn-submit">Submit</button>
</form>
$(document).ready(function(){
('#btn-submit').prop('disabled', true);
$("input[type=text]").change(function(){
if ($('#fname').val() && $('#lname').val()) {
$('#btn-submit').prop('disabled', false);
$('#msg').hide();
} else {
$('#btn-submit').prop('disabled', true);
$('#msg').show();
}
});
});
Stackblitz - https://stackblitz.com/edit/jquery-kgzhuo?file=index.html

JQuery ajaxSubmit function is not working for a form in an AngularJS HTML page

I am trying to patch up a legacy image upload code with AngularJS.
I have an HTML page which contains a form. Following is the HTML part of the code.
<form name="testForm" ng-init="testfunc()" novalidate>
<div id="adduser_header">
<div>
<p><b>Add new user</b></p>
</div>
</div>
<div id="userInfo">
<div>
<label>First Name</label>
<input type="text" name="fname" required>
</div>
<div>
<label>Last Name</label>
<input type="text" name="lname" required>
</div>
<div>
<form id="imageuploadForm"
action="/Projectname/jersey/ImageUploader/uploadimage"
method="POST" enctype="multipart/form-data"
accept-charset="utf-8" name="submitForm">
<div>
<input id="imagename" type="text" readonly="readonly"
placeholder="Click browse to upload image">
<div id="uploadImgBtn" onclick="getImgFile()">
<span>Browse</span>
</div>
</div>
<input id="userID" name="userID" type="hidden">
<input id="userImage" name="userImage" type="hidden">
<input id="usertType" name="usertType" type="hidden">
<p style="display: none;">this is your file input tag, so i hide it!
i used the onchange event to fire the form submission</p>
<div><input id="uploadimgfile" type="file" value="upload"
required="required" autofocus="autofocus"
name="imgfile"
onchange="upImgFile(this, event)">
</div>
<input style="display: none;" type="submit" value="Send">
</form>
</div>
</div>
<div id="action_buttons">
<input id="save_user" value="Add User" type="button"
title="Add User"
ng-click="submitRegistrationForm()"
ng-disabled="testForm.$invalid">
<a ui-sref="home-admin" ng-click="return()">
<input id="canceltoreturn" value="Cancel" type="button" title="Cancel">
</a>
</div>
</form>
I am able to Browse and select an image without any problem. My problem begins when i try to submit this AngularJS form. When i click Add User, i am first submitting AngularJS form named testForm which returns a success with an ID of the user. This ID is passed to the following patch of code (legacy):
uploadImage: function(id)
{
if($('#imageuploadForm').find('#userImage').val() != "")
{
$("#imageuploadForm").find("#userID").val(id);
var uploadstatus = null;
$("#imageuploadForm").ajaxSubmit({
success: function(data)
{
uploadstatus = data;
if(uploadstatus == "uploaded")
{
console.log("Uploaded Successfully!");
}
if(uploadstatus == "updated")
{
console.log("Updated Successfully!");
}
else
if(uploadstatus == "problem" || uploadstatus == "notuploaded")
{
console.log("Some problem occurred!");
}
$("#imagename").val("");
$('#imageuploadForm').find('#userImage').val("");
},
error: function(xhr, ajaxOptions, thrownError)
{
console.log(xhr.status);
}
});
}
else
{
alert("Please select some image to upload!")
}
}
When i am debugging the code, it comes till the line.
$("#imageuploadForm").ajaxSubmit
But nothing happens further. The service mentioned in the action attribute (/Projectname/jersey/ImageUploader/uploadimage) is not called at all.
This ajaxSubmit has worked well when the form was purely in HTML. (Also, i am using jquery.form.js for the ajaxSubmit function.)
But since i have tailored the code in AngularJS way, image uploading has stopped working.
What am i doing wrong here? I am not able to understand it. How can i resolve this issue?
It is illegal to nest <form> elements.
From the Docs:
The HTML <form> element represents a document section containing interactive controls for submitting information.
Content categories: Flow content, palpable content
Permitted content: Flow content, but not containing <form> elements
Tag omission: None, both the starting and ending tag are mandatory.
Permitted parents: Any element that accepts flow content
For more information, see
MDN HTML Reference - <form> Element
How to use AngularJS $http to send multipart/form-data

Save Data to Localstorage and use it to populate fields after submit

I have optin popup of two steps, first step is to capture email and name, when user click submit the data is captured, and another popup appears, the new popup has a form with more fields to get more info, plus email and name field.
what I want to do is to automatically populate the email and name field from first popup and hide them with display:none so user can't see them, after submit the data is captured again (all goes to activecampaign).
the two forms works just fine, what is not working is saving the data and calling it when needed
here is the js I'm using
jQuery(function($){
// PART I: Saving user details locally
$('#arlington-field-submit').on('click', function(){
// check if the user's browser has localStorage support
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
// store the full name in localStorage
var fullname = document.querySelector("input[name=arlington-name]");
localStorage.user_name = fullname.value;
// save the email in localStorage
var email = document.querySelector("input[name=arlington-email]");
$("input[name=fullname]").val(localStorage.getItem("server"));
localStorage.user_email = email.value;
}
});
// PART II: Pre-filling forms forms with locally saved values
if (typeof(Storage) !== "undefined") {
// check if the user has a name field stored
if (localStorage.user_name) {
name_field = document.querySelector("._form input[name=fullname]");
name_field.value = localStorage.user_name;
}
// check if the user has an email field stored
if (localStorage.user_email) {
email_field = document.querySelector("._form input[name=email]");
email_field.value = localStorage.user_email;
}
}
});
first form html:
<div id="arlington-element-form" class="arlington-element-form arlington-element" data-element="form">
<div id="arlington-form" class="arlington-form arlington-has-name-email arlington-has-buttons">
<div class="arlington-form-wrap"><input id="arlington-field-comments" name="arlington-comments" type="text" data-selectable="true" data-target="#builder-setting-comments_value" class="arlington-field-comments" placeholder="" value="" style="" autocomplete="off"><input id="arlington-field-name" name="arlington-name" type="text" data-selectable="true" data-target="#builder-setting-name_value" class="arlington-field-name" placeholder="Enter your name here..." value="">
<input id="arlington-field-email" name="arlington-email" type="email" data-selectable="true" data-target="#builder-setting-email_value" class="arlington-field-email" placeholder="Enter your email address here..." value="" >
<input id="arlington-field-submit" name="arlington-submit" type="submit" data-selectable="true" data-target="#builder-setting-submit_value" class="arlington-field-submit" value="JOIN NOW" >
</div>
<div class="arlington-yesno-wrap">
<button id="arlington-button-yes" type="button" name="arlington-yes" data-selectable="true" data-target="#builder-setting-yes_value" data-action="form" data-type="yes" class="arlington-button-yes arlington-button-yesno">Submit!</button>
</div></div></div>
second form html:
<form method="POST" action="xxxxxx" id="_form_8_" class="_form _form_8 _inline-form _dark" novalidate> <input type="hidden" name="u" value="8" /> <input type="hidden" name="f" value="8" /> <input type="hidden" name="s" /> <input type="hidden" name="c" value="0" /> <input type="hidden" name="m" value="0" /> <input type="hidden" name="act" value="sub" /> <input type="hidden" name="v" value="2" />
<div class="_form-content">
<div class="_form_element _x72304349 _full_width "> <label class="_form-label"> Full Name </label>
<div class="_field-wrapper"> <input type="text" name="fullname" placeholder="Type your name" /> </div>
</div>
<div class="_form_element _x10201592 _full_width "> <label class="_form-label"> Email* </label>
<div class="_field-wrapper"> <input type="text" name="email" placeholder="Type your email" required/> </div>
</div>
<div class="_form_element _x29901314 _full_width "> <label class="_form-label"> Phone </label>
<div class="_field-wrapper"> <input type="text" name="phone" placeholder="Type your phone number" /> </div>
</div>
<div class="_button-wrapper _full_width"> <button id="_form_8_submit" class="_submit" type="submit"> Submit </button> </div>
<div class="_clear-element"> </div>
</div>
</form>
Since the input which is being clicked is a submit button, chances are that the page is navigating before the JS within the click handler gets a chance to fire.
Try and replace
$('#arlington-field-submit').on('click', function(){
with:
$('#_form_8_').on('submit', function(event){
Then you can prevent the form from actually submitting so your JS can run:
$('#_form_8_').on('submit', function(event){
event.preventDefault();
// Do localStorage stuff
$(this).submit(); // submit the form normally after localStorage is saved
});
The way you look for elements is wrong, because you forgot quotes wrapping attribute values:
var fullname = document.querySelector("input[name=arlington-name]");
should be:
var fullname = document.querySelector('input[name="arlington-name"]');
And so on...
BTW I'm surprised you don't report an error like "An invalid or illegal string was specified".

html form submiting more fields than expected

I'm dealing with a awful issue, I developed a form with multi fields set (using normal div)
and when I test the submit action I got in the URL the one input not filled, also hidden in
the markup as showed bellow.
http://127.0.0.1:8000/exform.html?user=test&pwd=QWERT1234&user_reg=
And here is the code for the form:
<form id="exform">
<div class="fields" id="login">
<div class="txt">
<label for="user"></label>
<input id="user" type="text" name="user"/>
</div>
<div class="txt">
<label for="pwd"</label>
<input id="pwd" type="password" name="pwd" />
</div>
<input type="submit" value="test" id="test"/>
</div>
<div class="fields" id="register">
<div class="txt">
<label for="user_reg"></label>
<input id="user_reg" name="user_reg" type="text"/>
</div>
<div class="txt">
<label for="pwd2"></label>
<input id="pwd2" type="password" />
</div>
<div class="txt">
<label for="pwdc"></label>
<input id="pwdc" type="password"/>
</div>
<div class="buttons">
<input type="submit" value="OK" id="ok"/>
</div>
</div>
</form>
The strange is that the second field set isn't available in the screen, because in the css
there is a rule to only show the first group with the class "fields"
/*Hide all except first div with class div*/
#exform .fields:not(:first-of-type) {
display: none;
}
So I really want to know why the form is submitting fields out of the scope.
For example, if the second group fieldset is used, when the button submit with value OK is clicked the result produced is similar. In the URL, only the user_reg field parameter is showed filled with the two another fields for the first group without values:
http://127.0.0.1:8000/exform.html?user=&pwd=&user_reg=test
The following code is for submit test:
$(function() {
$('#test').click(function() {
$('#exform').submit(function(event) {
console.log("form Submited:" + document.forms['exform'] + "test");
});
});
$('#ok').click(function() {
$('#exform').submit(function(event) {
console.log("form Submited:" + document.forms['exform'] + "ok");
});
});
});
Doesn't matter I'm got the same URL results
This
http://127.0.0.1:8000/exform.html?user=test&pwd=QWERT1234&user_reg=
or
http://127.0.0.1:8000/exform.html?user=&pwd=&user_reg=test
Instead I'm receiving:
// on #test click
http://127.0.0.1:8000/exform.html?user=test&pwd=QWERT1234
// on #ok click
http://127.0.0.1:8000/exform.html?user_reg=test&pwd2=QWERT1234&pwdc=QWERT123
I can't retrieve the values for pwd2 and pwdc fields in the URL as parameters obtained after submitting.
This got me crazy.
If you do not specify the method method of the form, the default is GET while submitting it. This is the reason to see all form elements in your URL.
Try this:
<form id="exform" method="post">
<!-- form contents -->
See here for details.
When you submit form you submit all it's input fields at ones.
Even if you hide something with css it still exists in html.
When you processed the form you can add a hidden field "input type="hidden"" and give that field a value that tells your script witch fields you want processed in witch case.
And i also fink that post method is better (more secure) especially if you send password.

Categories