The whole form should not be valid until stuff[] has at least one item added to it. When the user enters in a value into the text box and then clicks add it then adds the value to stuff[], only at this point when a value has been added to stuff[] should the submit button be enabled. However, as soon as the user types anything into the text box without clicking add, and thus nothing in stuff[], it makes the form valid and enables the submit button.
<form ng-app="myApp" ng-controller="myCtrl" name="myForm" ng-submit="submit()" novalidate>
<div ng-repeat="things in stuff">
<table><tr><td>{{things}}</td></tr></table>
</div>
<input type="text" name="app" ng-model="input" ng-required="!stuff[0]" />
<button ng-disabled="!input" ng-click="add()">
<span> add</span>
</button>
<input type="submit" value="Submit" ng-disabled="myForm.$invalid" />
<script>
angular.module('myApp', []).controller('myCtrl', function ($scope) {
$scope.stuff = [];
$scope.input = null;
$scope.add = function () {
var l = $scope.stuff.length;
$scope.stuff[l] = $scope.input;
$scope.input = null;
};
$scope.submit = function () {};
});
</script>
</form>
[EDIT]
To answer your question directly: !stuff[0] is TRUE when there is nothing in the array, and FALSE otherwise. When it is TRUE, then input is required, making the form 'initially' invalid. As soon as you type something into the input, then the requirement is now fulfilled, meaning that the form is valid, and you can now click the submit button. The condition actually has nothing to do with actually putting something into the array.
This is fixable by attaching a condition to stuff.length as proposed by my answer below. It won't make the form invalid (which you can easily do with this condition elsewhere) but it will at least disable the submit button.
[/EDIT]
I don't understand why you have ng-required there, as you are wanting to disable the submit button, meaning the logic should be attached to the submit button, not the input text box.
I would do this instead:
<input type="text" name="app" ng-model="input"/>
<button ng-disabled="!input" ng-click="add()">
<span> add</span>
</button>
<input type="submit" value="Submit" ng-disabled="stuff.length == 0" />
Which will disable the submit button if there is nothing in stuff.
Related
I am trying to get an event handler on an HTML form. I am just trying t get the simplest thing working, but I just cannot see what I am missing.
It is part of a wider project, but since I cannot get this bit working I have reduced it down the most very basic elements 1 text field and a button to try and see what it is I am missing.
All I want to do is get some text entered and flash up message in a different area on the screen.
The user enters text into the input field (id=owner).
The plan is that when the button (id="entry") is pressed the event handler (function "entry") in the entry.js file should cause a message to display.
I don't want the form to take me to a different place it needs to stay where it is
I just want some form of text to go in the: <div id="feedback" section.
When I can get it working: I intend the create the text from the various text fields that get entered.
I Know that this is beginner stuff & I know that I have reduced this down such that it barely worth thought but I would welcome any input please & thank you.
HTML code is:
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
<script src="entry.js"></script>
Code for entry.js is:
function entry() {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementByID('feedback');
elMsg.textContent = 'hello';
}
var elEntry = document.getElementById('entry');
elEntry.onsubmit=entry;
I have tried:
Adding in a prevent default:
window.event.preventDefault();
doing this through an event Listener:
elEntry.addEventListener('submit',entry,false);
using innerHTML to post the message:
elMsg.innerHTML = "
At present all that happens is that the pushing submit reloads the page - with no indication of any text being posted anywhere.
One issue is that you have a typo, where getElementById capitalized the D at the end.
Another is that preventDefault() should be called on the form element, not the input.
Here's a working example that corrects those two mistakes.
function entry(event) {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
event.preventDefault();
}
var entryForm = document.getElementById('entry').form;
entryForm.onsubmit = entry;
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
I also defined a event parameter for the handler. I don't remember is window.event was ever standardized (it probably was), but I'd prefer the parameter.
Be sure to keep your developer console open so that you can get information on errors that may result from typos.
var elEntry = document.getElementById('entry');
elEntry.addEventListener("click", function(e) {
e.preventDefault();
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
});
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
I have a button submit inside a form and just a normal button outside of it. I want to validate a form:
function myButtonHandler(evt) {
if (myForm.checkValidity()) {
alert("yes");
} else {
alert("no");
}
}
This doesn't show the standard error tips inside of input elements when they're invalid when I click on a button -- ones shown by a browser when I click the submit button. How can I get these validation message to pop up when I click on my normal button when the form is invalid?
<form id="my_form">
<input type="text" placeholder="Name" required="true"/>
<input type="submit" id="submit" value="go" />
</form>
No jquery.
You'll need to add the code you've shown to a function that is set up as the click event callback for the normal button:
var myForm = document.querySelector("form"); // reference to form
var btn = document.querySelector("[type='button']"); // reference to normal button
// Set up click event handling function for normal button
btn.addEventListener("click", function(){
if (myForm.checkValidity()) {
alert("yes");
} else {
alert("no");
}
});
<form>
<input type="text" required>
<button type="submit">submit</button>
</form>
<button type="button">Check Validity</button>
If you just want to show the normal browser's validation errors, you can make the second button also a submit button. It's OK for the button to be outside of the form as long as you tie it back to the form with the form attribute.
<form id="theForm">
<input type="text" required>
<button type="submit">submit</button>
</form>
<button type="submit" form="theForm">Check Validity</button>
I want to validate a form with my custom js function "isValid". I did something like this:
<input id="pricecondition" name="pricecondition" ng-model="user.pricecondition" ng-focus="user.pricecondition=''" required />
<button ng-click="submit()" ng-disabled="form.$invalid && user.isValid">submit</button>
But it seems that the view ng-disabled calls user.isValid only once.
This is the js code of my controller:
$scope.user = {
[...],
lenght: "",
pricecondition: "",
isValid : function()
{
return false;
}
};
So when the property length or price condition changes the value the function isValid is fired, but the button seems not to re-evaluate user.isValid. The button is enabled obviously the function isValid returns false.
How can I force ng-disabled or ng-show to call isVlaid() again?
greetings
you got another problem from your comment, sorry i didn't noticed that at first...
use formname and not tag name for disabling the button...
<form name="myform" novalidate >
// your html
<button ng-disabled="myform.$invalid">submit</button>
</form>
or if you have forms inside form then use ng-form
<form name="parentForm">
<div ng-form="myform1">
// your html
<button ng-disabled="myform1.$invalid">submit1</button>
</div>
<div ng-form="myform2">
// your html
<button ng-disabled="myform2.$invalid">submit2</button>
</div>
</form>
You must have a form element with a name attribute in order to use "form.$invalid".
Also i would make the button invalid if the form is invalid OR the user is invalid.
<form ng-submit="submit()" name="form" novalidate >
<input id="pricecondition" name="pricecondition" ng-model="user.pricecondition" ng-focus="user.pricecondition=''" required />
<button ng-disabled="form.$invalid || !user.isValid()">submit</button>
</form>
I'm working on a submission form that includes a few required fields, and I have a segment of code that allows a popup menu to appear once you hit the "submit" button, and from there once you hit "ok" on the alert you're redirected to the home page. Here's the code I have for the popup alert.
<div id="popup">
<button onclick="myFunction()">Submit</button>
<script>
function myFunction(){
alert("Thank you! \nYour sumbission has been
accepted and you will receive a conformation email shortly! \n
You will now be taken to the Home page.");}
</script> <input type="reset" value="Reset" />
</div>
And this is the beginning of the code for redirecting you to the homepage.
<div id="all">
<div id="text">
<h1>Your Information</h1>
<form id="contact_form" action="home.html" method="post">
<input type="hidden" name="redirect" value="home.html" />
(Note: I clipped the above segment of code because the following information is only the form input boxes)
And this works like you would imagine, the alert popping up once you hit the submit button. However my question is that I have a few required fields on my form, and if the fields are not filled out and you hit "submit", the popup alert appears, and once you hit "ok" on the alert, because you have yet to fill out these fields it takes you back to the form and a little box saying "this field is required" appears.
This is in the wrong order. I want the alert box for the required fields to show before the popup alert for the confirmation of form submission, so that if you have required fields and you hit submit it will tell you to fill out the required fields before the message appears thanking you for submitting.
This may be a simple fix of placement or adding a little code but I'm having a hard time figuring out how to do it or finding an example that could help me.
If you know what to do I'd really appreciate it, thanks!
Edit: This is the javascript file for the validation code.
window.onload = setForm;
function setForm() {
document.forms[0].onsubmit = function() {
if (this.checkValidity()) alert("No invalid data detected. Will
retain data for further testing.");
return false;
}
}
function Validation()
{
vak k = true;
k = function 1 validates field 1 AND returns true or False based On Validation
k = function 2 validates field 2 AND returns true or False based On Validation
k = function 3 validates field 3 AND returns true or False based On Validation
return k;
//At The End Of This Function You Need To Get "TRUE" To Truly Submit.
}
On Submit :
If(Validation() == true)
{
then Only Submit
}
Write Back If It Dosen't Works...
<html>
<body>
<div id="popup">
<textarea cols="30" rows="2" name="required" id="required"></textarea>
<input type="submit" id="click" value="Submit">
<input type="reset" value="Reset" />
</div>
<script>
var click = document.getElementById("click");
click.addEventListener("click", function() {
var required = document.getElementById("required").value;
if (required===null || required==="") {
alert("Please make sure all required field are completed");
}
else {
alert("Thank you! \nYour sumbission has been accepted and you will receive a conformation email shortly! \nYou will now be taken to the Home page.");
window.location.replace("http://stackoverflow.com", 5000);
}
});
</script>
</body>
</html>
http://jsbin.com/wuxahape/1/
I have an HTML form that I submit after changing the action with some javascript. Two different buttons can do the submit.
The interesting thing is that I was trying to debug it and inserted an alert after changing the action and before submitting the form. The form is submitted without the alert ever being displayed. To make sure it's actually performing the javascript, I added an alert before changing the action. That alert displays; the alert after changing the action does not.
<form name='FormSelect' method='post' action='Undefined'>
...
<button onclick="SubmitForm('class')">Submit</button>
...
<button onclick="SubmitForm('student')">Submit</button>
...
</form>
<script type="text/javascript">
function SubmitForm(target){
alert("Action 1: " + document.FormSelect.action);
if (target=="class") {
document.FormSelect.action = "ClassAction.php";
} else {
document.FormSelect.action = "StudentAction.php";
}
alert("Action 2: " + document.FormSelect.action);
// document.FormSelect.submit();
}
</script>
Is that the expected sequence of events?
Any button placed inside form element will cause submit action. To prevent this you can add type="button" to button elements, or make you submit callback return false;
<button type="button" onclick="SubmitForm('class')">Submit</button
see http://jsfiddle.net/yD2Uu/
As the others have already pointed out the form will be submitted anyway if you don't cancle the event. I want to suggest a JavaScript free solution to your problem.
<button formaction="ClassAction.php">Submit</button>
<button formaction="StudentAction.php">Submit</button>
It's not supported in IE < 10 though. But you can still use your function as a fallback then, just a bit more elegant ;)
function SubmitForm(button){
button.form.action = button.formaction;
}
A better solution is to give the buttons a name each and submit to Action.php and let the server get the value of the named button
$student = filter_var($_POST["student"], FILTER_SANITIZE_STRING); // php5 cleaning
when you have
<form method="post" action="Actions.php">
<input type="submit" name="student" value="John Doe" />
<input type="submit" name="student" value="Jane Doe" />
<input type="submit" name="student" value="Whatever Doe" />
</form>
Otherwise if you must
Try this
<form method='post' action='Undefined'>
...
<input type="button" value="Class" onclick="SubmitForm(this)" />
...
<input type="button" value="Student" onclick="SubmitForm(this)"/>
...
</form>
<script type="text/javascript">
var actions = {
"class":"ClassAction.php",
"student":"StudentAction.php"
}
function SubmitForm(button){
button.form.action = actions[button.value];
button.form.submit();
}
</script>
Thanks to Yauhen Vasileusky's example, I started removing code between my 1st & 2nd alerts and found that the problem seems to be the following IF statement:
if (document.FormSelect.FormName.value.substr(0,19)=="ObservationRequest_" || document.FormSelect.FormName.value=="StudentReg2013rx" || document.FormSelect.FormName.value=="Toddler Update Form v3rx")
{
document.FormSelect.action = "GenerateXDP.php";
}
When I remove it, both alerts are displayed. So the answer to my question is that changing the action does not submit the form; it was some other error in my code that made it appear as if that was the case.