ng-disabled with function that trigger when change - javascript

I have a submit validation button that need to be enable when all fields is being entered correctly. As the validation is too complex and is not able to be solve by using formName.$invalid alone, i need to write a function to cater the validation. I expect that the shouldEnable function to be trigger for each of the model changes inside. But it does not. Os is there any alternative for this?
Initial
<button ng-disabled="formName.$invalid">Submit</button>
Expected
<button ng-disabled="shouldEnable()">Submit</button>
$scope.shouldEnable = function() {
$scope.isEnable = true;
angular.forEach($scope.form.input2, function(val) {
if($scope.form.input2.inputA && $scope.form.input2.inputB) {
isEnable = false;
}
})
}

Your function needs to return boolean value:
$scope.shouldEnable = function() {
var isEnable = true;
// make necessary checks
return isEnable;
}

If you are using Angular's data-binding, You should use something like this :
<button ng-disabled="shouldEnable">Submit</button>
// yourObject is the object you've map in the form
$scope.$watch('yourObject', function(newObject) {
$scope.shouldEnable = isValid(newObject);
});

Related

How to return a value from a jQuery event function to the parent function?

I have a jQuery event inside a JavaScript function. I've already read that you cannot access the inner function. However, I would like to know how to adjust my code so that the parent function returns true or false depending on the jQuery function.
function validate() {
$("#button").on('click', function(){
var input = document.forms["formular"]["text"].value;
if (input == "") {
return false;
}
});
if(onclickfunction() == true){
return true;
}
else{
return false
}
}
validate();
Or can you recommend a different approach?
Not sure what this code is supposed to do, because calling validate only creates the event listener without actually executing it. But what you can do is to prevent the default action when you need, which is how validation is usually implemented:
$("#button").on('click', function(){
var input = document.forms["formular"]["text"].value;
yourSecondFunction(input !== "");
});
function yourSecondFunction(inputIsValid) {
// Do your magic here
}

Can a attribute be controlled inside a button for certain conditions with the use of flag in controller using angular js?

<button type="button" class="btn btn-outlined" ng-click="vm.change()" data-modal-target="#add-save-all-alert-modal"></button>
I have an attribute called "data-modal-target" in my HTML which helps me to invoke a modal if ng-click.....I want to control the attribute inside my controller for certain conditions(by setting flags may be)...how can I do that?
vm.change = function () {
if(vm.modifiedBaseline && vm.modifiedBaselineToBeCommented){
vm.modalFlag = true;
}
else{
st1;
st2;
}
vm.modalFlag = false;
}
inside your ng-click() event you can write this code
$scope.change= function ($index) {
$('#add-save-all-alert-modal').modal('show');
};
Please let me know if this helped

Form validation - How to keep track of multiple fields to prevent submit - Global variable?

