I have sample code like this:
Html Code:
<body ng-controller="MainCtrl">
<form name="myForm">
<input name="myText" type="text" name="test" ng-model="mytext" required />
<button ng-click="save()" ng-disabled="myForm.$invalid">Save</button>
</form>
</body>
Js code:
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.save = function(){
//logic or http method
console.log("Test");
}
});
Attached the code in this link: Click Here
Logic:
Default save button disabled.
After enter the form enable the button.
After save again disable the save button.
Again user enter the text need to enable save button.
Note: Here I attached only one input but I have multiple input fields.
Also, In save function I had logic data save into database.
You can use $pristine to identify if there were any changes to the form and enable button only then:
<body ng-controller="MainCtrl">
<form name="myForm">
<input name="myText" type="text" name="test" ng-model="mytext" required />
<button ng-click="save(myForm)" ng-disabled="myForm.$invalid || myForm.$pristine">Save</button>
</form>
</body>
Notice how $pristine is used on ng-disabled:
ng-disabled="myForm.$invalid || myForm.$pristine"
In this case button will be disabled if form is invalid or if there were no changes to the form.
If you use this approach you also need to set the form to pristine after saving the data. You can use method $setPristine:
$scope.save = function(myForm) {
// set form to pristine
myForm.$setPristine();
}
Notice that there is a form parameter which is used to pass a form to the method. In HTML you also need to pass this parameter as part of ng-click:
ng-click="save(myForm)"
Here is JSFiddle that demonstrates the functionality
For more information check out documentation of FormController.
you have disabled the submit button when the form is invalid.
myForm.$invalid
so whenever a required field is blank the form will be invalid and button will be disabled. As soon as all the required input in the form have values, submit button will be enabled.
To make it disabled you need to reset all the modal variables of the required inputs once the save has done its work i.e on the success call back of http request reset the model variables.
Well here is how i would do it, i'll add another tracking variable. something like this.
$scope.btnStatus = true;
$scope.save = function(){
//logic or http method
$scope.btnStatus = false;
console.log("Test");
}
$scope.onChange = function(){
if($scope.btnStatus == false)
$scope.btnStatus = true;
}
and the html would look like this.
<form name="myForm">
<input name="myText" type="text" name="test" ng-change="onChange()" ng-model="mytext" required />
<button ng-click="save()" ng-disabled="myForm.$invalid || !btnStatus">Save</button>
</form>
Here is a working code based off of your code.
Related
Ive created a simple html form with a text input and a submit button. I was told that with a little javascript, I could make it so when users fill out that input and click the submit button, it would open up the live chat and automatically have their submission as the first message in the live chat. Here's my form:
<form name="question">
<input type="text" name="important">
<input type="submit" value="Submit">
</form>
I was told I have to include the api with the 'say' function ( https://api.zopim.com/files/meshim/widget/controllers/LiveChatAPI-js.html#say ). I've got this far:
<script>
$zopim(function() {
$zopim.livechat.say('SOMETHING GOES HERE');
});
</script>
But their 'say' example uses this link rather than an input:
Order orange banana
I'm not sure how to edit that code to use my form input instead of a static link.
Any ideas? Thanks!
What you are seeing in the reference from their docs just executes the say function when you click on it. You could simply add a click listener to the submit button and then get the value of the input and pass that to the .say function.
Note: I commented out the zopim parts as they technically don't matter here as we are simply trying to get some values from an input.
Example:
//$zopim(function(){
$('input[type="submit"]').on('click', function(e){
e.preventDefault(); // prevent hte form from redirecting
let message = $('input[name="important"]').val();
console.log(message);
//$zopim.livechat.say(message);
});
//});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="question">
<input type="text" name="important">
<input type="submit" value="Submit">
</form>
The connection to contact form might not be needed after all:
This is what fabricated from the above mentioned
this doesnt work, however, if anyone who knows what they are doing could take a look at it.
$zopim(function(){
$('input[type="submit"]').on('click', function(e){
e.preventDefault(); // prevent hte form from redirecting
var important = $('#amount').val();
if($.isNumeric(important)) {
{if( important < 30) { $('.error').html('We only buy 20 or more.').show();
} else
var message = 'I would like to sell ' + important '.';
$('.error').html('').hide(); $zopim.livechat.say(message);
let message = $('input[name="important"]').val();
console.log(message);
$zopim.livechat.say(message);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<form name="question">
<input type="number" placeholder="Amount" name="important">
<input type="submit" value="Start chat">
</form>
After I click submit in a form, some javascript runs to modify the data and sends it to whatever the form action is specified in the HTML:
// Submit the form:
// $form.get(0).submit();
$('.submit', $(event.target.form)).click();
I would like to instead use ng-click and send that info to an angular function, such as vm.checkout().
How can I make this happen?
Use ngSubmit directive instead of ngClick for form submit.It binds to the submit event which is fired when a form is submitted.
ng-submit works only when forms submitted.
where as ng-click can work without form submit event.
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.submitMe = function () {
alert('Submitted');
};
});
<div ng-app="myApp" ng-controller="MyCtrl">
<form ng-submit="submitMe()" name="myForm">
<button type="submit">submit</button>
</form>
</div>
JavaScript
$scope.submit = function(data){
// do something with data
}
HTML
<form>
<input type="text" ng-model="temp.name" name="name"/>
<button type="button" ng-click="submit(temp)">Submit</button>
</form>
If it is a form you are submitting you should use ng-submit. Add the ng-submit tag with the corresponding function which will be in your controller. Then, you will be able to handle the data from your form submission.
For example:
<form ng-submit="submit()" ng-controller="ExampleController"></form>
I have a HTML page containing a form. I want to make some fields "required". The problem is that I'm not using a <input type="submit"> in my form, instead, I use a Javascript function to submit the form because I need to send a Javascript variable to my server. Here is my code:
<form action="/toServer">
Username: <input type="text" name="usrname" required>
<input type="button" onclick="submitForm(this.form)" value="Submit">
</form>
var submitForm = function(frm){
var qstNbr = document.getElementById('hiddenField');
qstNbr.value = someJsVariable;
frm.submit();
}
So, Even is I have the required attribute in my input but the form is still being submitted even if I don't enter anything in the input.
Here is a JSFiddle of how I want my form to behave when clicking on the button without entering anything.
Anyone knows how form.submit() is different from having an <input> of type="submit" ?
EDIT: After following user2696779's answer and doing a little modification, here's the final working code:
<form action="/toServer">
Username: <input type="text" name="usrname" required>
<input type="submit" onclick="submitForm(this.form)" value="Submit">
</form>
var submitForm = function(frm){
if (frm.checkValidity()) {
var qstNbr = document.getElementById('hiddenField');
qstNbr.value = someJsVariable;
frm.submit();
}
}
Your current HTML input button isn't a submit type, it's a button type. The requred attribute on your input element is therefore ignored. To change this, change your button's type to submit:
<input type="submit" value="Submit">
Browsers which support the required attribute will now display a warning when the button is clicked:
JSFiddle demo.
Submitting using javascript will not trigger any validation. If you want to submit using a regular button + javascript and still have validation, you may use HTML5's checkValidity function to verify form fields, or the entire form.
For example, using JQuery:
if(!$('form')[0].checkValidity()) {
alert('not valid');
}
else {
$('form').submit();
}
See fiddle for working example: http://jsfiddle.net/8Kmck/2/
How can I prevent submitting a form in Angular until I receive a callback?
I have something along these lines:
<form method="post" action="http://example.com/external" ng-submit="submit()">
<input type="hidden" name="foo" value="{{bar}}" />
<input type="submit" />
</form>
Before submitting the form, I need to get the {{bar}} value from a local API call (using $http), and place it in the scope before allowing the actual form to submit (not POSTed using $http). How can this be done?
The form directive in Angular will wrap it in a formController and intercept it. You can still run your asynchronous code but you will need to reference the DOM form to submit it. I have an example fiddle with the solution - basically it sets up a button to submit the form, asynchronously sets the hidden field, then posts it.
Here is the relevant code:
MyController = function ($scope, MyService) {
$scope.boo = "";
$scope.submit = function () {
MyService.getAsync().then(function(result) {
$scope.boo = result;
document.myForm.action = "http://example.com/";
document.myForm.submit();
});
};
};
If you run a fiddle you will see the hidden field is populated:
http://jsfiddle.net/jeremylikness/T6B2X/
The "ugly" part of the code is the direct reference to:
document.myForm
If you wanted to clean this up, you could write your own directive that allows you to place an attribute on the form and interacts with a service to manipulate it. I.e. MyFormService and then I could do MyFormService.setAction(url) and MyFormService.submit() - that would be more cleaner and reusable but time wouldn't permit me to set that up for you.
As docs for ng-submit state:
Additionally it prevents the default action (which for form means
sending the request to the server and reloading the current page) but
only if the form does not contain an action attribute.
So remove that action attribute and handle it directly yourself in the submit() handler on the scope.
Make yours http call and in then success handler submit the form manually.
Can you not just use the submit button's onClick event to call a function that returns false if the submit is not allowed?
i.e. onClick='return CheckIfFooPopulated();'
Then in that function return false is foo as not yet been set or true if it OK to submit.
The problem is that ng-submit doesn't work with an action attribute, as stated in the docs.
Then, you can do whatever you want inside of submit() in your controller. However, I would use ng-model for the form input fields because it gives you better control over the model.
You would use this $scope.formModel to bind the input fields to the scope.
You could implement submit like that:
$scope.submit = function() {
$http.get("URL").success(function(data) {
$http.post("URL2", { model: $scope.formModel, bar: data.bar }).success(function() {
$location.path("/new-route");
});
});
}
There many possibilityes, but a less risky is to use ng-switch.
ng-switch do not load DOM if not needed.
<span ng-switch on="barNotEmpty">
<span ng-switch-when="true">
<form method="post" action="http://example.com/external" ng-submit="submit()">
<input type="hidden" name="foo" value="{{bar}}" />
</form>
</span>
<span ng-switch-default>
<form>
<input type="hidden" name="foo" value="{{bar}}" />
</form>
</span>
I have this simple form:
HTML
<form>
<label for="eName">Name</label>
<input id="eName" type="text" name="eName">
<label for="Email">Email</label>
<input id="Email" type="text" name="Email">
<button id="create" class="boton"
onclick="doSomething();" type="submit">Create!</button>
</form>
JS
function doSomething() {
var name, email;
name = document.getElementById("eName").value;
email = document.getElementById("Email").value;
putElementsIntoTheDOM(name, email);
}
When the user inputs some information I want to populate the DOM with the user input.
The example above works. But I think it can be done better. I just don't know how.
How can I wire the <button> so that when the user clicks it the form values are passed
to the function doSomething()?
Also, since I'm not sending the form values anywhere except populating the DOM, how can I
prevent the submission?
I've seen something like this but I can't get it too work.
<button id="create" class="boton" onclick="doSomething(this.form);"
type="submit">Create!</button>
If you don't want to send the form values anywhere, then you just need to remove type="submit" from your button.
Your example code works fine. I'm not sure what you mean by a 'better' way. More modern/idiomatic javascript would not be using the onclick attribute, but instead binding doSomething to the button. Using jQuery, that would look like:
$("#create").click(doSomething);
First of all you have to update your function declaration to be able to receive the variables you want to send
function doSomething(name,email) {
}
Secondly, if you have to send values of some fields to that function, you can do so on button click like this.
<button id="create" class="boton" onclick="doSomething(document.getElementById('eName').value,document.getElementById('Email').value);" type="submit">Create!</button>
However, using unobtrusive javascript is recommended, and for that jQuery is one of the options you can use for passing variables to your function neatly.
There is a difference between the type="submit" and type="button" that I didn't realize.
Also, the button and submit types react differently with onclick and onsubmit events.
For example
<form onclick="doSomething()">
<label for="eName">Name</label>
<input id="eName" type="text" name="eName">
<label for="Email">Email</label>
<input id="Email" type="text" name="Email">
<button id="create" class="boton" type="button">Create!</button>
</form>
Notice that at the top of the form there is onclick.
The onclick is fired whenever you focus on an input element, and of course if you click the button.
Changing the form to <form onsubmit="doSomething(); but not changing the type="button" doesn't do anything. Clicking the button doesn't trigger the function.
By changing the type="submit"and keeping the head <form onsubmit="doSomething(); triggers the function when the button is clicked. A nice added functionality to this is that if you have any <input ... required="required"> the submit will only work if those fields are filled in (and your form will let you know about the required fields).
To prevent the submission/refreshing (since I'm only populating the DOM with user input) adding return false at the form head prevents submission
<form onsubmit="doSomething(); return false">.
Finally, to get the form values adding this:
<form onsubmit="doSomething(this); return false> and then
function doSommething(formInfo) {
var name = formInfo.eName.value;
var email = formInfo.Email.value;
...
}