Validate input fields on bootstrap modal window button clicks using angular - javascript

I am trying to validate input fields on submit/ok button click in a modal window using angularjs framework. What I have tried are to add the attributes required/ng-required on my input button. But on my ok button click the input text field is not validated and the modal window is dismissed. As below is my modal-body. I would like to see the angular behaviour of showing the red border around it on click of ok.
<div class="modal-body">
<input type="text" class="input-box" size="10" required ng-model="data.myNumber"/>
</div>
Is there something additional I need to do in my event handler for submit buttons? Below is a plunker I created for the demo. Any help would be highly appreciated.
http://plnkr.co/edit/ACoTQgIVnWnR92LngT89?p=preview
By the way the plunker will run only in firefox.

First you'll need to use the correct elements and corresponding classnames. You'll need to wrap your input in a div with classname form-group, and that needs to be wrapped into a form element. The actual input needs to have the form-control class:
<form>
<div class="form-group">
<input type="text" class="form-control" size="10" ng-model="data.myNumber" required/>
</div>
</form>
A nice read on properly using forms with bootstrap can be found here:
http://getbootstrap.com/css/#forms
Now that it's a proper bootstrap form you can add angular validation. That's very simple just by giving the form and the input a name attribute:
<form name="modalForm">
<div class="form-group">
<input name="modalInput" type="text" class="form-control" size="10" ng-model="data.myNumber" required/>
</div>
</form>
Now angular will preform validation in the background. It will add modalForm to the scope of your modalcontroller from where you can get the state of the form and it's input elements.
Now because of the required attribute the input and form has been deemed invalid which can be checked by using: modalForm.modalInput.$invalid That will return true, when the input is empty . You can use it to add the has-error class to the form-group div element which will turn the border of the input element to red. You can dynamicly add this class by using the ng-class directive:
<div class="form-group" ng-class="{ 'has-error': modalForm.modalInput.$invalid }" >
<input name="modalInput" type="text" class="form-control" size="10" ng-model="data.myNumber" required/>
</div>
</form>
You can also add a message which also will be colored through the has-error class. Add a span element with the help-block class and use the ng-show directive to toggle it on the required error:
<div class="form-group" ng-class="{ 'has-error': modalForm.modalInput.$invalid }" >
<input name="modalInput" type="text" class="form-control" size="10" ng-model="data.myNumber" required/>
<span ng-show="modalForm.modalInput.$error.required" class="help-block">Input is required.</span>
</div>
</form>
Now if you want to make it impossible to push the ok button when the form is invalid you can toggle the disabled class and/or add use the ng-disabled directive:
<button class="btn btn-primary" ng-disabled="modalForm.$invalid" ng-class="{ 'disabled': modalForm.$invalid }" ng-click="ok()">OK</button>
I recommend reading the previous link on bootstrap forms and the following guide for using angular's forms. It has good examples:
https://docs.angularjs.org/guide/forms
Here's the complete modal code and a working example on Plunker:
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">My Modal</h3>
</div>
<form name="modalForm">
<div class="modal-body">
<div class="form-group" ng-class="{ 'has-error': modalForm.modalInput.$invalid }" >
<input name="modalInput" type="text" class="form-control" size="10" ng-model="data.myNumber" required/>
<span ng-show="modalForm.modalInput.$error.required" class="help-block">Input is required.</span>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-disabled="modalForm.$invalid" ng-class="{ 'disabled': modalForm.$invalid }" ng-click="ok()">OK</button>
<button class="btn btn-primary" ng-click="cancel()">Cancel</button>
</div>
</form>
</div>
http://plnkr.co/edit/GUE3sGci478obwOrzhNw?p=preview
PS: i know it doesn't answer you question as to how to preform input validation on button click but that's because it's not "the angular way" of using forms. The above and the links i provide should give you a good idea on how to properly use validation within Angular. Hope it helps, good luck.

