Disable submit button when form invalid with AngularJS - forms

I have my form like this:
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button disabled="{{ myForm.$invalid }}">Save</button>
</form>
As you may see, the button is disabled if the input is empty but it doesn't change back to enabled when it contains text. How can I make it work?

You need to use the name of your form, as well as ng-disabled: Here's a demo on Plunker
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="myForm.$invalid">Save</button>
</form>

To add to this answer. I just found out that it will also break down if you use a hyphen in your form name (Angular 1.3):
So this will not work:
<form name="my-form">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="my-form.$invalid">Save</button>
</form>

Selected response is correct, but someone like me, may have issues with async validation with sending request to the server-side - button will be not disabled during given request processing, so button will blink, which looks pretty strange for the users.
To void this, you just need to handle $pending state of the form:
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="myForm.$invalid || myForm.$pending">Save</button>
</form>

If you are using Reactive Forms you can use this:
<button [disabled]="!contactForm.valid" type="submit" class="btn btn-lg btn primary" (click)="printSomething()">Submit</button>

We can create a simple directive and disable the button until all the mandatory fields are filled.
angular.module('sampleapp').directive('disableBtn',
function() {
return {
restrict : 'A',
link : function(scope, element, attrs) {
var $el = $(element);
var submitBtn = $el.find('button[type="submit"]');
var _name = attrs.name;
scope.$watch(_name + '.$valid', function(val) {
if (val) {
submitBtn.removeAttr('disabled');
} else {
submitBtn.attr('disabled', 'disabled');
}
});
}
};
}
);
For More Info click here

<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required/>
<button ng-disabled="myForm.$pristine|| myForm.$invalid">Save</button>
</form>
If you want to be a bit more strict

Related

How to get the post vars from a form via user function

On a Typo3 website a form is integrated. The action should be routed to a typoscript user function.
This is what I tried so far:
The fluid form code (excerpt):
<form action="{f:cObject(typoscriptObjectPath: 'lib.mynlreg')}" method="post">
<input type="text" name="email" placeholder="Ihre E-Mail-Adresse">
<input type="submit" name="send" value="Jetzt registrieren" class="submit" />
</form>
The typoscript lib:
lib.mynlreg = USER_INT
lib.mynlreg {
userFunc = Vendor\Extension\myClass->myFunction
}
And the class:
class myClass {
public function myFunction($content, $conf) {
$arguments = $this->request->getArguments();
$formEmail = $arguments['email'];
return '<div>' . $formEmail . '</div>';
}
}
I expect to get the content of the form field "email", but after submitting the page throws an error. The question is, how do I get the post vars into the user function? Thank you for any help!
$this->request is not available in a userFunc. As gautamsinh mori says, you should use \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('email');, however I'm not sure you understand what the f:cObject ViewHelper does.
With this code, your HTML before submitting the form will be:
<form action="<div></div>" method="post">
<input type="text" name="email" placeholder="Ihre E-Mail-Adresse">
<input type="submit" name="send" value="Jetzt registrieren" class="submit" />
</form>
Your HTML after submitting will be:
<form action="<div>filledInEmail</div>" method="post">
<input type="text" name="email" placeholder="Ihre E-Mail-Adresse">
<input type="submit" name="send" value="Jetzt registrieren" class="submit" />
</form>
I'd recommend making an extension for this, but if you really want/need to do it like this, I think what you're looking for is something like:
<f:cObject typoscriptObjectPath="lib.mynlreg" />
<form action="{uri.page(addQueryString: 1)}" method="post">
<input type="text" name="email" placeholder="Ihre E-Mail-Adresse">
<input type="submit" name="send" value="Jetzt registrieren" class="submit" />
</form>
This will create the form with action to the current page (including any query string). You then have to change the userFunc to return an empty string if the form hasn't been submitted. Something like:
class myClass {
public function myFunction($content, $conf) {
$formEmail = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('email');
if (empty($formEmail)) {
return '';
}
return '<div>' . $formEmail . '</div>';
}
}

Why doesn't my React Js form accept user input?

