how to give "same as the above" in form entries - javascript

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form method="POST" class="form-group">
<label>First Name</label><input type="text" name="FName" class="form-control">
<label>Last Name</label><input type="text" name="LName" class="form-control"><br>
<label>I am Ready</label><input type="checkbox" name="ch"><br><br>
<label>Address</label><input type="text" name="Address" class="form-control">
</form><br><br>
<form method="POST" class="form-group">
<label>Same as Above</label><input type="checkbox" name="chd"><br><br>
<label>First Name</label><input type="text" name="FName" class="form-control">
<label>Last Name</label><input type="text" name="LName" class="form-control"><br>
<label>I am Ready</label><input type="checkbox" name="ch"><br><br>
<label>Address</label><input type="text" name="Address" class="form-control">
</form>
when we checked the checkbox named 'same as the above' then the second form will have to take same values that are in the first form fields.

you can use jQuery like suppose you have 2 input fields and a checkbox
if you click on checkbox it has to get value from first input and assign it to second like
$(function(){
("#checkbox").click(function(){
if($(this).is(':checked')){
var input1=$("#input1").val();
$("#input2").val(input1);
}
});
});

You need to start listening on proto form fields changes if "same as above" checked and stop listening if unchecked. And when value of any field changes then just proxy values of all proto form fields to surrogate form fields
(function($) {
var $forms = $('form');
var $protoForm = $forms.eq(0);
var $surrogateForm = $forms.eq(1);
var proxyValues = function(name) {
var $fields = $protoForm.find('input');
if (typeof name === 'string') {
$fields = $fields.filter('[name="' + name + '"]');
}
$fields.each(function() {
var field = $surrogateForm.find('[name="' + name + '"]').get(0);
if (field.type === 'checkbox') {
field.checked = this.checked;
} else {
field.value = this.value;
}
});
};
var startValuesProxy = function() {
proxyValues();
$protoForm.on('change.valuesProxy', 'input', function(e) {
proxyValues(e.target.name);
});
};
var stopValuesProxy = function() {
$protoForm.off('.valuesProxy');
};
$surrogateForm.on('change', '[name="chd"]', function(e) {
if (e.target.checked) {
startValuesProxy();
} else {
stopValuesProxy();
}
});
})(jQuery);

1) When You check the checkbox, which would mean you would need to create a hidden field on your Address form, and have the results of the address form fields that you require passed to the hidden fields on the address form.
2) On Checked Box Checked Event. Example
Hope Its Work !!!

In my experience you can just disable the controls - seems to be that way on other sites - then in your submit method - if the checkbox is clicked - send that to the controller and use the 'above' values there too..
$(function() {
$('#chkSameAsAbove').on('change', function() {
var otherControls = $(this).parent().find('input:not(#chkSameAsAbove)');
if($(this).is(':checked')) {
otherControls.prop('disabled', true);
} else {
otherControls.prop('disabled', false);
}
});
});
https://jsfiddle.net/7xv5bv4h/

Get all the inputs in javascript.
Let's say you have two input fields and one checkbox, if checkbox is checked both field will have same value, if not user will enter second value in second input.
so lets try this code:
var input1 = document.getElementById("input1");
if (document.getElementById('checkbox_field_ID').checked) {
$('#input2').append(input1);
}
I hope it helps :)

Related

How trigger validation on a textbox when a button is pressed?