Here are the main directions to get what you want:
Wrap your input in a <form> element.
In the ok() function, close modal only if it's valid
I also replaced type="text" with type="number", since you want the user to input a number. Also corrected the plunker to make it work:
ModalInstanceController
app.controller('ModalInstanceCtrl', function($scope, $modalInstance){
$scope.ok = function () {
if ($scope.numberForm.$valid) {
$modalInstance.close();
}
};
// ...
}
HTML
<form name="numberForm">
<div class="form-group">
<input type="number" class="form-control input-box" required ng-model="data.myNumber"/>
</div>
<button class="btn btn-primary" ng-click="ok()" >OK</button>
<button class="btn btn-primary" ng-click="cancel()">Cancel</button>
</form>
See plunker
Improvement: Play with angular validation to add red borders if input is invalid:
<form name="numberForm">
<div class="form-group" ng-class="{ 'has-error' : numberForm.myNum.$invalid }">
<input type="number" name="myNum" class="form-control input-box" required ng-model="data.myNumber"/>
</div>
<button class="btn btn-primary" ng-click="ok()" ng-disabled="numberForm.$invalid">OK</button>
<button class="btn btn-primary" ng-click="cancel()">Cancel</button>
</form>
See forked plunker

Related

I want to preview HTML form data in pop window before submit. How to do that using JavaScript?

Following is my HTML Code having two buttons, Preview and Submit. I want to pop a window showing form preview when click on Preview and then submit the form when I click on Submit.
<form action="">
<div class="search-form">
<div class="form-header">
<h4>Post a New Job</h4>
</div>
<label for="job_title">Job Title</label>
<input type="text" name="job_title" id="job_title" placeholder="Hiring for which position">
<label for="company">Company Name</label>
<input type="text" name="company" id="company" placeholder="Name of the hiring organization">
<label for="experience-required">Total Experience Required</label>
<div class="input-range">
<input type="number" min="0" max="50" name="experience-required-min" id="experience-required-min"
placeholder="Min in Years">
<span>To</span>
<input type="number" min="0" max="50" name="experience-required-max" id="experience-required-max"
placeholder="Max in Years">
</div>
<label for="salary-range">Salary Range</label>
<div class="input-range">
<input type="number" min="0" max="50" name="salary-range-min" id="salary-range-min"
placeholder="Min in Lpa">
<span>To</span>
<input type="number" min="0" max="50" name="salary-range-max" id="salary-range-max"
placeholder="Min in Lpa">
</div>
</div>
<label for="job-desciption">Job Description</label>
<textarea name="job-desciption" class="input-range" placeholder="Enter Job Desciption"
style="height: 100px"></textarea>
</div>
<br>
<a href="" <button class="btn btn-lg btn-warning" type="submit" name="search">Post</button>
</a>
<a href="" <button class="btn btn-lg btn-warning" type="submit" name="search">Preview</button>
</a>
</form>
You can do this using modals , you can use Bootstrap or Materialize css I'll link them below.
Bootstrap
https://getbootstrap.com/docs/5.1/components/modal/
materialize
https://materializecss.com/modals.html#!
After you implement a modal in your app you can easily use it's buttons to submit your form or cancel.
please let me know if this hepled
First, the preview button type should be button and not submit. Button with type as submit causes the form to submit. Also, do not wrap the button within the <a> anchor tag. That is unnecessary.
<!-- Note the use of type="button" -->
<button class="btn btn-lg btn-warning" type="button" name="search">Preview</button>
Second, you will need a JavaScript code to handle click handler. You can do something like this:
// Get reference to the preview button
const previewButton = document.querySelector('.search-form button[type="button"]');
previewButton.addEventListener('click', () => {
// Step 1: Read form data here using DOM APIs
// Step 2: Open preview using some modal dialog.
window.alert(/* Show form data */);
// Or use some other bootstrap or equivalent library dialog box.
});
There are many ways to write the JavaScript. Choose one that works best for you.

Clicking a button will put a value at input field without reloading the page

I just want to ask on how to put a value in an input field without reloading the page. Heres my code. What i want to happen is that when i click the button, "1234567" will automatically be inside or value of the input fields but without refreshing the page. This how my code is but nothing is happening. Thank you in advance!
This is for my input fields
<div class="form-group">
<label for="password">{{ $edit ? trans("app.new_password") : trans('app.password') }} <text class="text-danger">*</label>
<input type="password" class="form-control" id="password" name="password" #if ($edit) placeholder="#lang('app.leave_blank_if_you_dont_want_to_change')" #endif>
</div>
<div class="form-group">
<label for="password_confirmation">{{ $edit ? trans("app.confirm_new_password") : trans('app.confirm_password') }} <text class="text-danger">*</label>
<input type="password" class="form-control" id="password_confirmation" name="password_confirmation" #if ($edit) placeholder="#lang('app.leave_blank_if_you_dont_want_to_change')" #endif>
</div>
Then this for my button that when click it will trigger the event
<input type="button" class="btn btn-warning btn-sm btn-block" id="default_pass" onclick="myFunction()">
<i class="glyphicon glyphicon-filter"></i> Default Pass
</input>
Then this is the javascript
<script type="text/javascript">
$(document).on('click', 'default_pass', function myFunction() {
document.getElementById("password").value = "1234567";
document.getElementById("password_confirmation").value = "1234567";
});
</script>
PS Im really no good at javascript. Thanks for the help!
The problem is that your HTML is invalid. <input> isn't a container, so Default Pass is not inside it. Clicking on that doesn't trigger a click on the button.
You should use <button> instead.
And in the jQuery you need to use #default_pass as the selector. You don't need the onclick attribute in the button, since you're using jQuery to bind the event handler. You never defined the function as a global name; using function myFunction() in the jQuery event handler only defines the name in the local scope of the function; see Why JavaScript function declaration (and expression)?
$(document).on('click', '#default_pass', function myFunction() {
$("#password, #password_confirmation").val("1234567");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="password">Password <text class="text-danger">*</label>
<input type="password" class="form-control" id="password" name="password" #if ($edit) placeholder="Leave blank if you don't want to change" #endif>
</div>
<div class="form-group">
<label for="password_confirmation">Confirm Password <text class="text-danger">*</label>
<input type="password" class="form-control" id="password_confirmation" name="password_confirmation" #if ($edit) placeholder="Leave blank if you don't want to change" #endif>
</div>
<button type="button" class="btn btn-warning btn-sm btn-block" id="default_pass" >
<i class="glyphicon glyphicon-filter"></i>
Default Pass
</button>

Can't simulate click on submit button via javascript

I'm having problems simulating a click via javascript on a mailchimp pop-up subscribe form and i need your help.
<!-- Title & Description - Holds HTML from CK editor -->
<div class="content__titleDescription" data-dojo-attach-point="descriptionContainer"><strong>Unlock the content </strong>by subscribing to our page.</div>
<!-- Form Fields -->
<form action="//mc.us7.list-manage.com/subscribe/form-post?u=bcd9828fa83ea7a231ffbee26&id=1928481ac4" accept-charset="UTF-8" method="post" enctype="multipart/form-data" data-dojo-attach-point="formNode" novalidate="">
<div class="content__formFields" data-dojo-attach-point="formFieldsContainer">
<div class="field-wrapper" id="uniqName_3_0" widgetid="uniqName_3_0">
<label for="mc-EMAIL">Email Address</label>
<input type="text" name="EMAIL" value="" id="mc-EMAIL" class="invalid">
<div class="invalid-error" style="display: block;">This field is required.</div>
</div>
<div class="field-wrapper" id="uniqName_3_1" widgetid="uniqName_3_1">
<label for="mc-FNAME">First Name</label>
<input type="text" name="FNAME" value="" id="mc-FNAME" class="valid">
<div class="invalid-error" style="display: none;"></div>
</div>
<div style="position:absolute;left:-5000px;">
<input type="text" name="b_bcd9828fa83ea7a231ffbee26_1928481ac4" tabindex="-1" value="">
</div>
</div>
<div class="content__button">
<input class="button" type="submit" value="Subscribe" data-dojo-attach-point="submitButton">
</div>
</form>
<!-- Footer - Holds HTML from CK editor -->
<div class="content__footer" data-dojo-attach-point="footerContainer"></div>
</div>
<div class="modalContent__image" data-dojo-attach-point="formImageContainer"></div>
The code that i'm trying to target is:
<input class="button" type="submit" value="Subscribe" data-dojo-attach-point="submitButton">
It's the submit button "Subscribe" that you can also see in
http://www.aspeagro.com/EN_Program_Abricot.html
Thank you!
How about this? I think is should do what you're after?
HTML
<input id="submit-button" class="button" type="submit" value="Subscribe" data-dojo-attach-point="submitButton">
JS
$('#submit-button').on('click', function(e){
e.preventDefault();
// Do what you want to do
});
set id="btn" attribute to your submitting button and using jQuery you can trigger click with $("#btn").click(); call
If your aim is to submit the form, then don't bother sending a click event, but use the form's submit method:
var form = document.getElementById('uniqName_3_0').parentNode.parentNode;
form.submit();
The code is of course easier if you give the form an id attribute:
<form id="myform" ...
and then:
document.getElementById('myform').submit();
That button is inside an iframe. To access it from the parent page you would trigger it like this:
$('iframe').contents().find('input:submit').click()

ng-click doesnt work in input type submit

I write a angular application that has a form with input type submit but ng-click doesnt work
<div ng-show="!addDate && tk.doTime != null && tk.test2" class="change-item-btn" ng-click="addDate = true"> <span class="add-on"><i class="icon-time"></i></span>{{tk.doTime}}</div>
<form class="dateForm" ng-show="addDate" style="background-color:#dbf8f8;color: #152626; padding: 20px 20px 50px; margin-top:10px;" >
<div style="display:inline-block;width:50%;">
delivery
<div class="control-group">
<div class="controls">
<div class="input-append">
<input name="date" class="input-small datepicker form-control" placeholder="date" type="text" style="color:black" />
</div>
</div>
</div>
</div>
<div style="display:inline-block;width:50%;">
delivery time
<div class="input-append bootstrap-timepicker">
<input name="clock" style="color:black;direction:ltr;text-align:center" class=" input-small timepicker form-control" type="text">
</div>
</div>
<button ng-click="addDate = false" class="sbmtInput">cancel</button>
<input name="submit" type="submit" ng-click="deleting()" value="action" class="sbmtInput addDateTo" rel="{{tk.id}}-{{index}}-{{list.id}}" />
</form>
deleting function is
$scope.deleting= function(){
$scope.addDate = false;
}
addDate value change to false but doesnt have any effect on html view
where i go wrong?
This is because ng-click is in div with ng-show and in submit input as well.
When you click the event is done twice and in divs ng-click addDate is set to true again.
In order to make this work, you should prevent propagation in input.
To do this, use stopPropagation method, available in your scope $event object.
So the input code should be:
<input name="submit" type="submit" ng-click="deleting(); $event.stopPropagation();" value="action" class="sbmtInput addDateTo" rel="{{tk.id}}-{{index}}-{{list.id}}" />

AngularJS does not proper handle button type="reset"?

I have the following:
<form name="editor">
<h2>Create/Update</h2>
{{ editor.title.$error.required }}
<div ng-class="{ 'has-error': editor.title.$invalid && editor.title.$dirty, 'has-success': editor.title.$valid }" class="form-group">
<input type="text" name="title" ng-model="project.title" placeholder="title" required class="form-control">
<span class="input-icon fui-check-inverted" ng-show="editor.title.$valid"></span>
</div>
{{ editor.description.$error.required }}
<div ng-class="{ 'has-error': editor.description.$invalid && editor.description.$dirty, 'has-success': editor.description.$valid }" class="form-group">
<textarea name="description" ng-model="project.description" placeholder="description" required class="form-control"></textarea>
<span class="input-icon fui-check-inverted" ng-show="editor.description.$valid"></span>
</div>
<button ng-click="save()" type="submit" class="btn btn-primary btn-embossed">Save</button>
<button type="reset" class="btn btn-inverse">Reset</button>
Back
</form>
I follow "JavaScript Projects" tutorial on angular website main page. I've added reset button to detail.html. The problem is it's behavior. When I cleaning fields by myself, the validation fails, but when I click on the reset button, fields are cleaning up but the form remaining valid.
Is that an angular bug? And how get it fixed?
I believe what you're looking for is $setPristine();
$setPristine();
Sets the form to its pristine state.
This method can be called to remove the 'ng-dirty' class and set the form to its pristine state (ng-pristine class). This method will also propagate to all the controls contained in this form.
Setting a form back to a pristine state is often useful when we want to 'reuse' a form after saving or resetting it.
via http://docs.angularjs.org/api/ng/type/form.FormController
Example JS
$scope.data = {
"username": "",
"password" : ""
};
$scope.reset = function() {
$scope.data.username = "";
$scope.data.password = "";
$scope.form.$setPristine();
};
Example Markup
<form name="form" id="form" novalidate>
<input name="username" ng-model="data.username" placeholder="Name" required/>
<input name="password" ng-model="data.password" placeholder="Password" type="password" required/>
<div>
<hr />
<button class="button" ng-click="">Login</button>
<button class="button" ng-click="reset()">Reset</button>
</div>
</form>
Demo http://plnkr.co/edit/xTQLQH8mCCkY0tIX6n8Y?p=preview
Update : simplified solution
If you wish to do away with the controller function reset(), you could set type="reset" as originally done, but still need to $setPristine() on ng-click
<button class="button" type="reset" ng-click="form.$setPristine()">Reset</button>
new plunk: http://plnkr.co/edit/tNKPyyMboAQjeURn6m6W?p=preview

Categories