display one of two forms if button is clicked - javascript

I am in need of some help. I want to create a web page that has two buttons depending on which button is selected I want to display either form 1 or form 2. The next thing is if the user selects the button for form 1 I want to do form validation only for the selected form.
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<button type="button" class="btn btn-outline-primary">show form 1</button>
<button type="button" class="btn btn-outline-primary">show form 2</button>
<br>
<form id="form1" class="needs-validation" novalidate>
<hr>
<p>THIS IS FORM 1</p>
<hr>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">form1 box 1</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="form1 box 1" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom02">form1 box 2</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="form1 box 2" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form1</button>
</form>
<br>
<form id="form2" class="needs-validation" novalidate>
<hr>
<p>THIS IS FORM 2</p>
<hr>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">form2 box 1</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="form1 box 1" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom02">form2 box 2</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="form1 box 2" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form2</button>
</form>

See if it fits your requirements.
I just added an event to the buttons that just flips the display property of the two forms.
For the validation, only the displayed form is validated, but once you validate a form it remains validated.
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
function toggle(i) {
let form1 = document.getElementById('form1');
let form2 = document.getElementById('form2');
if (i == 1) {
form1.style.display = 'none';
form2.style.display = 'block';
} else {
form1.style.display = 'block';
form2.style.display = 'none';
}
}
.row {
background: #f8f9fa;
margin-top: 20px;
}
.col {
border: solid 1px #6c757d;
padding: 10px;
}
<button type="button" id="btn1" class="btn btn-outline-primary" onclick="toggle(2)">show form 1</button>
<button type="button" class="btn btn-outline-primary" onclick="toggle(1)">show form 2</button>
<br><br>
<form id="form1" class="needs-validation" novalidate>
<hr>
<p>THIS IS FORM 1</p>
<hr>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">form1 box 1</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="form1 box 1" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom02">form1 box 2</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="form1 box 2" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form1</button>
</form>
<form id="form2" class="needs-validation" style="display:none" novalidate>
<hr>
<p>THIS IS FORM 2</p>
<hr>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">form2 box 1</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="form1 box 1" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom02">form2 box 2</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="form1 box 2" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form2</button>
</form>
For this kind of things i recommend you to use some framework by the way, something like vuejs, or also jquery for simple things.

Related

How to show value after submit button in angular?

I made a form in Angular where, when user submit a form - new value show be shown under the form, I tried everything as per my knowledge but nothing works, currently labels of below form is showing without click, I need to show everything once where clicked submit button!
My interface:
HTML FILE
<div class="form-field col-lg-12">
<input class="submit-btn" type="submit" value="click" (click)="update">
</div>
<div class="form-field col-lg-12">
<input class="submit-btn" type="submit" value="click" (click)="update">
</div>
<div *ngIf="display">
<section class="admin-form">
<form class="contact-form row">
<div class="form-field col-lg-6" >
<label class="label" for="name">Article ID</label>
<label class="label infolabel" for="name">Fc409702-683e-11eb-Bc5e-54ee750463ec</label>
</div>
<div class="form-field col-lg-6 ">
<label class="label" for="company">Title</label>
<label class="label infolabel" for="company">SKF India Logs Nearly 2-Fold Rise In Q3 Net Profit</label>
</div>
<div class="form-field col-lg-6">
<label class="label" for="message">Publication, Edition</label>
<label class="label infolabel" for="message">Times Of India, Mumbai</label>
</div>
<input class="submit-btn" type="button" value="Delete" data-toggle="modal" data-target="#popup1">
</div>
</form>
</section>
</div>
TS FIle
export class MainComponent implements OnInit {
constructor() { }
display = true;
ngOnInit(): void {
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
}
update(){
this.display = !this.display;
}
}
On (click) you call update which I'm guessing is a function in your .ts.
If so, your .ts file can have something like this:
display: boolean = false;
/*...*/
update() {
...
this.display = true;
...
}
Then you *ngIf=display will trigger and show whatever is contained within
In the click handler, update should have (), like so:
<div class="form-field col-lg-12">
<input class="submit-btn" type="submit" value="click" (click)="update()">
</div>
<div class="form-field col-lg-12">
<input class="submit-btn" type="submit" value="click" (click)="update()">
</div>

How to get values from input boxes and save to database with button click angular

