How to get input value in Ember.js app? - forms

What's the best solution of getting input value from Ember.TextField, after the button has been submitted?
Assume I have simple app for sending messages. I specified a view which represents input form where the user enters his message:
App.TextView = Ember.View.extend({
templateName: 'text',
submit: function(event) {
console.log(event);
}
});
Then, there is Handlebars template for this view:
<script type="text/x-handlebars" data-template-name="text">
<h1>Send the message:</h1>
<div class="send_form">
{{view Ember.TextField}}
<button type="submit">Done</button>
</div>
</script>
Basically, I need just one thing. When the user clicks on the button, I need to be notified (in the submit function or anywhere else in my app) and I need to grab the value from the TextField. How can I achieve that?

You could for example bind the value of the text field to a message property in the view.
Perhaps there is other solution, but I think this quite simple: http://jsfiddle.net/Sly7/vfaF3/
<script type="text/x-handlebars">
{{view App.TextView}}
</script>
<script type="text/x-handlebars" data-template-name="text">
<h1>Send the message:</h1>
<div class="send_form">
{{view Ember.TextField value=view.message}}
<button type="submit" {{action "submit" target=view}}>Done</button>
</div>
</script>​
App = Ember.Application.create({});
App.TextView = Ember.View.extend({
templateName: 'text',
message: '',
actions: {
submit: function(event) {
console.log(this.get('message'));
}
}
});

Related

Use two buttons in the same form for invisible recaptcha

I'm trying to implement the new invisible recaptcha, from Google.
It's all working perfectly, but my forms always have two submit buttons, that does different things with the input.
I tried to simply add another in my form, but google only recognize the first one in code.
I can't think of any reason that would prevent the other button to work properly. Here is a simple example of what I tried :
<form action="page.php" method="POST">
<input type="text" value="textfield"/><br/>
<button class="g-recaptcha" data-sitekey="mysitekey" data-callback='onSubmit' value="anaction">An action</button>
<button class="g-recaptcha" data-sitekey="mysitekey" data-callback='onSubmit' value="anotheraction">Another action</button>
</form>
I usually tell apart the two buttons by making an isset on the POST values. Here it doesn't seem to work with the second button. If I switch the two lines, it will make the other button submit properly.
If someone has an idea about this, I'll thank him for enlightments.
Thank you :)
I had same issue and I fixed it like below:
<button type="submit" class="g-recaptcha"
id="captcha1"
data-sitekey="YOUR_SECRETKEY"
data-callback="sendData">button</button>
<button type="submit" class="g-recaptcha"
id="captcha2"
data-sitekey="YOUR_SECRETKEY"
data-callback="sendData">button</button>
<script type="text/javascript">
$( document ).ready(function() {
$(".g-recaptcha").each(function() {
var object = $(this);
grecaptcha.render(object.attr("id"), {
"sitekey" : "YOUR_SITEKEY",
"callback" : function(token) {
object.parents('form').find(".g-recaptcha-response").val(token);
object.parents('form').submit();
}
});
});
}
);
</script>
Yes I created a function sendData like below:
<script type="text/javascript">
function sendData(){
var test = $("#test").val();
if(test != ""){
$.post( "page.php",
{ 'g-recaptcha-response': grecaptcha.getResponse(), 'test' : test})
.done(function( data ) {
console.log(data);
}
);
}else{
console.log(data);
}
grecaptcha.reset(); //important
}
</script>
Stash the token in a hidden field and use it instead of the g-recaptcha-response value to send your verification request. You can distinguish between the two submissions by saving the action item in the JSON return object. I have no idea why this works, by the way.
<head>
...
<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
function onSubmit(token) {
document.getElementById("token").value = token;
document.getElementById("form").submit();
}
</script>
...
</head>
<body>
...
<form id="form" action="page.php" method="POST">
<input type="hidden" id="token" name="token">
...
<button type="submit" class="g-recaptcha" data-sitekey="..." data-callback="onSubmit" data-action="action">An Action</button>
<button type="submit" class="g-recaptcha" data-sitekey="..." data-callback="onSubmit" data-action="anotheraction">Another Action</button>
</form>

Use code captcha in two forms

