Is there any way I can direct focus to a specific input field on a form? - angularjs

I have a large form and I would like when the user clicks a "new" button for the focus to be placed in a specific input field. There's a grid on the form and every field has a known id. Note it might not be the first field so not easy to use the tab.
Would appreciate some advice if this is possible. Would save having to manually have the user move the cursor over and click in the input field.
Update: Changed "move cursor" to "change focus"

Here is one solution -
Angular js gives you an advantage of using some of the extra features so that you dont have to use the jquery.
Here is one way to implement the autofocus feature.
<div class="button" input-focus>{{element.idORname}}</div>
and the directive to be defined here.
.directive("inputfocus",function($timeout){
return {
link : function(element,attributes){
element.bind('click',function($timeout){
$timeout(function(){
element/*.parent() or.child()*/.find('type of the field you want to select')[0].focus();
);
);
);
Here you can use the javascript or jquery methods for the dom traversal if there are nested fields in your code.
$timeout is necessary to call for the focus after the browser renders when user has finished clicking the event
As you can see the find('')[0] is a replacement for find('').focus as the latter requires jquery to be used.

Place "autofocus" attribute on the element that you want to focus.
Example:
Name: <input type="text" name="name" autofocus />

If all the input ids are known, just use that.
$("#NewButton").on('click', function(){
//Other code.
$("#IdOfInputToBeFocused").focus();
});

Custom data attribute can be used with jQuery like this
<input data-field="special" />
And then that specific field can be called like this
jQuery('input').find("[data-field='special']").focus();

Related

Material UI - Replicating the "required" text field error message

I have a simple TextField component from Material UI in React (notice the "required")
<TextField
label="Last name"
name="lastName"
required
value={this.state.lastName}
onChange={this.handleChange}
/>
I love the functionality and appearance of the "required" property. It looks like this when it's activated:
Unfortunately, this property is only available on their TextField component and not the RadioGroup or Select components. If I can at least replicate the appearance (and maybe the fact that it scrolls the page to the location of the input), I can apply it to all of my inputs for a consistent UI.
Does anyone know where they are getting the appearance from? It looks like it may be from a different package. Any help in finding it would be appreciated.
If you are referring to the "Please fill out this field" it looks like this might be a browser specific feature rather than a Material feature... Have you checked other browsers to see if this behaviour is reproducible?
Actually is fairly easy to change the styles for the errors that the different browsers show whenever a form is validated. Here your friend is the Constraint API.
There is an invalid event that will be fired before a form is submitted that checks if the elements that have the required attribute satisfy or not its constrains .
What I normally do is to use the onInvalid event handler and pass a callback where you can get a lot of info about the validation.
For example in event.target.validationMessage you'll see the "Please fill out this field" or the event.target.validity.valid will tell you if the element is valid or not. Bear in mind that you have to preventDefault the event.
e.preventDefault();
setInvalid( e.target.validity.valid );
setMessage( e.target.validationMessage );
This is how I've styled the native HTML errors using the <SnackbarContent /> component from material-ui.
Also, just to mention that CSS has a couple of pseudo elements that will help you to style the input. :invalid and :valid but this has nothing to do with the message itself.
Because this styles inconsistency really bugged me a time ago I created a npm plugin that deals with this for you, pretty-form-error it works with React and at least Angular 1.x.x
This is actually a property of input from vanilla html. Textfield is composed of smaller components and Input is one of the components they use. The required property will trigger the dialog to appear.
<html>
<body>
<form>
Username: <input type="text" name="username" required>
<input type="submit">
</form>
</body>
</html>
This snippet will also produce the same message.

Submittable HTML5 Web Component

How do I create a form-submittable web component?
Background:
I have a customer-picker component that is basically a text input plus a tiny button to the right of the text box plus a dialog that pops up when the button is clicked. It is used in the same way as one might use an html select.
This component is used as part of an html form that is submitted in the old fashioned (non-ajax) kind of way. The actual html input is encapsulated privately inside of the customer-picker component.
Problem:
The text input's value is not submitted
I guess I can understand why this is. I suppose this is the desired behavior (otherwise we are breaking encapsulation).
So with all that said, how do I create a submittable web component?
For example, suppose I have a form like this:
<form action="action.jsp">
<input name="date-start"/>
<input name="date-end"/>
<input name="name-first"/>
<input name="name-last"/>
</form>
that gets submitted like this:
action.jsp?date-start=2016-06-01&date-end=2016-06-30&name-first=Joe&name-last=Smith
I would like to create the same form using components like this:
<form action="action.jsp">
<date-range name="date">
<full-name name="name">
</form>
that gets submitted exactly the same way as the example above:
action.jsp?date-start=2016-06-01&date-end=2016-06-30&name-first=Joe&name-last=Smith
I am aware of iron-form. But this solution has some problems.
For one, it does not emulate native form submission very well. In a normal html form, when you submit, the current page is automatically replaced by whatever is returned by the action URL. This doesn't seem to happen with iron-form.
Second. It only allows your component to contribute a single value to the submitted data. In the above mentioned date-range example, I would like two values to be submitted for one component.

AngularJS - Form validation triggered on load

I added field validation attributes like "required" and "pattern" in my form, and the form is inside a ng-controller. The validation works. But it seems the validations are triggered on page load, and I see all the fields are marked as invalid with error message when the page load.
I tried to add "novalidation" attribute to the form as indicated in the examples on AngularJS website, but no luck.
I would like to have the validation triggered the first time the user tries to interact with it. How can I do that?
Update
Here's an example https://jsfiddle.net/davidshen84/00t197gx/
<div class="mdl-cell mdl-cell-6-col mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="text" id="screenname" pattern="[a-zA-Z0-9]{3,}" ng-model="comment.screenname" required/>
<label class="mdl-textfield__label" for="screenname">Screen Name</label>
</div>
On load, you should see all the input fields had a red line under them which indicate they are in the invalid state. And the line turns to blue once validated.
Note: The style on the check button does not work...should not be a concern in the problem.
Angular is going to check the form the same way at any point (load or later) and render the result. If you don't want to display the results on load, add logic to check whether the form has been interacted with. You can hide your error messages using ng-if="yourFormName.$dirty", or display according to the status of an individual field with yourFormName.yourFieldName.$dirty.
Click here for live demo.
What is currently implemented (wrong IMHO) is that MDL automatically validates input and doesn't mind "novalidate" form attribute. I had to implement check for empty input value (skip validation and remove is-invalid class) and, since angular form validation requires "novalidate" attribute, check:
if (input.form.novalidate = true) // skip validation
that way you can actually turn off mdl validation and leave everything to angular.
One more thing is actually required. You can create angular directive which validates expression and add is-invalid class if necessary:
div class="mdl-textfield" mdl-validator="form.email.$error"

How can I hide a component in AngularJS yet still get an external library to bind to it?

In my code I have something similar to
<div ng-if="variableThatEvaluatesToFalse">
<input id="location">
</div>
What I'm trying to do is hide a component and then show it in response to user input. However, upon my page loading I want Google Maps to attach to my input. Google Maps relies on document.getElementById('location') which is null presumably because AngularJS is 'hiding' it. I can I get document.getElementById('location') to return my input field even if it is initially hidden by the ngIf directive?
The ngIf directive prevents elements from being included in the DOM at all. What you would need in this case is ngHide, which would keep the element in the DOM.
See: https://docs.angularjs.org/api/ng/directive/ngHide

How to add dynamic text fields with AngularJS

My question is more about what would be the best practice in this scenario:
I have a form that has to allow a user to input n number of ideas, each idea in an independent text field. Ideally there would be a couple of buttons next to the last text input to allow the user to create a new text input or to erase the latest one.
I know DOM manipulation is not the way to go with Angular but due to requirements, I have to do something that requires creating elements dynamically. Is there a best practice, service or directive in Angular that could allow me to do this or I should just inject the elements with jQuery?
The only thing you need is proper use of ng-repeat. No DOM manipulation with jQuery is necessary. Nor would it be good practice. Behold, the power of ng-repeat.
Working plunker here.
Something like this?
<div ng-repeat="idea in ideas">
<input ng-model="idea">
</div>
<button ng-click="AddNew()">Add New Idea</button>
<button ng-click="DeleteLast()">Delete Last Idea</button>
In controller:
$scope.AddNew = function() {
$scope.ideas.push("");
}
$scope.DeleteLast= function() {
$scope.ideas.splice($scope.ideas.length-1, 1);
}

Resources