I'm still learning to programme on AngularJS.
I want to get values from the input box and then click on the button I want to save them in the database.
My database table is called "user". I have columns like id, username, password, name.
I have two checkbox.When I click on first checkbox(Edit) it displaying "div myVar",when i click on second checkbox(Add new user) it displaying "div myVar1".
I want to activate this button "Add" to add input box values to database MySQL. Please help me.
I have this html code:
<label><input type="checkbox" ng-model="myVar">Edit</label>
<label><input type="checkbox" ng-model="myVar1">Add new user</label>
<div ng-show="myVar">
<div class="form">
<form ng-submit="saveItem(userForm.$valid)" name="userForm">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="database_address">User</label>
<input type="text" class="form-control" required ng-model="activeItem.username" placeholder="Потребителско Име..." />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="text" class="form-control" required id="password" ng-model="activeItem.password" />
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="username">Operator</label>
<input type="text" class="form-control" required id="username" ng-model="activeItem.name" />
</div>
</div>
</div>
<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Save</button>
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form><form ng-submit="createUser(userForm.$valid)" name="userForm1">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="database_address">User</label>
<input type="text" class="form-control1" ng-model="usernamee" placeholder="Потребителско Име..." />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="text" class="form-control1" ng-model="passwordd"required id="password" />
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="username">Operator</label>
<input type="text" class="form-control1" ng-model="namee" required id="username" />
</div>
</div>
</div>
<button class="btn btn-primary" ng-click="createUser();" type="submit">Add user</button>
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form>
And Angular code:
$scope.createUser=function()
{
//console.log($scope.activeItem);
//delete $scope.activeItem.hash_method
var objectToSave = {
username: $scope.usernamee,
password: $scope.passwordd,
name: $scope.namee,
id: $scope.id
};
{
defaultAdapter.query('INSERT INTO users(username,password,name,id) VALUES(username = :usernamee, password = :passwordd,name = :namee WHERE id =:id)',
{ replacements: objectToSave, type: Sequelize.QueryTypes.UPDATE }
).then(projects => {
console.log(projects);
$scope.editMode = false;
$scope.activeItem = false;
$scope.refresh();
});
}
}

Check if an input is empty in form

i have a dynamic form so i have no idea which kind of input there will be every time and i need to handle that, so i've done something like this
<div id="repond-questionnaire" class="modal fade in" style="display: block;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Questionnaire de Test</h4>
</div>
<div class="modal-body" id="questionnaire_here">
<form method="post" id="questionnaire_form">
<div class="form-group">
<label for="text"><h3>Who are you?</h3></label>
<textarea type="text" name="80" class="form-control" rows="3" placeholder="Text..." required="" value=""></textarea>
</div>
<div class="form-group">
<label for="focusedInput"><h3>How old are you?</h3></label>
<input type="number" name="81" class="form-control" placeholder="Number..." required="" value="">
</div>
<div class="form-group">
<label for="focusedInput"><h3>What is your email?</h3></label>
<input type="email" name="82" class="form-control" placeholder="Email..." required="" value="">
</div>
<div class="form-group">
<label for="focusedInput"><h3>Do you like our website?</h3></label>
<div class="radio">
<label class="input-lg"><input type="radio" name="83" value="Oui">Oui</label>
</div>
<div class="radio">
<label class="input-lg"><input type="radio" name="83" value="Non">Non</label>
</div>
</div>
<input type="submit" name="sumbit" id="sumbit" value="Sumbit" class="btn btn-success"></form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="close" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#repond-questionnaire').on('click', '#sumbit', function() {
// here i need to check if all inputs are empty or not
//check if they have a valid input or not for security
//because after i will send everything and upload them to the data base
$.ajax({
url: "user/sumbit_answers.php",
method: "POST",
data: $('#questionnaire_form').serialize(),
beforeSend: function() {
$('#sumbit').val("Sumbiting...");
},
success: function(data) {
$('#questionnaire_form')[0].reset();
if (data == 'exit_failure') {
alert("something wrong happened");
} else {
$('#questionnaire_here').empty();
$('#questionnaire_here').html(data);
}
}
});
});
$('#repond-questionnaire').on('click', '#close', function(event) {
$('#questionnaire_here').empty();
});
});
</script>
and i'm obliged to do this because somehow the events of the form are blocked ( even though i'm not using event.preventdefault(), my form input are all like this
<input type='$type' name='$row[cid]' class='form-control' placeholder='$type...' required value=''>
Given that required attribute is already set at <input> elements within <form>, you can use .checkValidity() of <form> element.
Additionally you can include pattern attribute with RegExp [^\s]+ to require at least a single character at <input> elements. Adjust RegExp to meet requirement.
<form name="form">
<input name="input1" type="text" pattern="[^\s]+" required>
<input name="input2" type="text" pattern="[^\s]+" required>
<input type="submit">
</form>
<script>
document.forms.form.querySelector("[type=submit]")
.onclick = function() {
console.log(this.form.checkValidity());
// if (this.form.checkValidity()) { /* all <input> elements have `.value */ }
// else { /* all <input> elements do not have `.value */ }
}
</script>
var text_input=$("[type=text]");
var password_input=$("[type=password");
var radio_input=$("[type=radio]");
var checkbox_input=$("[type=checkbox]");
var select=$("<select>");
var textarea=$("<textarea>");
Then you have to do for loop for each one to check and apply your validation according to that field
Call ajax after validation (the following link will help you)
jQuery Form Validation before Ajax submit

