How to save form data in a cookie (dojo) - cookies

I have a contact form where users will enter their details like name, address, phone and so on. Now I have a checkbox (remember me) on the form.. whenever the user checks this, the information should be saved in a cookie and retrieved when the same user visits later. This is how i started..
<tr><td><input id="mycheck" name="mycheck" data-dojo-type="dijit.form.CheckBox" value="" checked="false" onChange="setCookie" > <label for="mycheck" >Remember me </strong></label></td></tr>
setCookie: function () {
cookie("UserInfo", "cookieValue", { expire: 5 });
},
How do i get the cookie values (this should be whole forms data..do i need to use something like byId)...confused..any ideas??
Thanks

see http://dojotoolkit.org/reference-guide/1.7/dojo/cookie.html
if using > 1.7 you should pull in the required module and use it by reference (as it looks like youre doing):
NOTE is not {expire:X} but {expires :x}
<script>
require(["dojo/cookie"], function(cookie){
/* set */
cookie(cookieName, cookieValue, cookieProps);
/* get */
cookie(cookieName);
});
</script>
You can use dojo/dom-form module to pull values and save them for a neet one-liner
<form id="myform">
<input type="text" name="field1" value="value1">
<input type="text" name="field2" value="value2">
<input type="button" name="someButton" value="someValue">
</form>
<script>
require(["dojo/dom-form", "dojo/cookie"], function(domForm, dCookie){
dCookie(
"formdata",
domForm.toJson("myId"),
{expires: 5}
);
// The cookie will read: '{"field1":"value1", "field2":"value2"}'
// Note the button was skipped.
// Buttons only gets sent when used as submitbutton + onclick
});
</script>

Serialize the value to JSON then undo it when you retrieve like so:
//Setting the cookie to hold an array of values.
value = {my:"1",cookie:"2"};
dojo.cookie("myCookie", dojo.toJson(value), {expires: 30});
//Retrieving the cookie.
newValues = dojo.fromJson(dojo.cookie("myCookie"));

Related

What's the pattern attribute in paper-input-container?

I want to auto-validate the input in some <paper-input-container>'s <input is="iron-input"> field, so that it follows a dd.mm.yyyy pattern. Can I do this with the pattern attribute?
I tried pattern="^(\d{2}).\d{2}.(\d{4})$" and pattern="(1-9|0[1-9]|1[0-9]|2[0-9]|3[0-1]).([1-9]|0[1-9]|1[0-2]).(20[1-3][0-9])" together with allowed-pattern="[\d.]", but that doesn't work.
Is the pattern attribute meant to support this use case?
The <paper-input>.pattern is ignored unless you do one of the following:
Enable automatic input validation with <paper-input>.autoValidate
<paper-input auto-validate
pattern="^(\d{2}).\d{2}.(\d{4})$">
</paper-input>
codepen
Manually call <paper-input>.validate() (e.g., on button click)
<paper-input id="input" pattern="..."></paper-input>
<button on-tap="_validateInput">Validate</button>
// script
_validateInput: function() {
this.$.input.validate();
}
codepen
Set <paper-input>.required, and use an <iron-form> wrapper, which automatically calls <paper-input>.validate() on submit
<form id="form" is="iron-form" ...>
<paper-input required
pattern="..."></paper-input>
<button on-tap="_submit">Submit</button>
</form>
// script
_submit: function() {
this.$.form.submit(); // <-- auto validates required form inputs
}
codepen

How to clear the typeahead input after a result is selected?

