jquery not triggering for ENTER Keydown - keydown

i guess I'm missing something I've checked my code and its pretty much the same as another project where it works fine. the repository
first is what is in my jquery file
`$("#taskdata").keyup(function(event){
if(event.keyCode == 13){
console.log("getting band")
$("#getband").click();
}
});`
a directive it is in
`
angular.module('myApp').directive('newTask', function() {
return {
restrict: 'E',
template: `
<div class="newTask" style:" margin: 0;">
<input id="taskdata" class="data" name="task" ng-model="text"
placeholder="Enter Task">
<button class="submit" ng-click="postData( {text:text} )">Create Task</button>
</div> `
}
})
`

Related

Disable the submit button unless the original form image is changed with jquery

I tried the code mentioned in this question
my code:
$('.form_contact')
.each(function() {
$(this).data('serialized', $(this).serialize())
})
.on('change input', function() {
$(this)
.find('button:reset, button:submit')
.attr('disabled', $(this).serialize() == $(this).data('serialized'));
})
.find('button:reset, button:submit')
.attr('disabled', true);
And it works perfectly on text input and textarea and select.
But when I upload a picture for example with the following input:
<form class="form_contact" action="/admin/edit-post-logic.php" enctype="multipart/form-data" method="POST">
<input type="file" name="avatar" accept="image/png, image/jpeg">
<button disabled="" class="button_reset_form" type="reset">ביטול שינויים</button>
<button disabled="" class="button_submit_form" type="submit" name="submit">שמירה</button>
</form>
The image appears and everything is fine, but the buttons do not become active and remain disabled, does anyone have any idea what can be done to make it work?
Serialize does not convert the file input's value so it will be ignored. So your check will not get the value. So you need to add another check for the file input.
So you can check it directly $(input[type="file"]).val()
$('.form_contact')
.each(function() {
$(this).data('serialized', $(this).serialize())
})
.on('change input', function() {
$(this)
.find('button:reset, button:submit')
.attr('disabled', $(this).serialize() == $(this).data('serialized') && !$('input[type="file"]').length);
})
.find('button:reset, button:submit')
.attr('disabled', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form_contact" action="/admin/edit-post-logic.php" enctype="multipart/form-data" method="POST">
<input type="file" name="avatar" accept="image/png, image/jpeg">
<button disabled="" class="button_reset_form" type="reset">ביטול שינויים</button>
<button disabled="" class="button_submit_form" type="submit" name="submit">שמירה</button>
</form>

How to check password using RegEx using jquery and without keyup function

I want to make a signup form in which user type password which contains combination of alphabet,letter and length > 6 otherwise form will not submit
here I have shown function specifically for password only but i have other function for other input types and they are working properly but it is not.
$('#password').hide();
var password = false;
$('#user_password').focusout(function() {
check_password();
});
function check_password() {
var password = new RegExp(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/);
var password_length = $('#user_password').val().length;
if (password.test($("#user_password").val()) && password_length > 6) {
alert("hello");
$('#password').hide();
} else {
$('#password').html('Password should be more than 6 character and should contain a letter and number');
$('#password').show();
password = true;
}
}
$('#signupfrm').submit(function() {
password = false;
check_password();
if (password == false) {
return true;
} else {
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" name="signupfrm" id="signupfrm" method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
//other input types above password input type
<input type="password" class="form-control" placeholder="Password..." name="user_password" id="user_password" required="">
<span id="password">
</span>
<button type="submit" class="btn btn-login" name="signup" id="signup" value="Signup">Create My Account</button>
</form>
You likely meant to do this
But you need to fix your regex https://regex101.com/r/ND19JO/1
I suggest this:
^(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=]).*$
6 chars one lowerCase, one upperCase and one special char
const passwordRe = new RegExp(/^(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=]).*$/);
const check_password = function() {
const pw = $('#user_password').val();
const pwOK = passwordRe.test(pw);
$('#pwError').toggle(!pwOK);
return pwOK;
}
$(function() {
$('#user_password').focusout(check_password)
$('#signupfrm').on("submit", function(e) {
if (!check_password()) e.preventDefault();
})
})
#pwError {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" name="signupfrm" id="signupfrm" method="post" action="">
<input type="password" class="form-control" placeholder="Password..." name="user_password" id="user_password" value="bla" required="">
<span id="pwError">Password should be more than 6 character and should contain a letter and number</span>
<button type="submit" class="btn btn-login" name="signup" id="signup" value="Signup">Create My Account</button>
</form>
If you have the correct regex, you don't have to test separately for the length:
var password = /^(?=.*\d)(?=.*[a-zA-Z])(?!.*\s).{7,15}$/;
It seems you also do not allow white space in your password. The way to prevent the form from submitting is to execute event.preventDefault() in your submit handler if the password is invalid. So the function check_password needs to return a flag that will be checked. I have removed the code that hides and unhides the password field to reduce the code to its essence:
function check_password() {
var password = /^(?=.*\d)(?=.*[a-zA-Z])(?!.*\s).{7,15}$/;
if (password.test($("#user_password").val())) {
return true;
}
else {
console.log('Password should be more than 6 character and should contain a letter and number and no spaces');
return false;
}
}
$(function() {
$('#signupfrm').submit(function() {
if (!check_password(event)) {
event.preventDefault();
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" name="signupfrm" id="signupfrm" method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<input type="password" class="form-control" placeholder="Password..." name="user_password" id="user_password" required="">
<span id="password">
</span>
<button type="submit" class="btn btn-login" name="signup" id="signup" value="Signup">Create My Account</button>
</form>
Note that you should only attempt to create the submit handler once you are sure that the document's elements have been created, i.e. element id signupform in this case. That is why that code is placed in a jQuery.ready() block (or its shortcut version). See .ready().

ng-model vs ngModel - breaks form

New to angular, new to life:
I have a small email form.
This works:
<form method="post" name="form" role="form" ng-controller="contactForm" ng-submit="form.$valid && sendMessage(input)" novalidate class="form-horizontal">
<p ng-show="success"><b>We received your message</b></p>
<p ng-show="error">Something wrong happened!, please try again.</p>
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" ng-model="input.name" required><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" ng-model="input.email" required><br>
<label for="messsage">Message:</label><br>
<textarea id="messsage" name="message" ng-model="input.message" ngMaxlength='2000' required></textarea><br>
<button type="submit" name="submit" ng-disabled="error" value="submit">Submit</button>
</form>
This does not work:
<form method="post" name="form" role="form" ng-controller="contactForm" ng-submit="form.$valid && sendMessage(input)" novalidate class="form-horizontal">
<p ng-show="success"><b>We received your message</b></p>
<p ng-show="error">Something wrong happened!, please try again.</p>
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" ngModel="input.name" required><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" ngModel="input.email" required><br>
<label for="messsage">Message:</label><br>
<textarea id="messsage" name="message" ngModel="input.message" ngMaxlength='2000' required></textarea><br>
<button type="submit" name="submit" ng-disabled="error" value="submit">Submit</button>
</form>
for the 2 inputs and the textarea if I use 'ng-model' the email sends, but when the page loads, the form loads invalid.
If i use 'ngModel' the form loads clean, but the email wont submit.
controller here:
app.controller("contactForm", ['$scope', '$http', function($scope, $http) {
$scope.success = false;
$scope.error = false;
$scope.sendMessage = function( input ) {
$http({
method: 'POST',
url: 'processForm.php',
data: input,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success( function(data) {
if ( data.success ) {
$scope.success = true;
$scope.input.name="";
$scope.input.email="";
$scope.input.message="";
} else {
$scope.error = true;
}
} );
}
You can see it live here:
http://smartestdiner.com/Bethel/indexx.html#/contact
Warning:
There is some annoying red background
.ng-invalid{
background-color:red;
}
}]);
That's how we know it is loading invalidly.
The annoying red background is the form, since you have a very generic rule set by .ng-invalid, the class will be set on the form as well. You would need to make it more specific for the inputs and controls within the form.
Example:
input.ng-invalid,
textarea.ng-invalid {
background-color:red;
}
Or just reset rule for form.ng-invalid
To add on there is nothing called ngModel it is ng-model. using the former one doesn't do anything but adds a dummy attribute on the element, it has no effect. It is angular way of directive naming, since html is case insensitive the one way angular can identify the directive from attribute or element name (based on the restriction). It converts it to camelCasing to evaluate and process respective directive (or directives attribute bindings). When you do not have ng-model specified and if the form or control does not have novalidate attribute, then the browser's HTML5 validation kicks in that is what you see as inconsistency. Using HTML5 novalidate attribute makes sure no native validation happens on the form.
ng-model is when u write the view (html part).
ngModel is used when one write a custom directive. It is placed in the "require:" param so that u can access,
variables like ngModel.$modelValue
ngModel.$modelValue will have the latest content which has been typed by the user at realtime. So, it can be used for validations, etc.
View code:-
<!doctype html>
<html ng-app="plankton">
<head>
<script src="/bower_components/angular/angular.min.js"></script>
<script src="/scripts/emailing/emailing.directive.js"></script>
</head>
<body ng-controller="EmailingCtrl">
<div>
<label>Enter Email: </label>
<emailing id="person_email" ng-model="email_entered"></emailing>
</div>
</body>
</html>
Custom directive:-
(function() {
'use strict';
angular.module('plankton', [])
.directive('emailing', function emailing(){
return {
restrict: 'AE',
replace: 'true',
template: '<input type="text"></input>',
controllerAs: 'vm',
scope: {},
require: "ngModel",
link: function(scope, elem, attrs, ngModel){
console.log(ngModel);
scope.$watch(function(){ return ngModel.$modelValue;
}, function(modelValue){
console.log(modelValue);//awesome! gets live data entered into the input text box
});
},
};
})
.controller('EmailingCtrl', function($scope){
var vm = this;
});
})();
This has been plunked here:- here

How can I isolate nested form?

I'm very new to AngularJS, and new to client side programming.
Context:
I'm implementing a contact form with support for multiple phone numbers and addresses.
It look like this:
<form name="contactInsertForm" ng-controller="contactInsertController as contactCtrlr" ng-submit="contactInsertForm.$valid && contactCtrlr.save()">
<input type="text" name="name" />
<phones-editor></phones-editor>
<addresses-editor></addresses-editor>
<input type="submit" />
</form>
phonesEditor and addressesEditor are custom Angular directives which implement support for adding, removing and editing phones and addresses. The controllers and modules look like this:
Addresses:
(function () {
var app = angular.module("AddressesEditorModule", []);
app.directive("addressesEditor", function () {
return {
restrict: "E",
templateUrl: "/addressesEditorTemplate.html",
controller: function ($scope) {
this.addresses = [
// this will hold addresses.
];
// ...
}
}
})();
Phones:
(function () {
var app = angular.module("PhonesEditorModule", []);
app.directive("phonesEditor", function () {
return {
restrict: "E",
templateUrl: "/phonesEditorTemplate.html",
controller: function ($scope) {
this.phones = [
// this will hold phones.
];
// ...
}
}
})();
And the templates:
Addresses:
<!-- list already added addresses -->
<div ng-repeat="address in addressesEditorCtrlr.addresses">
<p>{{address.address}}</p>
<p>{{address.city}}</p>
</div>
<form name="addressInsertForm" ng-submit="addressInsertForm.$valid && addressesEditorCtrlr.add()">
<!-- inputs for each of the address fields -->
<input type="submit" value="Add" />
</form>
Phones:
<!-- list already added phones -->
<div ng-repeat="phone in phonesEditorCtrlr.addresses">
<p>{{phone.number}}</p>
<p>{{phone.areaCode}}</p>
</div>
<form name="phoneInsertForm" ng-submit="phoneInsertForm.$valid && phonesEditorCtrlr.add()">
<!-- inputs for each of the phone fields -->
<input type="submit" value="Add" />
</form>
As you may have noticed, the generated at the browser HTML looks like this:
<form>
<input type="text" name="name" />
<phones-editor>
<!-- list already added phones -->
<div ng-repeat="phone in phonesEditorCtrlr.addresses">
<p>{{phone.number}}</p>
<p>{{phone.areaCode}}</p>
</div>
<form name="phoneInsertForm" ng-submit="phoneInsertForm.$valid && phonesEditorCtrlr.add()">
<!-- inputs for each of the phone fields -->
<input type="submit" value="Add" />
</form>
</phones-editor>
<addresses-editor>
<!-- list already added addresses -->
<div ng-repeat="address in addressesEditorCtrlr.addresses">
<p>{{address.address}}</p>
<p>{{address.city}}</p>
</div>
<form name="addressInsertForm" ng-submit="addressInsertForm.$valid && addressesEditorCtrlr.add()">
<!-- inputs for each of the address fields -->
<input type="submit" value="Add" />
</form>
</addresses-editor>
</form>
The problem:
I have two form's inside a form. The nested forms work correctly, adding and validating values it should be doing, and refusing to add invalid phones/addresses.
But when I click the submit button at the outer form, it will interpret the inner forms input fields and will raise errors if these fields have invalid values.
How can I use AngularJS form handling and avoid this situation? Is this possible at all?
you would need a directive if you want child form as isolate form. Have a look at answers from this SO question. please have a look at fiddle attached in this answer. I am putting the fiddle link here for you to js-fiddle to see it in action.
putting below code just because SO doesnt accept only fiddle links...
<form name="parent">
<input type="text" ng-model="outside"/>
<ng-form name="subform" isolate-form>
<input type="text" ng-model="inside"/>
</ng-form>
</form>
Working on Angular 1.6
const isolatedFormDirective = () => {
return {
restrict: 'A',
require: '?form',
link: ($scope, $element, $attrs, ctrl) => {
ctrl && ctrl.$$parentForm && ctrl.$$parentForm.$removeControl(ctrl);
}
}
}
app.directive('isolatedForm', isolatedFormDirective);
This article has exactly what you are looking for.
The basic gist is that you want to use the ngForm directive inside your form tag.
<div ng-form="outerForm">
<input type="text" ng-model="main.outerFormText"/>
<div ng-form="innerForm">
<input type="text" ng-model="main.innerFormText" required/>
<button type="button" ng-click="main.submit('innerForm')"
ng-disabled="innerForm.$invalid">Inner Submit</button>
</div>
<button type="button" ng-click="main.submit('outerForm')"
ng-disabled="outerForm.$invalid">Outer Submit</button>
</div>
Example plnkr

Display message whilst server is running query Django

I have a very long task that runs once the client/user/customer presses the submit button. How can I display a message to say, hang on... query running, until the query finishes using Django?
You should consider using Ajax to do that.
Let's see an example using JQuery;
If in your template, you have this form :
<form id="my_form" action="" method="post">
<label for="age">Age:</label>
<input type="text" name="age" id="age"/>
<input type="submit" value="Submit"/>
</form>
<div id="loading" style="display:none;">Loading...</div>
Let's write some Javascript, assuming you have already include the Jquery lib :
$(function(){
$('#my_form').submit(function(event){
event.preventDefault();
alert('user submitted the form');
$('#loading').show();
$.post('my_url',
{age : $('#age').val()},
function(data){
$('#loading').hide();
alert('server finished to process data.');
});
});
});
You can fully customize this piece of code for doing what you want.
And if you want more debug in ajax, I suggest you to declare your ajaxSetup following this way :
function ajaxSetup(){
$.ajaxSetup({
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internal Server Error.\n' + x.responseText);
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
}
This is what I ended up doing using JQuery and including some code to determine which button was pressed:
<form>
<div id="loading" style="display:none;">Finding all words, may take a long time</div>
<div id="form_input_things">
<input type="submit" name="_save" value="Save" />
<input type="submit" name="_get_words" value="Get Words" />
{{ form.as_p }}
</div>
</form>
<script>
$("form").submit(function() {
{
if( $("[submit_button_pressed=Save]").get(0) === undefined )
{
$('#loading').show();
$('#form_input_things').hide();
}
}
return true;
});
$(":submit").live('click', function() {
$(this).attr("submit_button_pressed", $(this).val());
});
</script>