autoscroll to first blank required field using angular js - javascript

I have created a form using angular js with around 7 input elements. When I click on submit, I want the form to get scrolled up to the first blank field which is required. But now it is not correctly pointing to the field left blank. Any solution to resolve this ?
Check the error here.

before submitting the form, you can check whether the form is valid or not and use .focus() to focus on that element.
$scope.onSubmit = function(yourForm) {
if (!yourForm.$valid) {
angular.element("[name='" + yourForm.$name + "']").find('.ng-invalid:visible:first').focus();
return false;
}
};
method #2 - You can also use $anchorScroll service
see the documentation here
$scope.onSubmit = function(yourForm) {
if (!yourForm.$valid) {
var id = angular.element("[name='" + yourForm.$name + "']").find('.ng-invalid:visible:first').data('id');
$location.hash(id);
$anchorScroll();
return false;
}
};

Related

JavaScript's .select() method procs only from second attempt

With Angular, I'm trying to implement a way to change a value with an 'Edit' button click in such a way that when this button is clicked, an input is displayed over the text, and when the 'Save' button is clicked, the input's opacity becomes 0, and the model's value is applied.
I've created a jsfiddle to make my issue a bit more visual. JSFIDDLE DEMO
The issue is the following: I want to select the text to make it obvious for the user that it can be changed now, after the 'Edit' button is clicked. I do it this way:
var input = angular.element(document.querySelector('input'))[0];
input.focus();
input.select();
The only problem is that the input.select() only works on second attempt. You can see it in the demo. I have no rational explanation to this whatsoever. I need to mention that this app that I'm writing is for Electron, it means that it will only launch in Chromium, so I don't need cross-browser support for this.
When the 'Edit' button is clicked for the first time, no selection happens:
But when I click 'Save' and then 'Edit' again, everything works as expected:
Any thought would be much appreciated!
Use $timeout , it will trigger digest cycle
var app = angular.module('app', []);
app.controller('mainController', function($timeout,$scope) {
var vm = this;
vm.address = '127.0.0.1';
vm.name = 'anabelbreakfasts';
vm.editing = {
address: false
};
vm.temp = {
address: null
};
vm.changeClick = function(element) {
vm.editing[element] = !vm.editing[element];
if (vm.editing[element]) {
vm.temp[element] = vm[element];
var input = angular.element(document.querySelector('div.row.' + element + ' input'))[0];
$timeout(function(){
input.focus();
input.select();
});
} else {
vm[element] = vm.temp[element];
}
};
});
Fiddle
Use setTimeout:
setTimeout(function(){
input.select();
}, 0)
Also, input.focus() is kind of redundant

How to call a function when input is cleared in AngularJS?

I know Angular has simple syntax to display messages or update css, but what I'm trying to do is actually call a function.
<input ng-model="somefield">
<span ng-show="!somefield.length">Please enter something!</span>
<span ng-show="somefield.length">Good boy!</span>
This is my model vm.tagSearching = '' I can detect when I start typing in the input and see the value update. However once I get to the last letter, and I delete that I don't get an update.
I tried using $scope.watch
$scope.$watch('vm.tagSearching', function() {
alert('hey, var has changed!');
});
However this only fires once as the app initializes, but never again, even while typing.
Markup
<input class="tag-search-input"
type="text"
placeholder="Search Tags"
ng-model="tgs.tagSearching"
typeahead="t for t in tgs.fuzzyTagSearch($viewValue)">
Controller
function fuzzyTagSearch(word) {
console.log('fuzzyTagSearch',word);
if (word.length > 2) {
ApiFactory.getSearchResults(word).then(function(data) {
console.log('data',data.data.ticker_tags);
vm.terms = data.data.ticker_tags;
});
}
}
How would you accomplish this? I need to detect when the input is clear when the user backspaces / deletes all the letters so that I can reset the table.
You can simply set up an ng-change directive.
<input ng-model="tgs.tagSearching" ng-change="tgs.detectEmpty()">
vm.detectEmpty = function() {
if (vm.tagSearching.trim().length === 0) {
// it's empty
}
}

trigger change event except condition jquery