I'm using the ng-bootstrap typeahead component to search a customer database. When the user selects a customer from the typeahead results list, I navigate to a customer details page. I've got this working, but I want to clear the input field after navigation has taken place. I've tried setting the model to null or an empty string in the selectItem event logic, but this isn't working:
customer-search-typeahead.component.html
<template #resultTemplate let-r="result" let-t="term">
<div>
<div>
{{r.resource.name[0].given}} {{r.resource.name[0].family}}
</div>
<div>
{{r.resource.birthDate | date: 'dd/MM/yyyy'}}
</div>
</div>
</template>
<input type="text" class="form-control" [resultTemplate]="resultTemplate" (selectItem)="onSelect($event)"
[(ngModel)]="model" placeholder="Start typing a customer name..." [ngbTypeahead]="search"/>
customer-search-typeahead.component.ts
#Component({
selector: 'customer-search-typeahead',
template: require('./customer-search-typeahead.component.html'),
styles: [`.form-control { width: 300px; }`]
})
export class CustomerSearchTypeaheadComponent {
model: any;
searching: boolean;
constructor(private customerService: CustomerService, private router: Router) {}
onSelect($event) {
this.router.navigate(['/customers', $event.item.resource.id]);
this.model = null;
};
search = (text$: Observable<string>) =>
//omitted for brevity
}
The typeahead input looks like this after a selection has been made:
Solution
customer-search-typeahead.component.html
<input type="text" class="form-control" #input [ngbTypeahead]="search" (selectItem)="onSelect($event); input.value='' ">
customer-search-typeahead.component.ts
onSelect($event, input) {
$event.preventDefault();
this.router.navigate(['/customers', $event.item.resource.id]);
};
The issue you witnessing arises from the fact that the NgModel directive is updating model binding asynchronously and the actual model is updated after the onSelect method gets executed. So your model update gets overridden by the NgModel functionality.
Fortunately we (ng-bootstrap authors) got all the flex points in place to cover your use-case :-) There are a couple of things that you could do.
Firstly the $event object passed to the onSelect method has the preventDefault() method and you can call it to veto item selection (and as a result writing back to the model and input field update).
$event.preventDefault() will make sure that the model is not updated and the input field is not updated with the selected item. But text entered by a user will still be part of the input so if you want to clear up this as well you can directly update the input's value property.
Here is code demonstrating all those techniques together:
onSelect($event, input) {
$event.preventDefault();
this.selected.push($event.item);
input.value = '';
}
where input argument is a reference to the input DOM element:
<input type="text" class="form-control" #input
[ngbTypeahead]="search" (selectItem)="onSelect($event, input)">
Finally here is a plunker showing all this in practice: http://plnkr.co/edit/kD5AmZyYEhJO0QQISgbM?p=preview
The above one is template ref value solution.
This is for ngModel solution.
Html code:
<input type="text" class="form-control" [resultTemplate]="resultTemplate" (selectItem)="onSelect($event)"
[(ngModel)]="model" placeholder="Start typing a customer name..." [ngbTypeahead]="search"/>
Component code:
onSelect($event) {
$event.preventDefault();
this.model = null;
this.router.navigate(['/customers', $event.item.resource.id]);
};
$event.preventDefault();
for ngModel value change empty

How to submit a CFInput type=file within a CFDiv container