I have two forms on a page containing Google captcha code, but only one code works. Does anyone know if you can use the same code with the same key on two forms on the same page?,
Thks,
Yes, you can. But you have to explicitly render the widget as mentioned on the developer guide
you should use something like this on your front end(taken from the developer guide):
<html>
<head>
<title>reCAPTCHA demo: Explicit render for multiple widgets</title>
<script type="text/javascript">
var verifyCallback = function(response) {
alert(response);
};
var widgetId1;
var widgetId2;
var onloadCallback = function() {
// Renders the HTML element with id 'example1' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'widgetId1'.
widgetId1 = grecaptcha.render('example1', {
'sitekey' : 'your_site_key',
'theme' : 'light'
});
widgetId2 = grecaptcha.render(document.getElementById('example2'), {
'sitekey' : 'your_site_key'
});
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
</head>
<body>
<!-- The g-recaptcha-response string displays in an alert message upon submit. -->
<form action="javascript:alert(grecaptcha.getResponse(widgetId1));">
<div id="example1"></div>
<br>
<input type="submit" value="getResponse">
</form>
<br>
<!-- Resets reCAPTCHA widgetId2 upon submit. -->
<form action="javascript:grecaptcha.reset(widgetId2);">
<div id="example2"></div>
<br>
<input type="submit" value="reset">
</form>
<br>
<!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>
I just wanted a HTML snipped which I can insert multiple times, each time displaying another captcha. Also, I did not want to take care for specific IDs assigned to the containers, which would be very annoying when multiple formulars still appearing on one page will be designed and rendered independently. Here is my solution.
<div class="g-recaptcha"></div>
<script type="text/javascript"><![CDATA[
function renderCaptchas() {
var captchaNodes = document.getElementsByClassName('g-recaptcha');
for (var i = 0; i < captchaNodes.length; i++) {
var captchaNode = captchaNodes[i];
if (!captchaNode.captchaRendered) {
captchaNode.captchaRendered = true;
grecaptcha.render(captchaNode, {"sitekey": "YOUR_SITE_KEY"});
}
}
}
]]></script>
<script src="https://www.google.com/recaptcha/api.js?onload=renderCaptchas&render=explicit" async="async" defer="defer"></script>

Backbone.js and form input blur

I am pretty much a backbonejs newbie. I am submitting form data to mysql.
I have one special input box where the use types in his or her email address as a user name.
As it stands, I can check all my input fields (user, pass, address, phone, etc) client
side, use an event on a button, load the model, use PHP to put the data into the db.
This works just fine and is tested. The backend validation works fine and feeds to
the browser when necessary.
Now I want to check the loginname field against the back end BEFORE writing the record (I know I can trap this on the back end in the final submit but want to do it here). If the user already has an account with the same email address I want to catch that client side. The issue is I can't seem to find a way to capture this blur (or onblur or change whatever I use) when I move off the loginname field so I can (in the render of the view is all I can figure) go off, use PHP again and send back a flag "new" or "existing"
No errors in Google developer tool
define([
'jquery',
'underscore',
'backbone',
'lib/jquery-migrate-1.2.1',
'models/RegisterModel',
'text!templates/RegisterTemplate.html',
'lib/jquery.maskedinput-1.0',
'lib/bootstrap-acknowledgeinput.min',
'lib/jqBootstrapValidation'
], function($, _, Backbone, jQueryMigrate, RegisterModel, RegisterTemplate,
MaskedInput,Ack, jqAck){
var RegisterView = Backbone.View.extend({
el: $("#container"),
events: {
'click .btn-primary': 'saveClient',
'focusout .loginname': 'usercheck'
},
usercheck: function() { //** not working
console.log("usercheck detected");
alert("Alerts suck.");
},
render: function(){
//Since our template has dynamic variables in it, we need to compile it
var compiledTemplate = _.template( RegisterTemplate, this.model );
this.$el.html(compiledTemplate); //Replaces EVERYTHING inside the <div
id="container">
this.$('#phone').mask('(999) 999-9999');
this.$('#phone2').mask('(999) 999-9999');
this.$('#zip').mask('99999');
$(function () { //** working
$("input,select,textarea").not("[type=submit]").jqBootstrapValidation();
});
$('.loginname').live("click", function () { //** not working
alert('AHHHHHH!');
});
$().acknowledgeinput({ // ** this works fine
success_color: '#00FF00',
danger_color: '#FF0000',
update_on: 'keyup'
});
** I looked in Chrome at the blur event for the input with name/id = loginname
HTML I did look at the blur for the elmement with id (Chrome says it's input#loginname)
does have the blur event attached to it. I changed my code a bit, but still it doesn't seem to trigger. I never know with backbone if it's just something simple or one of those
"this and scope" issues :)
<div id="container" class="row-fluid">
<div class="span6">
<div class="requiredNotice"><i class="icon-warning-sign icon-red"></i> Can't
be blank!</div>
<h3>New Client Registration:</h3>
<form class="form-horizontal" method="POST">
<fieldset>
<div class="control-group">
<label class="control-label required" for="loginname">UserID (Email
</label>
<div class="controls">
<div class="input-prepend" data-role="acknowledge-input">
<div data-role="acknowledgement"><i></i></div>
<input type="email" data-type="email" required="required"
placeholder="Use email account"
maxlength="254" name="loginname" id="loginname"
class="inputclass pageRequired
input-xlarge" />
</div>
<span class="loginname_error label label-info hide"></span>
</div>
</div> ... etc
events: {
'click .btn-primary' : 'saveClient',
'focusout #input.loginname' : 'userCheck'
// "blur input.loginname" : "userCheck"
},
userCheck: function(e) {
console.log("usercheck detected");
alert("Alerts suck.");
},
.live is not needed here, there is nothing wrong with your event hash as well. There could be some thing wrong with template. I did just isolate the input field and focusout event in this jsfiddle it's working fine.
<script type="text/template" id="formtemplate">
<form>
<input type="text" class="loginname" value="" placeholder="enter login"/>
</form>
</script>
...
var View = Backbone.View.extend({
events:{
'focusout .loginname':'checkUser'
},
render:function(){
this.$el.html($('#formtemplate').html());
},
checkUser:function(e){
alert('checkUser'); //works well
}
});
var view = new View();
view.render();
view.$el.appendTo('body');
Okay - you said to tie this to blur, and this format finally worked!
'blur input#loginname' : 'userCheck'
events: {
'click .btn-primary' : 'saveClient',
'blur input#loginname' : 'userCheck'
},
userCheck: function(e) {
console.log("usercheck detected");
alert("Alerts suck.");
},
The console is not showing up, but at least I'm trapping the blur now! Thanks eveyone.

submit form using link tag with angularjs

I'm still new with angularJS. I've been trying to make a custom button and attach it to my form instead of using regular button. I've tried couple of approaches and so far none of them worked well. now when I press enter inside the input field I get the "results" view perfectly loaded to the main page. but when I click the search button "a" link tag the view loads then disappears instantly. as well as the location of the browser changes to "results" then goes back to "/#/" only. I have no idea why and what's causing this.
here's my html:
<div id="search-container" ng-controller="SearchController">
<form ng-submit="submitQuery()">
<div>
<input id="keywords" name="keywords" ng-model="query.keywords" placeholder="please enter query" value="" required/><br>
<img src="/Images/search-icon.png" alt="Search" title="Search" />
</div>
</form>
</div>
here is my model and ngjs controllers:
var bfapp = angular.module("blogfinder", []).config(function ($routeProvider) {
$routeProvider.when('/results', {
templateUrl: 'PartialViews/results.html',
controller: 'ResultsController'
});
$routeProvider.otherwise({ redirectTo: '/' });
});
bfapp.controller('ResultsController', function ($scope) {
});
bfapp.controller('SearchController', function ($scope, $location) {
$scope.query = { keywords: "" };
//on form submit
$scope.submitQuery = function () {
if ($scope.query.keywords !== null) {
$location.path('/results');
}
};
//on button click
$scope.submitForm = $scope.submitQuery;
});
well I feel so stupid. I've just found the solution after banging my head for couple of hours. Although this has never been mentioned on any site. All I needed is to remove "#" from <a href="#" id="search-btn" ng-click="submitForm()">. Now it works like charm.

Submit selection on Bootstrap typeahead() autocomplete?

How do I autosubmit the selection made with Twitter Bootstrap typeahead()??
http://twitter.github.com/bootstrap/javascript.html#typeahead
There is a clean way using the updater callback:
input.typeahead({
'source' : ['foo', 'bar'],
'updater' : function(item) {
this.$element[0].value = item;
this.$element[0].form.submit();
return item;
}
});
When user selects an option (either by mouse click or keyboard), the callback populates the input box and sends the form.
If you use the external typeahead.js plugin (recommended for Bootstrap 3):
To trigger a form on select just use the custom events.
$('#my-input')
.typeahead({/* put you options here */})
.on('typeahead:selected', function(e){
e.target.form.submit();
});
More info on custom events here and demo about JSfiddle.
Might not be the best solution, but I just tried this on my typeahead setup locally and it worked.
If your typeahead looks something like this...
<form id="test-form" method="post" action="">
<input id="test-input" type="text" data-provide="typeahead"
data-source='["1","2',"3"]' />
</form>
Then you can submit it with this javascript.
<script type="text/javascript">
$('#test-input').change(function() {
$('#test-form').submit();
});
</script>
Apparently there are a few git merge requests. This one does the job and allows you to send an array of objects to typeahead: https://github.com/twitter/bootstrap/pull/1751
I added a blur callback on the input. Be aware that you need to wait for a short period, that typeahead can change the value in the input and the blur callback is not called before that. It's just a workaround, but it works.
$('input.myTypeaheadInput').blur(function(e) {
window.setTimeout(function() {
window.console && console.log('Works with clicking on li item and navigating with the keyboard. Yay!');
}, 50);
});
To populate a value of a hidden field in an html form from the typeahead data selection, I did the following:
$('#prefetch').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'trees',
source: trees,
limit: 15
}).on('typeahead:selected', function(e) {
var result = $('#prefetch').val()
$('#formpane input[name=\"myID\"]').val(result)
});
For reference, here's the html code:
<body>
<div id="formpane">
<form action="/thanks" method="POST">
<input class="typeahead" type="text" placeholder="select categories" id="prefetch">
<button type="submit">Submit</button>
<input type="hidden" name="myID" />
</form>
</div>
<script type="text/javascript" src="js_file_above.js"></script>
</body>