I've got two text boxes for first and last name. I also have a button to save the data. The button has an event handler where it grabs the data from the fields and posts them with an ajax call to my API, using jquery.
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Here is an example which may help you:
$('#save').click(function() {
var errors = [];
var name = $('#name').val();
var vorname = $('#vorname').val();
if (!name) {
errors.push("Name can't be left blank");
}
if (!vorname) {
errors.push("Vorname can't be left blank");
}
if (errors.length == 0) {
console.log('Ajax started');
//put here your ajax function
} else {
for (var i in errors) {
console.log(errors[i]);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Name" id="name"><br>
<input placeholder="Vorname" id="vorname"><br>
<button id="save">Save</button>
here is an example using the popular add on jquery validate. https://jqueryvalidation.org/
click the run snippet button below
$(document).ready(function() {
$("#form").validate({
rules: {
"firstname": {
required: true,
},
"lastname": {
required: true,
}
},
messages: {
"firstname": {
required: "Please, enter a first name"
},
"lastname": {
required: "Please, enter a last name"
},
},
submitHandler: function(form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<form id="form" method="post" action="#">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<button type="submit">Submit</button>
</form>
Without seeing your code, it is very difficult to guess the correct scenario to provide examples for.
Given the following HTML:
<form>
<input type="text" class="text1">
<input type="text" class="text2">
<button type="button">Send</button>
</form>
You could use this for the jQuery part:
$('button').click(function() {
var txt1 = $(this).siblings('.text1').val();
var txt2 = $(this).siblings('.text2').val();
if (txt1.length && txt2.length) {
// do your ajaxy stuff here
} else {
alert("Imput some friggin' text!");
}
});
$(this) selects the button clicked.
.siblings('.text1') selects the input with class text1 inside the same block as the clicked button.
https://jsfiddle.net/sg1x0c3q/7/
As per my comments I would recommend using a form. But if you want a pure JS solution here you go. (if you want a form based solution just ask)
// convert all textareas into key value pairs (You can change the selector to be specific to your markup)
const createPayload = () => {
return [].slice.call(document.querySelectorAll('textarea')).reduce((collection, textarea) => ({
...collection,
[textarea.name]: textarea.value
}), {})
}
// Compare Object values against values that are not falsy (you could update the filter with a RegExp if you wanted more complicated validation)
const objectHasAllValues = obj => {
return Object.values(obj).length == Object.values(obj).filter(value => value).length
}
// If all key value pairs are not falsy then submit
window.submit = () => {
const payload = createPayload()
if (objectHasAllValues(payload)) {
fetch('/your/api', payload)
}
}
This solution presumes that your API expects a JSON payload. If you are expecting to send form data then you would need to use the formData js api.
This scales and doesn't need jQuery :)
Working example here https://jsfiddle.net/stwilz/dxg29mkj/28/
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Answer to form validation. I assume that First name and Last name can only contain alphabets ,i.e., only a-z and A-Z.
//This function will trim extra whitespaces form input.
function trimInput(element){
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s){
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name){
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#myForm').submit(function(e){
e.preventDefault();
var fname = $(this).find('input[name="fname"]');
var lname = $(this).find('input[name="lname"]');
var flag = true;
trimInput(fname);
trimInput(lname);
if(isEmpty($(fname).val()) === false || isName($(fname).val()) === false){
alert("First name is invalid.");
flag = false;
}
if(isEmpty($(lname).val()) === false || isName($(lname).val()) === false){
alert("Last name is invalid.");
flag = false;
}
if(flag){
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" id="myForm" method="post" action="#">
<input type="text" name="fname" placeholder="Firstname">
<input type="text" name="lname" placeholder="Last Name">
<input type="submit" name="submit" value="Submit">
</form>
I am not using the <form> tag for this.
Then the code will be like
//This function will trim extra whitespaces form input.
function trimInput(element) {
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s) {
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name) {
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#submit').click(function() {
var fname = $('#fname');
var lname = $('#lname');
var flag = true;
trimInput(fname);
trimInput(lname);
if (isEmpty($(fname).val()) === false || isName($(fname).val()) === false) {
alert("First name is invalid.");
flag = false;
}
if (isEmpty($(lname).val()) === false || isName($(lname).val()) === false) {
alert("Last name is invalid.");
flag = false;
}
if (flag) {
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname" placeholder="Firstname">
<input type="text" id="lname" name="lname" placeholder="Last Name">
<button type="button" id="submit" name="submit">Submit</button>
Check the code on jsFiddle.
Hope this will be helpful.

jquery focus and auto submit after last input is filled

I have two situation with jquery,
I have two text box(name, age), now what i need to do is auto focus the name onload while the age is disabled, once user key in an input on name, it become disabled and switch with age textbox(enable and focus). once the age textbox is filled, the jquery will auto submit it w/o any button
now first things is, I am able to disable and enable the textbox, but when i put document.name.focus() its not working, I mean, the focus is not working.second things is, i manage to do the auto submit using this code
$(document).ready(function(){
$('[name="age"]').blur(function(){
if(this.value != ''){
document.form.submit();
}
});
});
so after the last textbox is filled, it will auto submit, but the problem is, I keep receive this error "Notice: Undefined index: name in C:\location" whenever i run it.
here is my code :
<script>
$(document).ready(function(){
$('[name="age"]').blur(function(){
if(this.value != ''){
document.form.submit();
}
});
});
$(document).ready(function() {
$('[name="name"]').blur(function() {
var that = $('[name="age"]')[0];
if (this.value != '') {
this.focus();
this.disabled = true;
that.disabled = false;
}
});
});
function focusName(){
var count = document.form.name.value.length + 1;
if(count <= 8){
document.form.name.focus();
}else{
document.form.age.focus();
}
}
function focusAge(){
var count = document.form.age.value.length + 1;
if(count <= 10){
document.form.age.focus()
}else{
document.form.submit();
}
}
</script>
<fieldset>
<legend>Information </legend>
<form action="receive.php" method="post" name="form">
name : <input type="text" name="name" onKeyUp="focusName();" maxlength="8"><br>
Age : <input typr="text" name="age" disabled onKeyUp="focusAge();" maxlength="3"><br>
<!--input type="submit"-->
</form>
</fieldset>
please help!!.thanks.
Few tips : add some id on your textbox
Example :
name : <input type="text" id="name" name="name" onKeyUp="focusName();" maxlength="8"><br>
Age : <input typr="text" id="age" name="age" disabled onKeyUp="focusAge();" maxlength="3">
Focus the name onload (with JQuery):
$(document).ready(function(){$("#name").focus();})
Auto submit your form :
$("form :input").focusout(function(){
$(this).each(function(){
if($(this).val()=="" )
{
return false;
}
});
$("form").submit();
});

I want to make the input field has unique value

let us say that there is 5 input field for page (A)
<form class="classesName" action="action.php" method="POST">
<input type="text" name="class1" placeholder="Class Name1?" required="">
<input type="text" name="class2" placeholder="Class Name2?" required="">
<input type="text" name="class3" placeholder="Class Name3?" required="">
<input type="text" name="class4" placeholder="Class Name4?" required="">
<input type="text" name="class5" placeholder="Class Name5?" required="">
</form>
I want the user to fill all the fields BUT it must be unique class name for each field
so he can't fill
class a
class b
class a < this one is duplicated so it should display an error message
class c
class d
I think I can make if statement in the action.php page to check is there a duplication in the submitted field or not
but I don't want all the other values to be lost when I reload this page again to display the error for him
is there like a property in html5 or anything like that ?
thanks
No, this cannot be done with HTML5 alone. You'll have to write some JavaScript to make this happen. The JavaScript code should check all the values and if any two are identical prevent the form from submitting successfully.
In this case you could use javascript to validate the fields every time the user fills out a textbox. Here is an example:
$('input[type=text]').on('change',function(){
var arr = [];
$siblings = $(this).siblings();
$.each($siblings, function (i, key) {
arr.push($(key).val());
});
if ($.inArray($(this).val(), arr) !== -1)
{
alert("duplicate has been found");
}
});
JSFiddle: http://jsfiddle.net/x66j3qw3/
var frm = document.querySelector('form.classesName');
var inputs = frm.querySelectorAll('input[type=text]');
frm.addEventListener('submit', function(e) {
e.preventDefault();
var classArr = [];
for(var i = 0; i < inputs.length; i++) {
if(classArr.indexOf(inputs[i].value) != -1) {
inputs[i].style.backgroundColor = "red";
return false;
}
else
classArr.push(inputs[i].value);
}
frm.submit();
});
jsfiddle DEMO

Execute code when textboxes have data

I have a project which I have to calculate the coordenates between two points. The first coordenates are calculated once the user enters in three text boxes the street, province and city.
How can I execute the code I have in PHP once the user fills out all three boxes and not before?
<form name="form" action="" method="post">
<input type="text" name="provincia" id="provincia">
<input type="text" name="municipio" id="municipio">
<input type="text" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
This is the form the user has to fill in. Once the user writes in all three (without mattering the order) I have php code which Im not sure if it can execute once these boxes have values.
What should I have to use to accomplish this? Ajax? Jquery? Javascript?
Not really sure,
thanks.
are you looking for this?
$(document).ready(function () {
var flag = false;
$("input[type=text]").change(function () {
flag = true;
$("input[type=text]").each(function () {
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
alert(values);
});
});
edit
<form name="form" action="" method="post">
<input type="text" class="tobeChecked" name="provincia" id="provincia">
<input type="text" class="tobeChecked" name="municipio" id="municipio">
<input type="text" class="tobeChecked" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
$(document).ready(function () {
var flag = false;
$(".tobeChecked").change(function () {
var values = "";
flag = true;
$(".tobeChecked").each(function () {
values += $(this).val().trim() + "+";
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
});
});
Create a function to validate the required field for those three text boxes and once all are filled with values execute your script:
$('#provincia,#municipio,#calle').blur(function(){
if($('#provincia').val() !="" && $('#municipio').val() !="" && $('#calle').val() !=""){
// Do your process here
}
});
You can use jquery validate plugin to validate these 3 input fields on the client side itself, In that way, the user cannot submit the form until he completely fills the input fields.
Give your Button an ID like:
<input type="submit" id="button" value="¡Buscar!"/>
Then you can do this in JQuery:
$("#button").click(function(){
//Get the value of the fields
var textfield1 = document.getElementById("provincia").value;
var textfield2 = document.getElementById("municipio").value;
var textfield3 = document.getElementById("calle").value;
//Check if Values are filled
if ( !textfield1.match(/\S/) || !textfield2.match(/\S/) || !textfield3.match(/\S/))
{
//execute your script
}
I hope it helps.
use jquery .change() function
$( "#provincia" ).change(function() {
//you can do something here
alert( "Handler for .change() called." );
});

How to validate if textbox value is empty in a series of textboxes?

There are a series of textboxes like:
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
User can fill up the textbox values from top to bottom order. Only first textbox is required and all other textboxes are optional.
Allowed order to fill textbox values:
1st
1st & 2nd
1st, 2nd & 3rd
and likewise in sequence order
Dis-allowed order:
2nd
1st & 3rd
1st, 2nd & 4th
This means that user needs to fill up the first textbox only or can fill up the other textboxes in sequential order. User can NOT skip one textbox and then fillup the next one.
How to validate this in javascript/jQuery?
Any help is highly appreciated!
I would personaly use the disabled html attribute.
See this jsFiddle Demo
html
<form>
<input type="text" class="jq-textBox" required="required" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="submit" />
</form>
(Note the required attribute for HTML5)
jquery
$('input.jq-textBox').on('keyup', function(){
var next = $(this).next('input.jq-textBox');
if (next.length) {
if ($.trim($(this).val()) != '') next.removeAttr('disabled');
else {
var nextAll = $(this).nextAll('input.jq-textBox');
nextAll.attr('disabled', 'disbaled');
nextAll.val('');
}
}
})
Also see nextAll() jquery Method
Edit :
If you want to hide the disabled inputs in order to show them only when the previous input is filled, just add this css :
input[disabled] {
display: none;
}
Demo
You can iterate over the list backwards to quickly figure out whether there is a gap.
var last = false,
list = $(".jq-textBox").get().reverse();
$.each(list, function (idx) {
if ($(this).val() !== "") {
last = true;
}
else if (last) {
alert("you skipped one");
}
else if (list.length === idx + 1) {
alert("must enter 1");
}
});
http://jsfiddle.net/rnRPA/1/
Try
var flag = false, valid = true;
$('.jq-textBox').each(function(){
var value = $.trim(this.value);
if(flag && value.length !=0){
valid = false;
return false;
}
if(value.length == 0){
flag = true;
}
});
if(!valid){
console.log('invalid')
}
Demo: Fiddle
You can find all inputs that are invalid (filled in before the previous input) this way:
function invalidFields() {
return $('.jq-textBox')
.filter(function(){ return !$(this).val(); })
.next('.jq-textBox')
.filter(function(){ return $(this).val(); });
}
You can then test for validity:
if (invalidFields().length) {
// invalid
}
You can modify invalid fields:
invalidFields().addClass('invalid');
To make the first field required, just add the HTML attribute required to it.
I think a more elegant solution would be to only display the first textbox, and then reveal the second once there is some input in the first, and then so on (when they type in the second, reveal the third). You could combine this with other solutions for testing the textboxes.
To ensure the data is entered into the input elements in the correct order, you can set up a system which modifies the disabled and readonly states accordingly:
/* Disable all but the first textbox. */
$('input.jq-textBox').not(':first').prop('disabled', true);
/* Detect when the textbox content changes. */
$('body').on('blur', 'input.jq-textBox', function() {
var
$this = $(this)
;
/* If the content of the textbox has been cleared, disable this text
* box and enable the previous one. */
if (this.value === '') {
$this.prop('disabled', true);
$this.prev().prop('readonly', false);
return;
}
/* If this isn't the last text box, set it to readonly. */
if(!$this.is(':last'))
$this.prop('readonly', true);
/* Enable the next text box. */
$this.next().prop('disabled', false);
});
JSFiddle demo.
With this a user is forced to enter more than an empty string into an input field before the next input is essentially "unlocked". They can't then go back and clear the content of a previous input field as this will now be set to readonly, and can only be accessed if all following inputs are also cleared.
JS
var prevEmpty = false;
var validated = true;
$(".jq-textBox").each(function(){
if($(this).val() == ""){
prevEmpty = true;
}else if($(this).val() != "" && !prevEmpty){
console.log("nextOne");
}else{
validated = false;
return false;
}
});
if(validated)
alert("ok");
else
alert("ERROR");
FIDDLE
http://jsfiddle.net/Wdjzb/1/
Perhaps something like this:
var $all = $('.jq-textBox'),
$empty = $all.filter(function() { return 0 === $.trim(this.value).length; }),
valid = $empty.length === 0
|| $empty.length != $all.length
&& $all.index($empty.first()) + $empty.length === $all.length;
// do something depending on whether valid is true or false
Demo: http://jsfiddle.net/3UzHf/ (thanks to Arun P Johny for the starting fiddle).
That is, if the index of the first empty item plus the total number of empties adds up to the total number of items then all the empties must be at the end.
This is what you need :
http://jsfiddle.net/crew1251/jCMhx/
html:
<input type="text" class="jq-textBox" /><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/>
js:
$(document).on('keyup', '.jq-textBox:first', function () {
$input = $(this);
if ($input.val()!='')
{
$('input').prop('disabled',false);
}
else {
$('input:not(:first)').prop('disabled',true);
}
});
var checkEmpty = function ()
{
var formInvalid = false;
$('#MyForm').each(function () {
if ($(this).val() === '') {
formInvalid = true;
}
});
if (formInvalid) {
alert('One or more fields are empty. Please fill up all fields');
return false;
}
else
return true;
}

Categories