submit form using link tag with angularjs - forms

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.

Related

Why Is my script freezing up when I hit enter?

The majority of the Add-on is good but whenever I hit enter (which is, in my opinion, the most common way to submit a form, for example, a login form), but all it does is blank out.
I've tried linking the script with a onkeydown like so:
<div onkeydown="handle(event)">blagh blagh blagh</div>
but I still get the same results:
<html>
<form id='myForm' style="font-family:Georgia;">
<table>
<tr><td><h2>Enter your Password</h2></td></tr>
<tr><td><p>DO NOT HIT ENTER ON YOUR KEYBOARD!!!!!</p></td></tr>
<tr><td><input name='password' type='password' value="" onkeypress="handle(event)"></td></tr>
<tr><td><div id="submitbuttcontainer"><img id="submitloader" style="display:none;" src='https://lh6.googleusercontent.com/-S87nMBe6KWE/TuB9dR48F0I/AAAAAAAAByQ/0Z96LirzDqg/s27/load.gif' /><input id="submitbutt" type='button' onclick='showWorking();google.script.run.withSuccessHandler(onSuccess).decodeForRequest(document.getElementById("myForm"));' name="Submit" value="Submit"></div></td></tr>
</table>
</form>
<script>
function onSuccess(obj) {
document.getElementById('submitbutt').style.display="block";
document.getElementById('submitloader').style.display="none";
if(obj.status == 'success') {
google.script.host.closeDialog();
browser.msgbox('Access Granted', browser.buttons.OK)
}
else {
browser.msgbox('ALERT!!','!OOF!','Incorrect Password. Please retry', browser.buttons.OK);
}
}
function showWorking() {
document.getElementById('submitbutt').style.display="none";
document.getElementById('submitloader').style.display="block";
}
function handle(e){
if(e.keyCode === 13)
document.getElementById('submitbuttcontainer').click();
}
</script>
</html>
All I'm trying to do is get the form to submit when I hit enter and not blank out. I always hit enter to submit a form but in this case all it does is blank out the form and all I have is whiteness.
Here's the link for the complete source code (don't know if this will work because I'm in a school district):
https://script.google.com/a/bcsdschools.net/d/1_YUx4ZP3qEWVcFMc-MvfEYX2S34r7-b4M0iRlE_JQa81T3ZubN5OeISa/edit)
Problem
Hitting enter key results in form submission (which is explicitly forbidden in Apps Script due to its client-to-server communication implementation).
Solution 1 - handle inputs individually
Add preventDefault() to a keydown event if key is enter (btw, keypress event is deprecated, see reference on MDN, use the keydown / keyup instead):
var ENTER_CODE = 13;
function handle(e) {
if(e.keyCode === ENTER_CODE) {
e.preventDefault();
document.getElementById('submitbuttcontainer').click();
}
}
Solution 2 - handle form submit
You can listen for a submit event on your form instead and invoke preventDefault() as the only statement in event handler or handle form submission at the same time if you expect form to be submitted on enter key hit:
//assumption: form is initiated elsewhere in code;
form.addEventListener('submit', (event) => {
event.preventDefault();
//handle submission;
});
You can also prevent all forms from being submitted to make the setup flexible:
(() => {
const { forms } = document;
Object.values(forms).forEach(
form => form.addEventListener("submit", (e) => e.preventDefault())
);
})();
Or, alternatively, use event delegation and register one listener on the document since the event bubbles up:
document.addEventListener("submit", (e) => e.preventDefault());
Suggestion
Please, use addEventListener instead of on[event name here] attributes. This way is much more flexible and has the benefit of being concise and easy for others to read.
References
Handling forms in Apps Script guide
Why use addEventListener? MDN reference
I wanted to try to give you a complete answer, but I have to admit that I may know less about event handlers than you. But this seems to work for me.
aq4.html:
<html>
<head>
<script>
window.onload=function() {
preventFormSubmit1();
}
function preventFormSubmit1() {
console.log('preventFormSubmit1');
var form=document.forms['myForm'];
form.addEventListener('submit',function(e) {
e.preventDefault();
});
}
function handleFormSubmit(formObject) {
console.log('handleFormSubmit');
var first=document.forms['myForm']['first'].value;
var last=document.forms['myForm']['last'].value
var sheet=document.forms['myForm']['sheet'].value;
console.log('%s,%s,%s',first,last,sheet);
if(first.length>0 && last.length>0 && sheet.length>0) {
google.script.run
.withSuccessHandler(function(msg){
var div=document.getElementById('output');
div.innerHTML=msg;
var inputs=document.querySelectorAll('input[type=text]');
inputs[0].focus();
for(var i=0;i<inputs.length;i++) {
inputs[i].value='';
}
})
.processForm(formObject);
}else{
alert("Invalid or Incomplete Data");
}
}
console.log("MyCode");
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit(this)">
<input type="text" name="first" /> First<br />
<input type="text" name="last" /> Last<br />
<select name="sheet">
<option value="Sheet1">Sheet1</option>
<option value="Sheet2">Sheet2</option>
</select> Sheet<br />
<input id="sub" type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
aq1.gs:
function processForm(formObject) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(formObject.sheet);
sh.appendRow([formObject.first,formObject.last]);
return Utilities.formatString('First: %s<br />Last: %s<br />Sheet: %s', formObject.first,formObject.last,formObject.sheet);
}
function runOne() {//This loads the dialog
var userInterface=HtmlService.createHtmlOutputFromFile('aq4').setWidth(1000);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "My Form Example")
}