Second Time Checkbox Not Working

I have created a two javascript.
1.When i click the checkbox the input field is appeared and when i unchecked input field is disappeared.
2.Second is when i click the add more items the all fields are created one more time.
Now the problem is when is created a second and more items the checkbox is not working.
HTML Code:
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12">
<div data-role="dynamic-fields">
<div class="form-inline">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<input type="text" class="form-control" id="Name1" placeholder="Food Name" name="Name1" style="width:120%;" required data-rule-minlength="2">
<label class="sr-only" for="field-name">Name</label>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<input type="text" class="form-control" id="field-value" placeholder="Description" style="width:120%;" required>
<label class="sr-only" for="field-value">Description</label>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<select id="select1" name="select1" style="width:130%;" class="form-control" required>
<option value=""></option>
<option value="1">Food Type 1</option>
<option value="2">Food Type 2</option>
<select>
<label for="select1">Food Type</label>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" value="" class="form-control" data-role="tagsinput" placeholder="Tags" />
<label class="sr-only" for="field-tags">Tags</label>
</div>
</div>
</div>
<div class="row">
<div class="form-inline">
<div class="col-md-3">
<div class="form-group">
<input type="text" class="form-control" id="Name1" placeholder="Price" name="price" style="width:120%;" required data-rule-minlength="2">
<label class="sr-only" for="field-name">Price</label>
</div>
</div>
<div class="col-md-2">
<div class="checkbox checkbox-styled">
<label><em>Half Plate Price</em>
<input type="checkbox" value="" id="trigger2" name="question"> </label>
</div>
</div>
<div class="col-md-1">
<div id="hidden_fields2">
<input type="text" id="hidden_field2" name="hidden" placeholder="Price" class="form-control" style="width:140%;margin-left:-35px;height: 29px;margin-top: 24px;font-weight: 380;font-size: 16px;line-height: 1.5;"> </div>
</div>
<div class="col-md-3">
<div class="checkbox checkbox-styled">
<label><em>Quarter Plate Price</em>
<input type="checkbox" value="" id="trigger" name="question"> </label>
</div>
</div>
<div class="col-md-1">
<div id="hidden_fields">
<input type="text" id="hidden_field" name="hidden" placeholder="Price" class="form-control" style="width:140%;margin-left:-100px;height: 29px;margin-top: 24px;font-weight: 380;font-size: 16px;line-height: 1.5;"> </div>
</div>
</div>
</div>
<button class="btn btn-icon-toggle btn-delete" data-toggle="tooltip" data-placement="bottom" title="Delete Field" data-role="remove"> <span class="md md-delete"></span> </button>
<button class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Add More Field" data-role="add"> Add More Items </button>
</div>
<!-- /div.form-inline -->
</div>
<!-- /div[data-role="dynamic-fields"] -->
</div>
<!-- /div.col-md-12 -->
</div>
<div class="form-group">
<button type="button" name="submit" href="#" class="btn ink-reaction btn-raised btn-primary">Submit Items</button>
</div>
<!--end .form-group -->
</div>
Checkbox Js:
<script type="text/javascript">
$(function() {
// Get the form fields and hidden div
var checkbox = $("#trigger");
var hidden = $("#hidden_fields");
hidden.hide();
checkbox.change(function() {
if (checkbox.is(':checked')) {
// Show the hidden fields.
hidden.show();
} else {
// Make sure that the hidden fields are indeed
// hidden.
hidden.hide();
$("#hidden_field").val("");
}
});
});
$(function() {
var checkbox = $("#trigger2");
var hidden = $("#hidden_fields2");
hidden.hide();
checkbox.change(function() {
if (checkbox.is(':checked')) {
// Show the hidden fields.
hidden.show();
} else {
hidden.hide();
$("#hidden_field2").val("");
}
});
});
</script>
Add more items JS:
$(function() {
// Remove button
$(document).on('click', '[data-role="dynamic-fields"] > .form-inline [data-role="remove"]', function(e) {
e.preventDefault();
$(this).closest('.form-inline').remove();
});
// Add button
$(document).on('click', '[data-role="dynamic-fields"] > .form-inline [data-role="add"]', function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-inline:first-child').clone();
new_field_group.find('input').each(function() {
$(this).val('');
});
container.append(new_field_group);
});
});
page Screenshot:
There are a couple of problems here:
You are cloning elements and then trying to access them via the same ID (you should use class)
Your functions don't target just clicked element but any element with the selector.
You are cloning elements so you need bind the click event to a non-cloned element: e.g. via $(document).on
I've updated some of your code to demonstrate what I'm talking about. In the html, I've added classes in the trigger2 and hidden_fields2 elements and display:none style to the hidden fields so they are hidden by default.:
<div class="col-md-2">
<div class="checkbox checkbox-styled">
<label><em>Half Plate Price</em>
<input type="checkbox" value="" class="trigger2" id="trigger2" name="question"> </label>
</div>
</div>
<div class="col-md-1">
<div id="hidden_fields2" class="hidden_fields2" style="display:none;">
<input type="text" id="hidden_field2" name="hidden" placeholder="Price" class="form-control" style="width:140%;margin-left:-35px;height: 29px;margin-top: 24px;font-weight: 380;font-size: 16px;line-height: 1.5;"> </div>
</div>
In the javascript, I've changed the function to run from a $(document).on event bind and used the element class instead of the id. I've also changed the code so it only effects the checkbox you change and the closest hidden elements:
$(function() {
$(document).on('change', '.trigger2', function(){
var checkbox = $(this);
var parent = checkbox.closest('.form-inline');
var hidden = parent.find(".hidden_fields2");
hidden.hide();
if (checkbox.is(':checked')) {
// Show the hidden fields.
hidden.show();
} else {
hidden.hide();
$(".hidden_field2").val("");
}
});
});
You need to use the same logic on your other functions and inputs.