I am submitting a file in a cfdiv container, but the value of the file is not submitting to the processing page. If I submit the file outside of the cfdiv, it sees the file value. However, if the file is inside a cfdiv or div container, the form field is undefined. I have also added the enctype="multipart/form-data" to the cfform, but it is still not working.
UPDATE:
This is the first page (index.cfm)
<div name="loadcontainer" id="loadcontainer">
<cfinclude template="homepage.cfm">
</div>
The homepage.cfm
<cfform name="school_create" id="school_create"
action="pro_create_school.cfm"
enctype="multipart/form-data"
method="post">
<cfinput size="50" type="file" id="school_logo" name="school_logo">
<button type="submit">Save</button>
</cfform>
When the save button is clicked, it doesn't see the form.school_logo value in the action processing page.
I have also tried using a normal form and input, instead of a cfform/cfinput, but the form is being loaded into another tab when submitted, instead of the div container.
"File" is an incorrect "type" for a CFINPUT in earlier CF Versions (not sure what version you are using). I did check the docs and it is allowed in current versions.
Meanwhile, Instead change your CFINPUT to:
<input size="50" type="file" id="school_logo" name="school_logo">
Or better yet, get rid of <cfform> - you aren't using it for anything and you don't need it. A good JS library (jquery) will provide you with better functionality for validation etc.
In this case you could easily do:
<form name="school_create" id="school_create"
action="pro_create_school.cfm"
enctype="multipart/form-data"
method="post">
<input size="50" type="file" id="school_logo" name="school_logo">
<button type="submit">Save</button>
</form>
And it would work as expected. Cfform is designed to provide simple validation functions in a native CF Fashion, but outside of tutorials and books explaining CFML almost no one uses it. When we see it used here at CF Webtools, we refactor it as soon as we are able.
I was able to Submit the form both the <cfinput type="file"..../> and other form field in the form with ajax.
<script>
function validateForm() {
var x = document.forms["add_academic_year"]["start_year"].value;
var y = document.forms["add_academic_year"]["end_year"].value;
if (x == null || x == "" || y == null || y == "") {
alert("Start Year and End Year Must be Selected");
return false;
}
if (y <= x) {
alert("End Year must be greater than Start Year ");
return false;
}
console.log("submit event");
var fd = new FormData(document.getElementById("add_academic_year"));
$.ajax({
url: "pro_academic_year.cfm",
type: "POST",
data: fd,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function( response ) {
// display response in DIV
$("#loadcontainer").html( response.toString());
})
.fail(function(jqXHR, textStatus, errorMessage) {
// display error in DIV
$("#outputf").html(errorMessage);
})
return false;
}
</script>

Inputs on Ember refresh page when a user hits Enter key

I'm using Ember CLI and have noticed odd behaviour. When the user clicks into the input and presses the enter key, the page refreshes.
My page has a basic element like this that is NOT part of any form:
<input type="text" class="form-control" id="per_page" value="50">
I am currently serving the page via:
ember cli
So node is hosting and has the fancy live reload thing going on so that when I update a page that is part of the underlying app.
So what is causing a page reload the enter key pressed inside an input? Could it be node or live reload? Are inputs just supposed to refresh a page when a user presses the enter key and I missed that in my HTML for dummies book?
**Better still, how can I intercept and instead call a function via:
{{action** "myFunction"}}
That happens because when you hit Enter, form gets submitted which results in page reload. what you need to do is set onsubmit="return false" on the form so nothing happens during submit. you can bind input to execute some action by adding action attribute action="doSomething"
<form onsubmit="return false">
{{input type="text" action="createComment" value=topic id="inputTopic"}}
</form>
Edit: In Ember 3+ you now use the {{on}} modifier to setup events on elements.
<form {{on 'submit' this.submitForm}}>
<!-- the rest of your form here -->
<button type='submit'>Submit</button>
</form>
And the action defined like so
#action
submitForm(event) {
event.preventDefault();
// Your code
}
Historically Ember has handled this use case with the following code:
<form {{action 'submitForm' on='submit'}}>
<!-- the rest of your form here -->
<button type='submit'>Submit</button>
</form>
This prevents the form from refreshing the page.
There is another method that gives you more control, by giving you the event so you can manage that yourself:
<form onsubmit={{action 'submitForm'}}>
<!-- the rest of your form here -->
<button type='submit'>Submit</button>
</form>
In this case, you will get an event and will have to call event.preventDefault() to stop the page refresh.
actions: {
submitForm(event) {
event.preventDefault();
}
}
This is a running example of the two: https://ember-twiddle.com/827820958e054f7af57b7677630729fc?openFiles=controllers.application.js%2C
I had the same problem - what worked for me, was to overwrite the keyPress Event in the input component like this:
keyPress: function (e) {
var keyCodeEnter = 13;
if (e.keyCode === keyCodeEnter) {
return false;
}
}
Hope it will help someone in the future! :)

How to Defer Ember views from synchronously updating from bound input fields

Let's say I have a group of editable users, when one goes to edit that user, ember will synchronously update all views as you type into the bound input text field.
This is cool and all but from an UX point of view it can be misleading.. those values hadn't changed on the server at all.. What I'd like to do is to defer the view update until I set it in the corresponding action method based on a success message from the server.
I have found that when I use {{bind-attr value=firstName}} instead of {{input value=firstName}} that indeed ember no longer updates the view on changing the input field, however the newly typed value is no longer accessible in the actions submit method via this.get('firstName')?
Example.hbs
<script type="text/x-handlebars" id="user">
<h3>Edit {{fullName}}</h3>
<p>
<label>First Name</label>
{{input value=firstName}}
</p>
<p>
<label>Last Name</label>
<input {{bind-attr value=lastName}} />
</p>
<p>
<button {{action 'submit'}}>Submit</button>
</p>
</script>
Example Controller
App.UserController = Ember.ObjectController.extend({
actions: {
submit: function(){
// call to server, on confirmation set 'Globally' first and last names
console.log(this.get('firstName') + " - " + this.get('lastName'));
}
}
});
Here's my jsbin:
http://jsbin.com/jipik/2/edit?html,js,console,output
All you need is a secondary set of variables. Add to your controller a variable named firstNameEdited and set its value initially to firstName. Value bind your input field to this new value and submit this new value to your api call. On a successful return of the API call, update firstName with the value of firstNameEdited.