I have a form with multiple fields (lets say 4 for this example).
I am using javascript functions on each field to validate them, generating an error indication - a red box, or a hint as text next to the box.
like so ..
<input
...
onkeyup="validateName()"
onblur="checkDuplicateName(); validateName()"
>
So what I would like to do is not allow a submit if any of the fields do not validate.
So the question is - what is the best way to set it up so submit is disabled unless all 4 fields are valid?
I will use either
document.getElementById("mySubmit").disabled=true;
or
event.preventDefault()
(..though trying to avoid Jquery) to prevent the submit.
How should I keep track of the condition of the 4 fields?
Should I create a global variable like - window.validFields, so I can access it from each of my validation functions - adding one to the variable for each field that is valid, and subtracting one when invalid? (window.validFields==4 allows a submit)
Not sure the best way to accomplish this.
Any help would be appreciated, thanks.
Assuming a form like this …
<form class="is-invalid" id="form" method="post">
<input type="text" id="lorem">
<input type="text" id="ipsum">
<input type="text" id="dolor">
<input type="text" id="amet">
<button id="submit">Submit</button>
</form>
… you could do the following …
(function () {
var fields = {
lorem: false,
ipsum: false,
dolor: false,
amet: false
},
isValid = false,
form = document.getElementById('form'),
i,
tmpInput;
// Binding submit-event to prevent form-submit
form.addEventListener('submit', onSubmit, false);
// Binding events on input-elements (keyup & blur)
for ( i in fields ) {
tmpInput = document.getElementById(i);
tmpInput.addEventListener('keyup', checkInput, false);
tmpInput.addEventListener('blur', checkInput, false);
}
// Checking form state by iterating over the fields object;
// Adding/removing 'is-valid'-class and setting `isValid`-flag
function checkFormState() {
for ( var j in fields ) {
if ( !fields[j] ) {
isValid = false;
form.className += /\bis-invalid\b/i.test(form.className)
? ''
: 'is-invalid';
return;
}
}
form.className = form.className.replace(/\bis-invalid\b/i, '');
isValid = true;
}
// Abort the submit, if the `isValid`-flag is `false`
function onSubmit(evnt) {
if ( !isValid ) {
evnt.preventDefault();
return false;
}
}
// Setting the corresponding value in the `fields`-object;
// Checking the form state
function checkInput() {
fields[this.id] = this.value.length > 5; // or any other validation rule
checkFormState();
}
})();
There's an object with the IDs of the relevant input-fields that holds each validation state. On keyup and blur each input field is checked. If it passes the validation, the corresponding value in the fields-object is set to true. Additionally the state of the form is checked on each event on an input element.
The checkState-function iterates over the fields-object. If it finds a property, that is false, the 'is-invalid'-class is set on the form-element (if it isn't already set), the isValid-flag is set to false and the function is aborted.
Otherwise — all input-fields are valid —, the isValid-flag is set to true and the 'is-invalid'-class is removed from the form-element. Now, the form can be submitted.
This all works without a single global variable. Mission accomplished!
I made a Fiddle where you can test this.
PS: Have in mind, that the addEventListener-method is only supported by IEs down to version 9. If you have to support version 8 and below, you need a workaround like this.
I hope this helps you.
You can use the forms submit event, like this:
HTML:
<form method="post" onsubmit="return MyValidation(); " ...
JS:
(function() {
var field1Valid = false;
var field2Valid = false;
window.validateField1 = function(elmnt) {
// do some validation...
if(everything == OK) {
field1Valid = true;
setButtonDisabled(false);
}
else {
field1Valid = false;
setButtonDisabled(true);
}
}
window.validateField2 = function(elmnt) {
// do some validation...
if(everything == OK) {
field2Valid = true;
setButtonDisabled(false);
}
else {
field2Valid = false;
setButtonDisabled(true);
}
}
window.checkDuplicateName = function() {
// do some more validation...
}
window.setButtonDisabled = function(disabled) {
document.getElementById('submit').disabled = disabled;
}
window.MyValidation = function() {
return field1Valid && field2Valid;
}
}());
The above example also checks whether to disable the submit button or not.
Another way would be to handle all your validation logic within the form submit event, but validating input immediately is always nicer.
There are also quite some validation plugins available for use with jQuery, if you're interested. Building this yourself can get messy quickly if you have multiple fields that need to be validated in multiple ways...

Popup - if user enters bad input, how can I get it to error on submit

I have a popup on my page that has a typeahead input on it. Right now you can type garbage and click submit and it lets you. I'm trying to write code that will throw an error on the popup if you type something that isn't included in the typeahead options and it won't let you submit it until you fix it. Here is my code, it is for making a school schedule that has classes in the typeahead dropdown.
var schedule = schedule.content.get();
var validClasses = Fp.filter(schedule.classes, function (class) { return !class.passed; }),
inputClasses = $('.optimizeViaClasses input.className').map(function () { return $(this).val(); }),
isErrorForValidClasses = Fp.all(inputClasses, function (inputClass) { return Fp.contains(validClasses, inputClass); });
if(validClasses !== inputClasses){
$errorMessage.text('Your selection does not match the class(es) in the current schedule!');
$errorMessage.show();
}
Right now if you enter garbage in the input field, this will throw an error but still let the user submit. How can I stop the user from submitting until the input is correct?
Here is my button:
$submitBtn.on('click', function(event){
if(inputParameters() !== false){
$myPopUp= $modal.find('#myData').detach()[0];
}
event.preventDefault();
});
and I checked the output of inputClasses in the Google developer console, it outputs the class and a prevObject. I just need the class...
Let javascript return either True or false and if the popup comes out return false other wise true.
For instance if it get into if return false other wise true.
since you modified your code i suppose you might want to try this instead:
http://api.jquery.com/event.stoppropagation/
also you might want to be doing something along the lines of this if stoppropagation does not result in the desired effect:
$("#formid").on("submit",function(e){
// declare isValid outside of this and set it in your validation function or call it inside this and check for that.
if(isValid) {
e.stopPropagation();
}
});
at least that's how i went about solving such issues usually. i hope it helps.
got it. the error i had was throwing an error.
var schedule = schedule.content.get(),
validClasses = Fp.filter(schedule.classes, function (class) { return !class.passed; }),
inputClasses = $('.optimizeViaClasses input.className').map(function () { return $(this).val(); }),
actualValidClasses = Fp.pluck(validClasses, 'className');
$.each(inputClasses , function(index, value){
if($.inArray(value, actualValidClasses ) === -1){
$errorMessage.text('Your selection does not match the class(es) in the current schedule!');
$errorMessage.show();
error = true;
return false;
}
});

Using Blur and Submit events on the same form

I am still confused about this. Started learning JQuery about a week now and this is what I have:
var IsValidUserName = false;
$(document).ready(function () {
$('#txtUserName').blur(function () {
if ($('#txtUserName').val().match(isNumberLetter) &&
($('#txtUserName').val().length >= 8)) {
$('#userNameError').removeClass("error").addClass("default");
$('#txtUserName').removeClass("alert");
$('#txtUserName + label').removeAttr("id", "lblUserName");
IsValidUserName = true;
}
else {
$('#userNameError').removeClass("default").addClass("error");
$('#txtUserName').addClass("alert");
$('#txtUserName + label').attr("id", "lblUserName");
}
});
});
Lets say I have another function like above, lets say FirstName:
How do I call this on the submit event? The code works as I need it to when the user leaves a field. Not sure how I can also call this code and also use the variable above to prevent submit if the data entered is invalid.
I need to call the validation above if the user clicks the submit button and stop the submission if the IsValidUserName variable is false.
Somethings just need a little push.
Thanks my friends.
Guy
You could always extract it into a function instead of an anonymous function and pass the reference to the object you want to check. This would give you the added benefit of reusing it for other elements.
function validate(ele) {
var valid;
if (ele.val().match(isNumberLetter)) && (ele.val().length >= 8)) {
valid = true;
// update user here.
} else {
valid = false;
// update user here.
}
return valid;
}
$(function(){
$('#firstName').blur(function(){ validate($(this)); });
$('#lastName').blur(function(){ validate($(this)); });
$("yourFrom").submit(function(){
var firstNameIsValid = validate($('#firstName'));
var lastNameIsValid = validate($('#lastName'));
if (!nameIsValid) && (!lastNameIsValid) {
return false;
// User has already been updated
}
});
});
Also, since you are already heavily using javascript for your validation (hope this is convenience and not the only security), you can also disable the submit button entirely until the form meets the proper requirements.

Categories