I have a simple AddUser component and in the render function I am returning the following html:
<form ref="form" className="users-form" onSubmit={ this.handleAddNew }>
<input ref="username" type="text" name="username" placeholder="username"
value={this.state.username} onChange={function() {}} /><br />
<input ref="email" type="email" name="email" placeholder="email"
value={this.state.email} onChange={function() {}} /><br />
<button type="submit"> Add User </button>
</form>
I am binding the state of username and email to this.state which I am setting to blank in getInitialState like so:
getInitialState() {
return { username: '', email: '' };
}
I am binding state to the form so I can set it to blank after form submission.
The problem with this setup is that the form now renders as readonly.
I cannot get any user input into either text fields. What am I doing wrong?
Your input fields are controlled components, since you are using the value property. This makes the inputs readonly and they will always reflect the value, the variable (in this case, the state variable) holds. You have to explicitly setState onChange since you are setting username field as a state variable.
Read more about it here
onUserNameChange : function(e){
this.setState({username : e.target.value})
},
render: function(){
return ...
<input ref="username" type="text" name="username" placeholder="username"
value={this.state.username} onChange={this.onUserNameChange} /><br />
...
<button type="submit"> Add User </button>
</form>
}
A better way to do this is :
onChange : function(field,e){
this.setState({field: e.target.value});
},
render : function(){
return <form ref="form" className="users-form" onSubmit={ this.handleAddNew }>
<input ref="username" type="text" name="username" placeholder="username"
value={this.state.username} onChange={this.onChange.bind(this,"username")} /><br />
<input ref="email" type="email" name="email" placeholder="email"
value={this.state.email} onChange={this.onChange.bind(this,"email")} /><br />
<button type="submit"> Add User </button>
</form>
}
It looks like you saw the console warning about controlled fields needing an onChange handler and added one just to shut the warning up :)
If you replace your empty onChange handler functions with onChange={this.handleChange} and add this method to your component, it should work:
handleChange(e) {
this.setState({[e.target.name]: e.target.value})
}
(Or for people not using an ES6 transpiler:)
handleChange: function(e) {
var stateChange = {}
stateChange[e.target.name] = e.target.value
this.setState(stateChange)
}
However, if your component is an ES6 class extending React.Component (instead of using React.createClass()), you will also need to ensure the method is bound to the component instance properly, either in render()...
onChange={this.handleChange.bind(this)}
...or in the constructor:
constructor(props) {
super(props)
// ...
this.handleChange = this.handleChange.bind(this)
}

Meteor - Data saving issue

