Here's the code of an Angular 4 component used to collect contact information from visitors:
.html:
<form (submit)="onCreateContact()">
<div class="form-group">
<input type="text" [(ngModel)]="contactname" name="contactname" class="form-control form-control-lg" placeholder="Name">
</div>
<div class="form-group">
<input type="email" [(ngModel)]="contactemail" name="contactemail" class="form-control form-control-lg" placeholder="Email">
</div>
<div class="form-group">
<input type="text" [(ngModel)]="contactphone" name="contactphone" class="form-control form-control-lg" placeholder="Phone">
</div>
<input type="submit" class="btn btn-outline-light btn-block" data-toggle="modal" data-target='#addContactModal'>
</form>
<!-- Modal -->
<div class="modal fade" id="addContactModal" tabindex="-1" role="dialog" aria-labelledby="addContactModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addContactModalLabel">Contact</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Thanks for contacting us! We will get in touch with you shortly.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
.ts:
onCreateContact() {
let contact = {
contactname: this.contactname,
contactemail: this.contactemail,
contactphone: this.contactphone
}
return this.http.post('api/contacts/add', contact).map(res => res.json()).subscribe(data => {
if(data.success) {
console.log(data);
} else {
console.log('Failed to add contact');
}
}
);
}
All contact fields are required; the data is not passed to the backend if not all fields are filled.
Currently, the Bootstrap modal popups every time I press the submit button, even when the data is not passed. How can I show it only when the data is actually passed to the server?
You are toggling the modal when the user clicks on the submit button.
What you need to do is, toggle the modal from component class(.ts) after getting the response from the backend.
So in your ".ts" file add below line under the imports section
declare var $: any;
Then toggle modal after receiving response from backend as below
onCreateContact() {
return this.http.post('api/contacts/add', contact).map(res => res.json()).subscribe(data => {
if(data.success) {
console.log(data);
$('#addContactModal').modal('show'); // Add this line
} else {
console.log('Failed to add contact');
$('#errorModalId').modal('show'); // If you are planning to show error modal when something goes wrong.
}
});
}
Don't forget to remove data-toggle and data-target attribute from submit button.
Hope this helps.
Related
I have this form that users have to fill. When they don't fill the form or if they don't fill it correctly, the request POST is not loading. The request post allows me to save their name and email.
I want to show a bootstrap modal when the form is filled correctly by clicking the button "Download now".
The bootstrap modal says "Congratulations." It is like a success modal to say they have correctly filled the form.
But I have an issue: when nothing is filled in the form or either when it is not filled correctly, the modal is still showing when I click the button "Download now".
How can I make my modal understand that I want it to show only when the user succeed in filling correctly the form? I want the modal to pay attention to the function formValidation() before showing when I am clicking the button "Download now".
HTML CODE:
<form name="myForm" style="width:100%;" id="submit_request_form" enctype="multipart/form-data" onsubmit="return submitClick();">
<div class="form-group">
<label>First and last name:</label>
<input type="text" class="form-control" id="id_name" name="user_name" placeholder="Enter first & last name" required>
</div>
<div class="form-group">
<label>Email address:</label>
<input type="email" id="id_email" name="user_email" class="form-control" placeholder="Enter email" required>
<small class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<button type="submit" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Download now</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="alert alert-success" role="alert">
Congratulations. You will receive an email in few minutes!
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</form>
Javascript:
<script>
function submitClick() {
if (formValidation() == true) {
//POST REQUEST
return true;
} else {
return false;
}
}
function formValidation() {
if (document.myForm.user_name.value == "") {
alert("Please fill in your Name!");
return false;
}
// Validate length of the Name LastName
else if ((document.myForm.user_name.value.length) > 50) {
alert("The name is too long!");
return false;
}
// Validate emails
else if (!/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(myForm.user_email.value)) //Regular expressions to validate email
{
alert("Enter Valid Email Address!");
return false;
}
return true;
}
</script>
You'll have to programatically show the modal instead of relying on the automatic behaviour of data-toggle="modal" data-target="#exampleModal".
Remove the data-toggle and data-target attributes on your button and add this somewhere in your submitClick function's if (formValidation() == true) branch, preferably after the POST request has completed (but that's up to you really)
$('#exampleModal').modal()
See https://getbootstrap.com/docs/4.4/components/modal/#via-javascript
I am using mbd material design angular7 template. I have a set of tasks that has an edit button each. When i click on the Edit button a modal opens up. I want this modal to have the existing values of the field. I can be done through formControlName. But it is not happening.I click on the edit button and on that click function , i assign the values before opening the edit Modal. However, they don't fill the text boxes in the modal. In console it appears before i click the modal button. Please help
app.component.ts
openEditModal(taskIdValue:number){
console.log("Task Id Value = ", taskIdValue)
for(var i = 0 ; i<this.result.length ; i++){
if(this.result[i].taskId == taskIdValue ){
console.log("this.result[i] = ", this.result[i])
localStorage.setItem('editTaskId',this.result[i].taskId);
localStorage.setItem('editTaskName',this.result[i]. taskName);
}
}
this.editTaskId = localStorage.getItem('editTaskId')
this.editTaskName = localStorage.getItem('editTaskName')
$('#editModal').click();
this.displayEdit = true;
}
editTask(){
console.log("this.result.taskId", )
}
app.component.html
<td>
<button class = "btn btn-primary waves-light"
(click)="openEditModal(data.taskId)">Edit</button>
<button type="button" id = "editModal" style =
"visibility:hidden" class="btn btn-primary waves-light" data-
toggle="modal" data-target="#EditExample"
(click)="centralLarge.show()" mdbWavesEffect>
Edit
</button>
<div mdbModal #centralLarge="mdb-modal" class="modal fade"
id="EditExample" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true"
[config]="{backdrop: true, ignoreBackdropClick: false}">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title w-100" id="myModalLabel">Edit
Data</h4>
<button type="button" class="close" data-
dismiss="modal" aria-label="Close" (click)="centralLarge.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" *ngIf = "displayEdit">
<div>
<div>
<form (ngSubmit)="editTask(editTaskForm.value)"
[formGroup]="editTaskForm">
<div class="form-group">
<label>Task Id : </label>
<input type="text" maxlength="100"
class="form-control" placeholder="Enter Task Id "
formControlName="editTaskId"
[formControl]="editTaskForm.controls['editTaskId']"
required>
</div>
<div class="form-group">
<label>Task Name : </label>
<input type="text" maxlength="1000"
class="form-control" placeholder="Enter Task Name "
formControlName='editTaskName'
[formControl]="editTaskForm.controls['editTaskName']"
required>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-
secondary btn-sm waves-light" data-dismiss="modal"
(click)="centralLarge.hide()"
mdbWavesEffect>Close</button>
<button type="submit"
[disabled]="!editTaskForm.valid" class="btn btn-primary btn-sm
waves-
light"
(click)="centralLarge.hide()"
mdbWavesEffect>Save </button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</td>
You'd better use [(ngModel)] with your object maybe, your typescript code is not clear enough with the way you build editTaskForm, so I suggest to organize the code clearly, and step by step, you will get it working.
Greetz!
you can set the previous value by using this.formGroupname.patchValue({}), For example
this.form.patchValue({ fullname1: this.fullname1, });
i have put my login form inside a bootstrap modal component.Upon entering the values inside the input fields and clicking submit, nothing happens and the modal simply closes. Inside my inspect element under the networks tab, I do not see any post request being made.
have used passport-local for authorisation and mysql as database.
Here is my html snippet
<div class="modal fade" id="login" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="login modal">Login</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="post" action="/login"></form>
<div class="modal-body">
<div class="form-group">
<label for="Email login">Email address</label>
<input type="email" name="email" class="form-control" id="Email login" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="Password login">Password</label>
<input type="password" name="password" class="form-control" id="Password login" placeholder="Password">
</div>
<div class="form-check">
<input type="checkbox" name="remember" class="form-check-input" id="remember">
<label class="form-check-label" for="exampleCheck1">Remember Me</label>
</div>
<!-- <button type="submit" class="btn btn-primary">Submit</button> -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success" data-dismiss="modal">Submit</button>
</div>
</form>
</div>
</div>
</div>
and here is the route.js code
route.get('/login', (req, res) => {
res.render('login')
})
route.post(
'/login',
passport.authenticate('local', {
successRedirect: '../chat',
failureRedirect: '/',
failureFlash: false,
badRequestMessage: 'Please enter your account credentials to login.'
}),
function(req, res) {
console.log(req.param('remember'));
if(req.isAuthenticated(req, res)) {
res.redirect('../chat');
} else {
var errors = req.flash('error');
if(errors) {
assign['errors'] = errors;
}
res.render('index.html', {errors: errors});
}
}
);
here chat is the folder in my parent directory where i want to redirect the user after a successful login.
Please look into this as soon as possible.I have been trying to debug this since about 40 days.I know it could be a minor syntax error which has croosed my mind.
Thank you
just remove ( data-dismiss="modal" ) from submit button, data-dismiss is closing your popup before execution.
just remove the closing form tag here:
<form method="post" action="/login"></form>
I've a Bootstrap modal for changing a user's password. The problem, however, is that no matter what I try I cannot get the event to fire, be it via onclick or by attaching the button to an event using .on. It simply will not recognise it.
I've tried putting the <script> tags above the modal, below the modal, and even inside the modal, only to always have onclick return Uncaught ReferenceError: updatePassword is not defined. I then removed the onclick, assigned an ID to the submit button, and tried $('#update-password').on('click', function() { ... }); but this wasn't recognised at all.
The culprit in all of this is almost definitely the Bootstrap modal, and I'm guessing it's got something to do with how the browser handles it upon page load.
--
Modal
<!-- Modal -->
<div class="modal fade" id="changePasswordModal" tabindex="-1" role="dialog" aria-labelledby="changePassModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="changePassModalLabel">Change Password</h4>
</div>
<div class="modal-body">
<div class="col-md-12">
<div class="alert alert-password" style="display: none;">
<p></p>
</div>
</div>
<form role="form" action="#" method="post">
<div class="form-group">
<label for="password-current">Current Password<span>*</span></label>
<input type="password" class="form-control" id="password-current" name="pass-curr" placeholder="Current password...">
</div>
<hr>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="password-new">New Password<span>*</span></label>
<input type="password" class="form-control" id="password-new" name="pass-new" placeholder="New password...">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="password-new-conf">Confirm New Password<span>*</span></label>
<input type="password" class="form-control" id="password-new-conf" name="pass-new-c" placeholder="Confirm new password...">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="updatePassword()">Update Password</button>
</div>
</div>
</div>
</div>
Script
<script>
function updatePassword(){
console.log('foo');
/*$.ajax({
url: url+"ajax/update_password",
data: {pass-curr : pass-curr, pass-new : pass-new, pass-new-c : pass-new-c},
async: false,
success: function(data) {
},
error: function(data) {
$('#alert-password').removeClass('alert-success').addClass('alert-danger').html('<p><strong>Sorry, an error occurred!</strong></p><p>'+data.additional+'</p>').slideDown(200, function() {
$('#alert-password').delay(4000).slideUp(200);
});
}
})*/
};
</script>
My apologies if this has been asked before. The only questions I could seem to find were those asking how to launch a modal through onclick.
The problem is that your event is not getting binded with button
Please find the JSFIDDLE here
In your HTML - do the following in the script tag
<head>
<script>
function updatePassword(){
console.log('updatePassword');
}
$(document).ready(function(){
// $('.btn-primary').on('click',function(){ - This too works
// console.log('foo');
//});
$('.btn-primary').on('click',updatePassword);
});
</script>
</head>
I am trying to point my scripts to two different buttons in my html. The scripts both send an email of what the customer entered however both belong to two separate modal forms.
The first form is:
!-- Beginning of Pop-up Device Form -->
<div class="btn-buy hover-effect" data-toggle="modal" data-target="#modal-1"></div>
<div class="modal fade" id="modal-1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">SpryMobile Device Testing</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<form id="emailForm">
<h4>Name</h4>
<p><input name="contactName" id="contactName" class="form-control" type="text" /></p>
</div>
<div class="col-md-6">
<h4>Email Address</h4>
<p><input class="form-control" required name="contactEmail" id="contactEmail" type="email" /></p>
</div>
<div class="col-md-12">
<h4>Tell us about your operation</h4>
<input type="hidden" value="Device and Meter Testing" id="contactType"/>
<textarea rows="7" cols="20" class="form-control" name="contactMessage" id="contactMessage"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn-u btn-u-default" data-dismiss="modal">Close</button>
<input type="submit" value="Send Message" class="btn-u" id="contactSubmit" name="contactSubmit"> <i id="contactSpinner" class="icon-spinner icon-spin" style="display:none;"></i></button>
<br>
<div class="alert alert-success" id="messageSuccess" style="display:none;">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Thank you!</strong> We appreciate your comments, and will get back to you soon.
</div>
<br>
<div class="alert alert-danger" id="messageError" style="display:none; padding-bottom:35px;">
<button class="close" data-dismiss="alert">x</button>
<div style="float:left;"><strong>Sorry.</strong> There was a problem with the server.</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- End of pop-up -->
The script that I have associated with this modal form is:
<script type="text/javascript">
$(document).ready(function() {
$('#emailForm').on('submit', function(event) {
event.preventDefault();
if( ! $("form")[0].checkValidity() ) {
return false;
}
// Disable the submit button
$('#contactSubmit').attr("disabled", "disabled");
$('#contactSpinner').css('display', 'inline-block');
$.ajax({
type : "POST", cache: false,
url : "#controllers.routes.Application.contactSend()",
data : {
contactName: $("#contactName").val(),
contactEmail: $("#contactEmail").val(),
contactMessage: encodeURIComponent( $("#contactMessage").val() ),
contactType: $("#contactType").val()
},
success : function(msg) {
// Check to see if the mail was successfully sent
if (msg == 'OK_SO_UPDATE') {
$("#messageSuccess").css("display", "block");
}
},
error : function(ob, errStr) {
$("#messageError").css("display", "block");
$("#messageError span.message").text(ob.responseText);
},
complete: function() {
$('#contactSubmit').removeAttr("disabled");
$('#contactSpinner').css('display', 'none');
}
});
return false;
});
});
</script>
This is referencing the scripts by giving the my form an id of "emailForm". However, if I wanted to add a second modal form such as:
<!-- Beginning of Pop-up Professional Form -->
<div class="btn-buy hover-effect" data-toggle="modal" data-target="#modal-2"></div>
<div class="modal fade" id="modal-2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">SpryMobile Professional</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<form id="emailForm">
<h4>Name</h4>
<p><input name="contactName" id="contactName" class="form-control" type="text" /></p>
</div>
<div class="col-md-6">
<h4>Email Address</h4>
<p><input class="form-control" required name="contactEmail" id="contactEmail" type="email" /></p>
</div>
<div class="col-md-12">
<h4>Tell us about your operation</h4>
<input type="hidden" value="Professional" id="contactType"/>
<textarea rows="7" cols="20" class="form-control" name="contactMessage" id="contactMessage"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn-u btn-u-default" data-dismiss="modal">Close</button>
<input type="submit" value="Send Message" class="btn-u" id="contactSubmit" name="contactSubmit"> <i id="contactSpinner" class="icon-spinner icon-spin" style="display:none;"></i></button>
<br>
<div class="alert alert-success" id="messageSuccess" style="display:none;">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Thank you!</strong> We appreciate your comments, and will get back to you soon.
</div>
<br>
<div class="alert alert-danger" id="messageError" style="display:none; padding-bottom:35px;">
<button class="close" data-dismiss="alert">x</button>
<div style="float:left;"><strong>Sorry.</strong> There was a problem with the server.</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- End of pop-up -->
This references the same script since I gave this form the id of emailForm as well. However, for some reason the alerts that are suppose to appear for the second form are not showing up. Any idea what this could be? Will I need to create a unique script for each form?
Duplicate ID's violate the specifications and are problematic, but here's a way around that to temporarily repair this code.
$(event.target).find("#messageError").css("display", "block");
The FORM tag is also malformed. I moved it up to match the bottom form tag (to after the fourth DIV).
(There are many duplicate ID problems yet unresolved, but the above specifies to the program within the event listener which element to reveal.)
The solution is to use class and name attributes where appropriate.
JSFiddle: http://jsfiddle.net/BloodyKnuckles/s7D98/