drupal 7 prevent redirect in modal window (ctools) when submit

I have placed a form (built with entityform) into a modal (ctools modal) using jquery.
Now, what happens is that when I click on the "submit" button, I get redirected to another page where I display the "success" message.
I'd like to avoid the redirect and display the "success" message within the modal (in the same page where the modal pop up).
Thanks in advance.
This is the jquery I used to launch the modal on click:
(function ($) {
Drupal.behaviors.tuo = {
attach: function (context, settings) {
$('#comments_button', context).click(function () {
$('#suggerimenti').dialog('open');
$('.ui-dialog-titlebar').append($('h2', '#block-views-invio-suggerimenti-block'));
$('.ui-dialog-content').append($('form', '#block-views-invio-suggerimenti-block'));
});
$('#suggerimenti').dialog({
autoOpen:false,
minWidth:500,
});
}
};
})(jQuery);
And this is the html of the form created by Drupal:
<form id="prova-invio-entityform-edit-form" class="entityform entitytype-prova_invio-form" accept-charset="UTF-8" method="post" action="/tuo_tema_dev2/?q=content/blandit-ratis-usitas-valde">
<div>
<div class="pre-intructions"></div>
<div id="edit-field-suggerimento-new" class="field-type-text-long field-name-field-suggerimento-new field-widget-text-textarea form-wrapper">
<div id="edit-field-refer" class="field-type-entityreference field-name-field-refer field-widget-entityreference-autocomplete form-wrapper">
<div id="edit-actions--3" class="form-actions form-wrapper">
<input id="edit-submit--4" class="form-submit ajax-processed" type="submit" value="invia suggerimento" name="op">
</div>
</div>
</form>
You can add a hidden form value to your form when using the modal view (check if your ajax is set in the URL). Then in your submit function remove your redirect when the form value is present. Assuming it is set using $form_state using this line:
unset($form_state['redirect']);
We can give you more help if you attach your form code. That seems more relevant to me, for this problem, than your JavaScript.

create custom durandal modal

I am trying to develop custom modal plugin for durandal 2.1 to have my own logic and abstract it from the rest of my app here is what I have so far but something does not work and modal gets inserted in DOM twice
define(['jquery', 'knockout', 'plugins/dialog'], function ($, ko, dialog) {
var modal = {
install: function (config) {
dialog.addContext("Modal", {
addHost: function (theDialog) {
var body = $("body");
$('<div id="Dialog" class="AlignC"><div class="ModalHost"></div></div>').appendTo(body);
theDialog.host = $('#Dialog').get(0);
},
removeHost: function (theDialog) {
alert("demoving host");
$("#Dialog").remove();
},
compositionComplete: function (child, parent, context) {
var theDialog = dialog.getDialog(context.model);
}
});
}
};
return modal;
});
and here is how i call it from my viewmodel
dialog.show(this, null, 'Modal');
can anyone tell me what is wrang with this code why my model ELEMENT is inserted twice and ovelay each other. how can i fix that.
second element does not have content inside.
by the way here is view I am trying to show inside modal
<span class="Loader"></span>
<div class="Modal">
<h2 class="Caps">SomeName</h2>
<div class="Row">
<input type="text" />
</div>
<div class="Desc">
description
<br />
XXY YYX XXY
</div>
<div class="Buttons">
<span class="Green">Check</span>
<span>Add</span>
</div>
</div>
Ok I managed to fix this behavior. the problem with click binding was firing twice and this was the problem associated with inserting tow HTML elements in DOM after fixing click handler, everything works just fine.

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.

jQuery - Sliding content tab, slides open/close on click

Fixed thanks to helpers below, see it in action here: http://bit.ly/15npgSC
I am learning jQuery and have come across a problem which I cannot find a fix for. I have a content slider which when a button is clicked, it slides open, and when the button is clicked again, it closes. This is all fine, the problem I have is that the slider opens automatically when the page loads, not only when clicked. How can I keep it closed when the page loads and have it only open when clicked? It works fine afterwards, its just that as the page loads, it opens. I tried putting $(document).click(function() { at the start which kind of worked but then when clicked it would open and then close immediately after opening with no click. I changed back to the jQuery code below but now have the problem of it opening when the page loads again.
$(document).ready(function() {
$('.pull-me').click(function() {
$('.panel').slideToggle('slow');
});
$('a').toggle(function() {
$(this).html("Click to close!");},
function() { $(this).html("Click to open!");
}).click();
});
If you are able to fix this problem, could you explain why this occurs with my current code and why the fix stops that happening please?
Thanks, Rafa.
Sorry for not posting the HTML code before, but this is it:
<div class="panel">
<br />
<br />
<p>Now you see me!</p>
</div>
<div>
<p class="slide">Click to open!</p>
</div>
Because you did not post any HTML so I guess '.pull-me' is an 'a' element.
Pls try below code(remove .click()):
$(document).ready(function() {
$('.pull-me').click(function() {
$('.panel').slideToggle('slow');
});
$('a').toggle(function() {
$(this).html("Click to close!");},
function() { $(this).html("Click to open!");
}); // modified here
});
You are triggering click event when the page first load.
Try this:
// HTML
<div class="pull-me">
Click here!
</div>
<div class="panel">
show/hide
</div>
// jQuery
$(document).ready(function() {
$('.pull-me').click(function() {
$('.panel').slideToggle('slow');
});
$('a').toggle(function() {
$(this).html("Click to open!");},
function() { $(this).html("Click to close!");
});
});
check here in this JsFiddle -> http://jsfiddle.net/GXCuz/1/