I have this template:
<Template name="nuevoEjercicio">
<div class="container-fluid">
<div class="form-group">
<input type="text" class="form-control input-lg" name="ejercicio" placeholder="Ejercicio?"/>
<input type="number" class="form-control" name="repeticiones" placeholder="Repeticiones?" />
<input type="number" class="form-control" name="peso" placeholder="Peso?" />
<button type="submit" class="btn btn-success" >
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
</Template>
that I use to capture and save to the database.
Then on my .js file I am trying to get the data and save it:
Template.nuevoEjercicio.events({
'click .btn btn-success': function (event) {
var ejercicio = event.target.ejercicio.value;
var repeticiones = event.target.repeticiones.value;
var peso = event.target.peso.value;
ListaRutina.insert({
rutina:"1",
ejercicio:ejercicio,
repeticiones:repeticiones,
peso:peso,
});
// Clear form
event.target.ejercicio.value = "";
event.target.repeticiones.value = "";
event.target.peso.value = "";
// Prevent default form submit
return false;
}
});
}
as I understand, when I click on any object that has the btn btn-success style....but is not the case. For some obscure reason -for me- is not working.
Can you check it and give me some advice?
Thanks!
First of all, there's an error in you selector. It's 'click .btn.btn-success', not 'click .btn btn-success'.
Also you can't do that event.target.ejercicio.value thing. event.target is the element that was clicked. You'll have to do something like this:
'click .btn.btn-success': function (event, template) {
var ejercicio = template.$('[name=ejercicio]').val()
...
OK
What after wasting hours and hours the solution is:
1- on the html file give your input an id:
<input type="number" class="form-control" **id="peso"** placeholder="Peso?" />
<button type="submit" class="btn .btn-success" id="**guardar**" />
so now you want to save data on the input when the button is clicked:
2- You link the button with the funcion via the id
Template.TEMPLATENAMEONHTMLFILE.events({
'click **#guardar**': function (event, template) {
var ejercicio = template.$("**#peso**").val();
and get the value linking using the input id.

Passing Text into URL from a Form

I'm trying to insert a variable collected from a form into a URL, but I don't want the "?variable=value" part of the URL.
<form action="http://www.example.com/<?php echo htmlspecialchars($_GET['entry']);?>/" method="GET">
<input type="text" value="" name="entry" id="entry">
<input type='submit'>
</form>
Is there any easy way to do this? I want the browser to go to the following URL when the user types "whatever"
http://www.example.com/whatever/
Edit:
I've changed the code to the following, which seems to work, but have I now introduced a script vulnerability?
<form onSubmit=" location.href = 'https://www.example.com/' + document.getElementById('entry').value + '/' ; return false; ">
<input type="text" value="" name="entry" id="entry" placeholder="Your Promo Code">
<input name="promoSubmit" type="submit" value="Buy Now">
</form>
you could use javascript for this kind of tasks, i don't see why would you involve server side for such thing
but the easiest answer will be like:
<script>
function go(){
window.location='http://www.example.com/'+document.getElementById('url').value;
}
</script>
<input type='text' id='url'>
<button id='btn_go' onclick='javascript:go();'>Go</button>

HTML required readonly input in form

I'm making a form. And on one input tag is an OnClick event handler, which is opening a popup, where you can choose some stuff, and then it autofills the input tag.
That input tag is also readonly, so only right data will be entered.
This is the code of the input tag:
<input type="text" name="formAfterRederict" id="formAfterRederict" size="50" required readonly="readonly" OnClick="choose_le_page();" />
But the required attribute isn't working in Chrome. But the field is required.
Does anybody know how I can make it work?
I had same requirement as yours and I figured out an easy way to do this.
If you want a "readonly" field to be "required" also (which is not supported by basic HTML), and you feel too lazy to add custom validation, then just make the field read only using jQuery this way:
IMPROVED
form the suggestions in comments
<input type="text" class="readonly" autocomplete="off" required />
<script>
$(".readonly").on('keydown paste focus mousedown', function(e){
if(e.keyCode != 9) // ignore tab
e.preventDefault();
});
</script>
Credits: #Ed Bayiates, #Anton Shchyrov, #appel, #Edhrendal, #Peter Lenjo
ORIGINAL
<input type="text" class="readonly" required />
<script>
$(".readonly").keydown(function(e){
e.preventDefault();
});
</script>
readonly fields cannot have the required attribute, as it's generally assumed that they will already hold some value.
Remove readonly and use function
<input type="text" name="name" id="id" required onkeypress="return false;" />
It works as you want.
Required and readonly don't work together.
But readonly can be replaced with following construction:
<input type="text"
onkeydown="return false;"
style="caret-color: transparent !important;"
required>
1) onkeydown will stop manipulation with data
2) style="caret-color: transparent !important;" will hide cursor.
3) you can add style="pointer-events: none;" if you don't have any events on your input, but it was not my case, because I used a Month Picker. My Month picker is showing a dialog on click.
This is by design. According to the official HTML5 standard drafts, "if the readonly attribute is specified on an input element, the element is barred from constraint validation." (E.g. its values won't be checked.)
Yes, there is a workaround for this issue. I found it from https://codepen.io/fxm90/pen/zGogwV site.
Solution is as follows.
HTML File
<form>
<input type="text" value="" required data-readonly />
<input type="submit" value="Submit" />
</form>
CSS File
input[data-readonly] {
pointer-events: none;
}
If anyone wants to do it only from html, This works for me.
<input type="text" onkeydown="event.preventDefault()" required />
I think this should help.
<form onSubmit="return checkIfInputHasVal()">
<input type="text" name="formAfterRederict" id="formAfterRederict" size="50" required readonly="readonly" OnClick="choose_le_page();" />
</form>
<script>
function checkIfInputHasVal(){
if($("#formAfterRederict").val==""){
alert("formAfterRederict should have a value");
return false;
}
}
</script>
You can do this for your template:
<input required onfocus="unselect($event)" class="disabled">
And this for your js:
unselect(event){
event.preventDefault();
event.currentTarget.blur();
}
For a user the input will be disabled and required at the same time, providing you have a css-class for disabled input.
Based on answer #KanakSinghal but without blocked all keys and with blocked cut event
$('.readonly').keydown(function(e) {
if (e.keyCode === 8 || e.keyCode === 46) // Backspace & del
e.preventDefault();
}).on('keypress paste cut', function(e) {
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="readonly" value="test" />
P.S. Somebody knows as cut event translate to copy event?
Required and readonly don't work together.
Although you can make two inputs like this:
<input id="One" readonly />
<input id="Two" required style="display: none" /> //invisible
And change the value Two to the value that´s inside the input One.
I have the same problem, and finally I use this solution (with jQuery):
form.find(':input[required][readonly]').filter(function(){ return this.value === '';})
In addition to the form.checkValidity(), I test the length of the above search somehow this way:
let fcnt = $(form)
.find(':input[required][readonly]')
.filter(function() { return this.value === '';})
.length;
if (form.checkValidity() && !fcnt) {
form.submit();
}
function validateForm() {
var x = document.forms["myForm"]["test2"].value;
if (x == "") {
alert("Name missing!!");
return false;
}
}
<form class="form-horizontal" onsubmit="return validateForm()" name="myForm" action="" method="POST">
<input type="text" name="test1">
<input type="text" disabled name="test2">
<button type="submit">Submit</button>
</form>