How do I bind a value to a textbox in Angular2? - date

I have been trying to figure out how to bind a value to a textbox in Angular2. Currently I have a textbox with a placeholder that is loaded with a predetermined value.
<input id="textbox" class="k-textbox" placeholder={{label}} />
But once I change a value of a date component, I would want the placeholder value to be updated to the date value selected. So far i wrote this but this doesn't seem to be working. Please advice.
date-component.html
<input id="datepicker" (input)="changeLabel()"/>
date-component.ts
label:string;
constructor() {
this.label = 'Select Date';
}
changeLabel() {
this.label = 'Date Selected';
}
}

use an click event to propagate the changes.
date-component.html
<input id="datepicker" (click)="changeLabel()"/> //<-- click event

You could use two way databinding with NgModel.
https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngModel
Basically this would make "label" change to whatever the user types.
<input [(ngModel)]="label" id="datepicker" />
You will also need to import FormsModule in your app.
Plunker to show what I mean:
https://plnkr.co/edit/CfmalT7GesrP5lzBsNFx?p=preview

use keyup Event
<input (keyup)="changeLabel()">
enter the value its call the keyup event

Related

TextField is not getting updated on re-render with different intialValues

I'm using redux-form-material-ui for the forms. I have simple form with two text fields. This form will show the initalValues passed to it and user can also update the values of TextField. These TextFields working fine with validations and all but I'm facing problem while re-rendering. On route change, I'm passing the different intialValues to that form component but even though proper values passed to it, TextFields are not getting updated. It just shows the first time passed initialValues.
Here is my code:
From parent component:
<ReduxForm {...initialValues} />
ReduxForm component:
class ReduxForm extends React.Component {
render () {
return (
<div>
<form onSubmit={() => console.log('Submitted')} >
<Field
className='input-field'
name='name'
component={TextField}
floatingLabelText='Full Name'
/>
<Field
className='input-field'
name='email'
component={TextField}
floatingLabelText='Email'
/>
</form>
</div>
)
}
}
export default reduxForm({
form: 'test-form',
validate
})(ReduxForm)
I Know that, this is the same problem with defaultValue in material-ui's TextField. Is this expected behavior in redux-form-material-ui also? If so, is there way I can solve this issue without setting the state and all?
Thank you!
Haven't used redux-form-material-ui but try adding enableReinitialize: true to your reduxForm decorator
export default reduxForm({
form: 'test-form',
validate,
enableReinitialize: true
})(ReduxForm);
And see if that works.

Angular 2 checkbox - How to use [checked] with (ngModelChange)?

I'm having trouble programmatically setting a checkbox in Angular 2. The following code fires onCheck() whenever the user checks the checkbox. I can also check the checkbox programmatically by setting this.select to 'true'.
<input type="checkbox" [(ngModel)]="v.checked" [checked]="select" (ngModelChange)="onCheck(v.checked)">
My problem is that when I set this.select to 'true', ngModelChange doesn't seem to detect the change and onCheck() doesn't fire... :-(
Any tips? Is there an alternative way to programmatically set a checkbox AND have its associated function fire?
you can use checkbox with component variable like :
#Component({
selector : 'my-component'
template : `<input type="checkbox" [(ngModel)]="selected"/>`
})
export class MyComponent(){
public selected: boolean = false;
}

How to hide a text field in play framework