$('#query_txt').change(function() {
return window.location = $('#query_txt').data('url') + '/searches?query=' + $('#query_txt').val();
});
This event is triggered when it's made a change on input field #query_txt
However I want execute this code unless a user click on this link:
I have tried with this version with coffeescript but is not working:
unless $(".select2-search-choice-close").click()
$('#query_txt').change ->
window.location = $('#query_txt').data('url') + '/searches?query=' + $('#query_txt').val()
How can I do it?
Thank you!
Make a condition flag true when you click it. Or unbind to change in the click handler for your link.
Try this
var buttonClicked = false;
$('#query_txt').change(function() {
if(buttonClicked)
window.location = $('#query_txt').data('url') + '/searches?query=' + $('#query_txt').val();
});
$(".select2-search-choice-close").click(function(){
buttonClicked = true;
return false;
});
The fix to this question is in when click on close button and when click on suggestions text with select2.
Select2 returns an object in callback and it is possible check if it's added or removed there. Thank you to Eru.

Submit / Validation Jquery

Im trying to validate a form at the point of clicking submit. There are a number of inputs which need validating which are all assigned the class .ipv4val. The issue I have is that I cant seem to add the 'bad' class to the single input element that has failed the validation ?
$("form").submit(function() {
var REGEX = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/;
if (REGEX.test($(".ipv4val").val())) {
return true;
}
else {
$(this).addClass("bad");
return false;
}
Any ideas ?
Look out for your use of: $(this).addClass("bad")
$(this) is the form element at the time of its execution. Try using the element ID of the input.
Have you considered the jquery.validate plugin, instead of rolling your own validation?
Try it this way:
$("form").submit(function() {
var REGEX = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/;
var ok=true;
$(".ipv4val").each(function(){
if (!REGEX.test($(this).val())) {
$(this).addClass("bad");
ok = false;
}
});
return ok;
};

how to check if a form is valid programmatically using jQuery Validation Plugin

I have a form with a couple of buttons and I'm using jQuery Validation Plugin from http://jquery.bassistance.de/validate/. I just want to know if there is any way I can check if the form is considered in valid state by jquery validation plugin from anywhere in my javascript code.
Use .valid() from the jQuery Validation plugin:
$("#form_id").valid();
Checks whether the selected form is valid or whether all selected
elements are valid. validate() needs to be called on the form before
checking it using this method.
Where the form with id='form_id' is a form that has already had .validate() called on it.
2015 answer: we have this out of the box on modern browsers, just use the HTML5 CheckValidity API from jQuery. I've also made a jquery-html5-validity module to do this:
npm install jquery-html5-validity
Then:
var $ = require('jquery')
require("jquery-html5-validity")($);
then you can run:
$('.some-class').isValid()
true
#mikemaccana answer is useful.
And I also used https://github.com/ryanseddon/H5F. Found on http://microjs.com. It's some kind of polyfill and you can use it as follows (jQuery is used in example):
if ( $('form')[0].checkValidity() ) {
// the form is valid
}
For a group of inputs you can use an improved version based in #mikemaccana's answer
$.fn.isValid = function(){
var validate = true;
this.each(function(){
if(this.checkValidity()==false){
validate = false;
}
});
};
now you can use this to verify if the form is valid:
if(!$(".form-control").isValid){
return;
}
You could use the same technique to get all the error messages:
$.fn.getVelidationMessage = function(){
var message = "";
var name = "";
this.each(function(){
if(this.checkValidity()==false){
name = ($( "label[for=" + this.id + "] ").html() || this.placeholder || this.name || this.id);
message = message + name +":"+ (this.validationMessage || 'Invalid value.')+"\n<br>";
}
})
return message;
}
valid() method.
http://docs.jquery.com/Plugins/Validation/valid
iContribute: It's never too late for a right answer.
var form = $("form#myForm");
if($('form#myForm > :input[required]:visible').val() != ""){
form.submit();
}else{
console.log("Required field missing.");
}
This way the basic HTML5 validation for 'required' fields takes place without interfering with the standard submit using the form's 'name' values.
For Magento, you check validation of form by something like below.
You can try this:
require(["jquery"], function ($) {
$(document).ready(function () {
$('#my-button-name').click(function () { // The button type should be "button" and not submit
if ($('#form-name').valid()) {
alert("Validation pass");
return false;
}else{
alert("Validation failed");
return false;
}
});
});
});
Hope this may help you!
In case you're validating before submitting the form:
$(function(){
$('.needs-validation').on('submit', function(event){
if(!event.target.checkValidity()){
// Form didn't pass validation
event.preventDefault();
$(this).addClass('was-validated');
}
})
})
You can't use $('form')[0].checkValidity() with multiple forms in the view.

Categories

Resources