I'm trying to figure out how to copy a users text input in one form field to another. Specifically, when someone fills in their email address in the contact form, it will be duplicated in the mailing list form.
Both these forms are using ajax so there's no concerns about the input text being lost on submit.
This is the code I have:
<div id="contact_form">
<form name="contact" method="post" action="">
<input type="text" name="name" id="name" size="30" value="Name" class="text-input" />
<label class="error" for="name" id="name_error">Please enter your name.</label>
<br />
<input type="text" name="email" id="email" size="30" value="Email" class="text-input" />
<label class="error" for="email" id="email_error">I need your email.</label>
<br />
<textarea rows="10" cols="30" type="textarea" name="message" id="message" value="Message" class="text-input" ></textarea>
<label class="error" for="message" id="message_error">A message is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit" value="Send" />
</form>
</div>
<div id="details">
<p>some details here, not sure what yet</p>
</div>
<div id="mail_list">
<input type="text" id="mail" value="Your email" name="mail_list" /><input type="submit" name="submit" class="button" id="submit" value="Send" />
</div>
I found this in the Jquery documentation, but couldn't get it to work:
$("#email").optionCopyTo("#mail");
Thanks!
You said you want it in real time. I assume that means while the user is typing, the value should be replicated for each keystroke.
If that's right, try this:
var mail = document.getElementById("mail");
$("#email").keyup(function() {
mail.value = this.value;
});
Or if you want more jQuery:
var $mail = $("#mail");
$("#email").keyup(function() {
$mail.val( this.value );
});
This will update for each keyup event.
I'd probably add a redundant blur event in case there's an autocomplete in the field.
$("#email").blur(function() {
$mail.val( this.value );
});
Since all your fields have unique ids, this is quite straight forward:
$(function() { // <== Doc Ready
$("#email").change(function() { // When the email is changed
$('#mail').val(this.value); // copy it over to the mail
});
});
Try it out with this jsFiddle
.change()
.val()
Is $("#mail") another input box ? It doesn't appear in your HTML (Edit: well it does now, but didn't at first :)
$("#mail").val($("#email").val()) should do what you want.
use keyup and change both.
$("#boxx").on('keypress change', function(event) {
var data=$(this).val();
$("div").text(data);
});
here is the example
http://jsfiddle.net/6HmxM/785/
you can simply do this
$('#mail').text($('#email').val())
Related
I have a some custom validation for a small input form, that checks if a field is required. If it is a required field it alerts the user, if there is no value. At the moment it will validate all inputs other than check boxes.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label>Question: What is your name?</label>
<input type="text" name="name" id="name"></input>
</div>
<div class="ss-item-required">
<label>Question: What is your email?</label>
<input type="text" name="email" id="email"></input>
</div>
<div class="ss-item-required">
<label>Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label>Do you agree to out terms?</label>
<input type="checkbox" name="Check_0">
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value)
alert(field.name + ' is required');
});
console.log(fields);
}
</script>
If anyone can work out how to include validation of check boxes, it would be much appreciated.
Even though some answers already provide a solution, I've decided to give mine, that will validate every required input in your form, regardless of being a checkbox (maintaining your each loop).
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label>Question: What is your name?</label>
<input type="text" name="name" id="name">
</div>
<div class="ss-item-required">
<label>Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label>Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label>Do you agree to out terms?</label>
<input type="checkbox" name="Check_0">
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
$.each(fields, function(i, field) {
field=$(field).find('input, select, textarea')[0]
if (!field.value || (field.type=='checkbox' && !field.checked))
alert(field.name + ' is required');
});
}
</script>
The problems were:
serializeArray() would try to get the value from your checkbox, and because it returned nothing, the checkbox input was never added to fields!
Checkboxes don't have a property value, instead they are checked
There is more than one way to determine this:
Check the length of the JQuery wrapped set that queries for only checked checkboxes and see if it is 1:
if($("input[name='Check_0']:checked").length === 1)
Check the checked property of the DOM element itself (which is what I'm showing below) for false. To extract the DOM element from the JQuery wrapped set, you can pass an index to the wrapped set ([0] in this case), which extracts just that one item as a DOM element and then you can use the standard DOM API.
if(!$("input[type='checkbox']")[0].checked)
NOTE: It's important to understand that all client-side validation can be easily bypassed by anyone who really wants to. As such, you
should always do a second round of validation on the server that will
be receiving the data.
FYI: You have some invalid HTML: There is no closing tag for input elements and for label elements, you must either nest the element that the label is "for" inside of the label or you must add the for attribute to the label and give it a value of the id of the element that the label is "for". I've corrected both of these things below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label for="userName">Question: What is your name?</label>
<input type="text" name="userName" id="userName">
</div>
<div class="ss-item-required">
<label for="email">Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label for="address">Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label for="Check_0">Do you agree to out terms?
<input type="checkbox" name="Check_0">
</label>
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value){
alert(field.name + ' is required');
}
});
// Check to see if the input is a checkbox and if it's checked
if(!$("input[type='checkbox']")[0].checked){
alert("You must agree to the terms to continue.");
}
}
</script>
Personally (and I'm far from alone on this), the use of JQuery is way overused in today's world. When it came out, the standard DOM API wasn't as mature as it is now and JQuery made DOM element selection and manipulation very simple. Back then, JQuery was a Godsend.
Today, the DOM API has matured and much of what we use to rely on JQuery to make easy, can be done just as easily without JQuery. This means you don't have to reference the JQuery library at all (faster page loading) and you're code follows standards.
If you're interested, here's your code without JQuery:
<form>
<div class="ss-item-required">
<label for="userName">Question: What is your name?</label>
<input type="text" name="name" id="userName">
</div>
<div class="ss-item-required">
<label for="email">Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label for="address">Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label for="Check_0">Do you agree to out terms?
<input type="checkbox" name="Check_0">
</label>
</div>
Submit
</form>
<script>
function formcheck() {
// Get all the required elements into an Array
var fields = [].slice.call(document.querySelectorAll(".ss-item-required > *"));
// Loop over the array:
fields.forEach(function(field) {
// Check for text boxes or textareas that have no value
if ((field.type === "text" || field.nodeName.toLowerCase() === "textarea")
&& !field.value){
alert(field.name + ' is required');
// Then check for checkboxes that aren't checked
} else if(field.type === "checkbox" && !field.checked){
alert("You must agree to the terms to continue.");
}
});
}
</script>
I'm new with Javascript and I'm learning by myself. I have a problem with a form on my page. I just want to test with a simple javascript code that I can manipulate my input "type=submit" by adding a function to it to console.log a string when the form is submitted (I watched it on a video and I wanted to do it by myself).
Here is my code:
(function() {
"use strict";
document.getElementById('enviar').addEventListener('submit', enviar);
function enviar(event) {
event.preventDefault();
console.log("you submitted the form");
}
})();
and this is my HTML code:
<form id="escribenos" method="post">
<label for="name">Nombre y Apellido</label>
<input type="text" name="name" id="name" pattern="[A-Za-z]+\s+[A-Za-z]+" required value=""/>
<label for="email">Correo electrónico</label>
<input type="email" name="email" id="email" required />
<label for="asunto">Asunto</label>
<input type="text" name="asunto" id="asunto" />
<label for="comentario">Mensaje</label>
<textarea maxlength="250" rows="5" name="comentario" id="comentario" style="resize:none;"></textarea>
<input id="enviar" value="enviar" type="submit" ></input>
</form>
The problem that I'm having here is that is not working at all.. my ID element is selected properly but I don't know what is wrong with my code. I created a variable and console my ID selected to see if I was getting the right element from the DOM and I'm getting in the console the right input element. please if someone knows why is not working.
plus: On my text input field I have a regular expression but I'm not getting the output I want.. the goal is that the user has to write at least two names (First and Last), so when they write just one it will be incorrect.. the problem that I'm having with this regular expression if when someone writes more than two names (First, Middle and Last) I DON'T want to make that an incorrect answer because technically is correct. So I need to make a better regular expression to get that result (when the user writes two or more names, not just two) but I don't know too much about Regular Expressions.
You are getting the element with the id enviar which is the submit button element. You need to be querying based on the form's element id which is escribenos. Try running the snippet below and you can see that it has the expected outcome.
(function() {
"use strict";
document.getElementById('escribenos').addEventListener('submit', enviar);
function enviar(event) {
event.preventDefault();
console.log("you submitted the form");
}
})();
<form id="escribenos" method="post">
<label for="name">Nombre y Apellido</label>
<input type="text" name="name" id="name" pattern="[A-Za-z]+\s+[A-Za-z]+" required value=""/>
<label for="email">Correo electrónico</label>
<input type="email" name="email" id="email" required />
<label for="asunto">Asunto</label>
<input type="text" name="asunto" id="asunto" />
<label for="comentario">Mensaje</label>
<textarea maxlength="250" rows="5" name="comentario" id="comentario" style="resize:none;"></textarea>
<input id="enviar" value="enviar" type="submit" ></input>
</form>
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".
Writing some JavaScript so the form does not submit in less the fields have been filled out, and if the user has not, a message pops up saying 'please fill out the name field' or 'please fill out the email field' etc. I am writing a separate function for each field (don't know if that is the right way) and when I add each function to the window.onload, it only pops up with one of the messages. Any advice would be great.
HTML
<form id="frmContact" name="frmContact" method="post" action="thanks.htm">
<fieldset id="quickSupport">
<legend><strong>Quick Support</strong></legend>
<p> If your request isn't urgent, drop us a quick line and we'll get back to you within 24 hours </p>
<p>
<label for="name">Name:</label>
<input type="text" value="Your Name" name="name" id="name" tabindex="10" />
</p>
<p>
<label for="email">Email:</label>
<input type="text" value="Your Email" name="email" id="email" tabindex="20" />
</p>
<label for="comments">Comments </label>
<br />
<textarea name="comments" value="Message" id="comments" cols="45" rows="5" tabindex="60" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;">Message</textarea>
</p>
<p>
<input type="submit" name="submit" id="submit" value="Send" tabindex="70" />
</p>
</fieldset>
</form>
<p><span id="errorMessage"></span></p>
<p><span id="errorMessage1"></span></p>
JavaScript
function prepareEventHandlers () {
document.getElementById("frmContact").addEventListener("submit", function(event) {
// Show message
if (document.getElementById("email").value == "Your Email") {
document.getElementById("errorMessage").innerHTML = "Please provide at least an email address!";
// to STOP the form from submitting
return false;
} else {
// reset and allow the form to submit
document.getElementById("errorMessage").innerHTML = "";
return true;
}
event.preventDefault(); // Prevent form from submitting
}
});
}
function prepareEventHandlersName () {
document.getElementById("frmContact").addEventListener("submit", function(event) {
// Show message
if (document.getElementById("name").value == "Your Name") {
document.getElementById("errorMessage1").innerHTML = "Please provide a name!";
// to STOP the form from submitting
return false;
} else {
// reset and allow the form to submit
document.getElementById("errorMessage1").innerHTML = "";
return true;
}
event.preventDefault(); // Prevent form from submitting
}
});
}
function start() {
prepareEventHandlers();
prepareEventHandlersName();
}
window.onload = start;
You should use the browser's built-in validation attributes.
<form id="frmContact" name="frmContact" method="post" action="thanks.htm">
<fieldset id="quickSupport">
<legend><strong>Quick Support</strong></legend>
<p>If your request isn't urgent, drop us a quick line and we'll
get back to you within 24 hours</p>
<p>
<label for="name">Name:</label>
<input type="text" value="Your Name" name="name" id="name"
tabindex="10" required />
</p>
<p>
<label for="email">Email:</label>
<input type="text" value="Your Email" name="email" id="email"
tabindex="20" required />
</p>
<label for="comments">Comments</label>
<br />
<textarea name="comments" value="Message" id="comments" cols="45"
rows="5" tabindex="60"
placeholder="PLACEHOLDER WHEN NO MESSAGE IS WRITTEN" required>Message</textarea>
</p>
<p>
<input type="submit" name="submit" id="submit" value="Send"
tabindex="70" />
</p>
</fieldset>
</form>
When you try to submit the form, the browser will automatically display nice error messages for you, in the user's language. No JavaScript required.
The reason your code is failing, because
document.getElementById("frmContact").onsubmit = ...
will override any previous onsubmit handler you've added.
You need to use .addEventListener() instead, if you want to add multiple functions.
A more correct way would be to create a single function that does all checks, and attach that as the handler, once.
Both functions are running, but you're overwriting the onsubmit handler for frmContact in your second function. To avoid this, don't assign event handlers that way. Instead, use addEventListener.
document.getElementById("frmContact").addEventListener("submit", function(event) {
if (document.getElementById("email").value == "Your Email") {
// Show message
event.preventDefault(); // Prevent form from submitting
}
});
Note that when you do it this way, you can't prevent the form from submitting by simply returning false. Instead, you have to use the event's preventDefault method.
I am trying to pass values between boxes.
So, When a User types inside of the first text box:
<input type="text" placeholder="Your personal message" id="valbox"></input>
<input type="submit" name="design1" id="butval" value="Choose Design"></input>
Then they click the 'choose design' button, and what they typed in, gets passed to another
input text box on the same page.
this is the second input box i want to pass it to.
<input type="text" class="input-text" name="billing_last_name" id="billing_last_name" placeholder="" value="">
Any help would be much appreciated
thank you
Live Demo
Instead of a submit type input use a button type input.
HTML
<input type="text" placeholder="Your personal message" id="valbox"></input>
<input type="button" name="design1" id="butval" value="Choose Design"></input>
<input type="text" class="input-text" name="billing_last_name" id="billing_last_name" placeholder="" value="">
JS
window.onload = function(){
document.getElementById('butval').onclick = function(){
document.getElementById('billing_last_name').value = document.getElementById('valbox').value;
}
};
First add a clicklistener for the submit button and inside that callback pass the text through the elements
document.getElementById("butval").addEventListener("click", function(event){
var text = document.getElementById("valbox").value;
document.getElementById("billing_last_name").value = text;
event.preventDefault();
return false;
});
this is by far easiest in jquery given
<input type="text" placeholder="Your personal message" id="valbox"></input>
<input type="submit" name="design1" id="butval" value="Choose Design"></input>
<input type="text" class="input-text" name="billing_last_name" id="billing_last_name" placeholder="" value="">
use a simple
$("#butval").click(function(event){
$("#billing_last_name").html("<p>"+$("#valbox").html()+"</p>");
event.preventDefault();
});
but better change type="submit" to type="button" then you can remove the essentially unnecessary line event.preventDefault();