How to hide a text field in play framework? For example how to hide this field:
#inputText(userProfileForm("name"), '_label -> "Name")
This should work in all browsers:
#inputText(
userProfileForm("name"),
'_label -> "Name",
'style -> "display: none"
)
Note that this only hides the field, not the label etc.
If you want to hide the label aswell, you can't do this with the default helpers.
You can however specify the input field yourself:
<input type="hidden" name="name" value="#userProfileForm.data.get("name")" />
The name should be name of the field in your form (coincidentally name aswell in this case).
I haven't tested the value but it should work, maybe you'll need to strip the " around name.
If you do this, the hidden data will be sent, along with the other data in the form to the server.
Edit:
If the hidden value is empty, that means you didn't bind it to the form when calling the view. You can bind the name to the form like this in Java (I don't know Scala, but it's explained in the Play Scala documentation):
Map<String, String> data = new HashMap<>();
data.put("name","get the username here");
return ok(index.render(userProfileForm.bind(data));
Another option (which is cleaner in my opinion) is to simply pass the username as an argument to the view. The controller becomes:
return ok(index.render(userProfileForm, "username goes here"));
And in the view you can then simply do:
#(userProfileForm : Form[UserProfileForm])(name : String)
#helper.form(...){
<input type="hidden" name="name" value="#name" />
//...
}
The inputText helper takes a varargs of (Symbol, Any), which represent the html attributes. If you are using html5 you can just add the hidden attribute:
#inputText(userProfileForm("name"), '_label -> "Name", 'hidden -> "hidden")
normally the hidden attribute has no value, but I couldn't find any information about how to do this with the helpers. In Chrome at least it works like this as well.
edit:
btw, you can also just use html instead of the helper:
<input attribute=value hidden />
I know that this is an old question, but i had a similar issue, i wanted to hide an inputText and still, handle it using the helpers.
The best and cleanest way to do it is to write your own helper adding a custom value to tell when to hide the element itself.
I came to a solution like this
my own field constructor
#(elements: helper.FieldElements)
#if(elements.args.contains('hideIt)){
#elements.input
}else{
<div class="#if(elements.hasErrors) {error}">
<div class="input">
#elements.input
<span class="errors">#elements.errors.mkString(", ")</span>
<span class="help">#elements.infos.mkString(", ")</span>
</div>
</div>
}
that i used in the view file like this:
#inputText(form("fieldName"),
'hidden -> "true",
'hideIt -> true
)
now you are done :)
While it worked, I didn't like the hashmap version provided by #Aerus, preferring to use the statically typed forms when possible, so I came up with an alternative.
final UserProfileForm initial = new UserProfileForm("get the username here");
return ok(index.render(Form.form(UserProfileForm.class).fill(initial));
Then, in the profile, you can do as follows:
<input type="hidden" name="name" value="#userProfileForm("name").value" />

jQuery Stop .blur() event when clicking "submit" button

I am building a small landing page with a simple demo e-mail signup form. I want to have the form field open up when focused, and then shrink back down on blur.
However the problem I'm facing is when you click the submit button this instigates the blur function, hiding the button and shrinking the form. I need to find a way to stop the .blur() method only when the user is clicking to focus on the submit button. Is there any good workaround for this?
Would appreciate any help I can get!
I know this question is old but the simplest way to do it would be to check event.relatedTarget. The first part of the if statement is to prevent throwing an error if relatedTarget is null (the IF will short circuit because null is equivalent to false and the browser knows that it doesn't have to check the second condition if the first condition is false in an && statement).
So:
if(event.relatedTarget && event.relatedTarget.type!="submit"){
//do your animation
}
It isn't the prettiest solution, but it does work. Try this:
$("#submitbtn").mousedown(function() {
mousedownHappened = true;
});
$("#email").blur(function() {
if (mousedownHappened) // cancel the blur event
{
mousedownHappened = false;
}
else // blur event is okay
{
$("#email").animate({
opacity: 0.75,
width: '-=240px'
}, 500, function() {
});
// hide submit button
$("#submitbtn").fadeOut(400);
}
});​
DEMO HERE
Try this inside .blur handler:
if ($(':focus').is('#submitbtn')) { return false; }
why not rely on submit event instead of click? http://jsbin.com/ehujup/5/edit
just couple changes into the html and js
wrap inputs into the form and add required for email as it obviously suppose to be
<form id="form">
<div id="signup">
<input type="email" name="email" id="email" placeholder="me#email.com" tabindex="1" required="required">
<input type="submit" name="submit" id="submitbtn" value="Signup" class="submit-btn" tabindex="2">
</div>
</form>
in js, remove handler which listen #submitbtn
$("#submitbtn").on("click", function(e){
e.stopImmediatePropagation();
$("#signup").fadeOut(220);
});
and use instead submit form listerer
$("#form").on("submit", function(e){
$("#signup").fadeOut(220);
return false;
});
you may use $.ajax() to make it even better.
Doing this you gain point in terms of validation and the native browser's HTML5 validator will make check email format where it is supported.

Programmatical changes will not reflect in knockout viewmodel

To change the status of a checkbox with javascript doesn't correspond to the spirit of MVVM. But I'm creating a general javascript library for better looking standard controls like checkbox, radio button or selectbox.
Based on the following viewmodel:
function MyViewModel() {
var self = this;
self.ok = ko.observable();
};
var vm = new MyViewModel();
ko.applyBindings(vm);
But I get a problem in conjunction with knockout when I change the checked status of a checkbox programmatically:
document.getElementById('chk').checked = true
The change will not appear in the property of the viewmodel. But when I click the checkbox all works fine.
Look at http://jsfiddle.net/KWdZB/1/
Is there any workaround?
Your problem is that ko subscribes on the click event inside the checked binding:
ko.utils.registerEventHandler(element, "click", updateHandler);
But changing the checked attribute won't trigger the click event so ko won't be notified.
If you manually trigger the click event after the attribute change it can work...
I don't know how to do it with pure javascript but with jQuery you can write:
$('#chk').attr('checked', true).triggerHandler('click')
You can test it in this JSFiddle.
This is normal because the checked binding handlers doesn't subscribe to the checked change event but subscribe to the click event handler (You can see on source file at the checked binding handlers code).
If you need to change value with click, you must to do with the ok observable value.
There is the HTML
<div>
<input type="checkbox" id="chk" data-bind="checked: ok"/><br>
<input type="button" id="btnCheck" value="Check" data-bind="click: Check"/>
<input type="button" id="btnUnCheck" value="Uncheck" data-bind="click:Uncheck"/>
</div>
<div>
Value: <span data-bind="text: ok"></span>
</div>
And the javascript :
function MyViewModel() {
var self = this;
self.ok = ko.observable();
self.Check = function(){
self.ok(true);
}
self.Uncheck = function(){
self.ok(false);
}
};
vm = new MyViewModel();
ko.applyBindings(vm);
​
​
You can see it in this fiddle.