Email validation for specific domain name

I have the following form. I want to validate the email field .it should only contain for domain name "#somename.com " when the user clicks submit.
The mail should only be validated when the check box is clicked to show the email field.
If the email is invalid i want to prevent submission
<form class="form-horizontal" id="rForm" data-toggle="validator" role="form">
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<label class="checkbox-inline col-xs-10">
<input type="checkbox" ID="chkbx"> Email
</label>
</div>
</div>
<div class="form-group email">
<div class="col-xs-offset-3 col-xs-8">
<div class="col-xs-8">
<input type="text" class="form-control " placeholder="Enter email">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<input type="reset" class="btn btn-default" id="rset" value="Reset">
<input type="submit" class="btn btn-primary" id="submit" value="Submit">
</div>
</div>
</form>
JS
$("#submit").on('keypress click', function(e){
e.preventDefault();
$('#chkbx').hide();
$('#chkbx').click(function () {
// This will show / hide your element accordingly
$('.email').toggle();
});
});
Checkout JavaScript RegEx to determine the email's domain (yahoo.com for example). You can use that and augment your example:
$('#chkbx').click(function() {
// This will show / hide your element accordingly
$('.email').toggle();
});
$("#submit").on('click', function(e) {
e.preventDefault();
if ($('#chkbx').is(':checked')) {
// https://stackoverflow.com/questions/3270185/javascript-regex-to-determine-the-emails-domain-yahoo-com-for-example
console.log(/#testdomain.com\s*$/.test($('#email_input').val()));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal" id="rForm" data-toggle="validator" role="form">
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<label class="checkbox-inline col-xs-10">
<input type="checkbox" ID="chkbx" checked>Email
</label>
</div>
</div>
<div class="form-group email">
<div class="col-xs-offset-3 col-xs-8">
<div class="col-xs-8">
<input id="email_input" type="text" class="form-control " placeholder="Enter email">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<input type="reset" class="btn btn-default" id="rset" value="Reset">
<input type="submit" class="btn btn-primary" id="submit" value="Submit">
</div>
</div>
</form>
Use the following function to test for your email.
EDIT:
You first need to add a name= and id= to your email input field.... So what you want to do is:
<input type="text" class="form-control " placeholder="Enter email" name="email" id="email">
and then do:
function testEmail(string) {
var regex = /.+#somename.com$/i;
return regex.test(string);
}
//testEmail("nope#test.com"); // false
//testEmail("what#somename.com.other"); //false
//testEmail("yeah#somename.com"); //true
//testEmail("#somename.com"); // false
$('form').submit(function(e){
var values = $('form').serialize();
if(!testEmail(values.email))
e.preventDefault();
// your submission code goes here.
})

Categories

Resources