Trying to disable a button using Angular's ng-disable - javascript

I have this in my angular code:
$scope.Disable = false;
$scope.SetDisable = function (Number) {
if (Number.length < 4) {
return false;
}
else {
return true;
}
};
$scope.$watch("Admin.UserName", function () {
$scope.Disable = $scope.SetDisable($scope.Admin.UserName.length);
});
And this code in my view:
<input id="Submit" name="Submit" class="btn btn-success" type="submit" value="Login" ng-disabled="Disable" />
Notice that ever i change the default value of $scipe.Disable to true and turn the other lines of code in my Angular script to comment, the button is still enabled.
If i change the code in my View to:
<input id="Submit" name="Submit" class="btn btn-success" type="submit" value="Login" ng-disabled="true" />
(ng-disabled="true")
The button is disabled.
What am i doing wrong?

use ng-change instead of $watch e.g.
$scope.myChange = function (nu) {
if (nu.length < 4) {
$scope.Disable = false;
}
else {
$scope.Disable = true;
}
};
see this link:
https://plnkr.co/edit/m5TUzC35gg8EuApVHcO0?p=preview

This may caused by Angular scope inheritance feature, you could overcome this issue by two approaches:
use controller as syntax:
angular.controller('formController', function(){
this.Disabled = false;
})
<div ng-controller="formController as ctrl">
<input ng-disabled="ctrl.Disabled">
</div>
use a reference variable instead of a primitive variable
$scope.Disabled = { value: false }
<input ng-disabled="Disabled.value">

The problem is that within the $watch() function you pass the length of the string instead of the string when call the function SetDisable() and in this function you use the length again in the if condition.
HTML:
<html ng-app="app">
<head>
</head>
<body ng-controller="mainController">
<div>
<label>UserName:</label>
<input type="text" ng-model="UserName" placeholder="Enter a name here">
<hr>
<input id="Submit" name="Submit" class="btn btn-success" type="submit" value="Login" ng-disabled="Disable" />
</div>
</body>
</html>
JS:
angular
.module('app', [])
.controller('mainController', mainController);
mainController.$inject = ['$scope'];
function mainController($scope) {
$scope.Disable = false;
var SetDisable = function (name) {
if (name.length < 4) {
return false;
} else {
return true;
}
}
$scope.$watch('UserName', function() {
$scope.Disable = SetDisable($scope.UserName);
})
}
I made a working example:
http://codepen.io/anon/pen/GomYGq?editors=101

Related

How to show and hide button value on click in AngularJS?

I need to add a minus sign onclick of a button (-200), and on second click, the minus sign should be removed. And minus sign can be added only in the beginning.
<input type="button" value="-" name ="minus" id="minus" ng-click="click($event)" />
$scope.click = function(event){
angular.element('.numValBox').focus();
angular.element('.numValBox').val(function(index,val){
return val + angular.element(event.target).val();
});
};
Here is a good approach to it:
JSFiddle
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<input type="button" value="-" name="minus" id="minus" ng-click="click($event)" />
<input type="text" ng-model="numValBox" class="numValBox"></div>
</div>
JS:
angular.module('myApp', [])
.controller('myCtrl', function ($scope) {
$scope.numValBox = "hello world";
$scope.click = function (event) {
$scope.numValBox = ($scope.numValBox.match(/-/)) ? $scope.numValBox.replace('-', '') : '-'+$scope.numValBox;
};
});
Of course I thought the input value should be anything not only numbers and that's because I did a match

angular show inputs base checkbox ng-model make inputs unreachable

Please help, I have the following code
<div>
<input type="checkbox" id="chk1" ng-model="Status" />
<span ng-bind="Title"></span>
</div>
<div id="div1" ng-show="Status">
<span ng-bind="SpanTitle" ></span>
<input type="text" id="txtLastName"
ng-model="LastName"
ng-click="LastNameClick()"
ng-blur="LastNameOut()"
name="txtLastName" />
</div>
and when checkbox is being checked the div1 is shown but the input text cannot be clicked or written.
Any idea please?
Edit: Added controller from user's comment
function DController($scope) {
var defaultInputText = "hello";
$scope.Title = "check";
$scope.SpanTitle = "Span";
$scope.Status = false;
$scope.LastName = defaultInputText;
$scope.LastNameClick = function () {
if ($scope.LastName ==defaultInputText) {
$scope.LastName = "";
}
}
$scope.LastNameOut = function () {
if ($scope.LastName.length == 0) {
$scope.LastName = defaultInputText;
}
}
}
From code, that you have provided, I can suggest, that problem can be in css. May be some elements overlap the input.

TinyMCE doesn't initialize using ng-repeat

I have a problem when I want to append a textarea linked to tinyMCE wysiwyg.
tinyMCE don't have time to initialize so maybe the solution is to wait the end of the ng-repeat. But I don't now how and tinyMCE is not using angular so..
Need your help.
Have a good time.
Take a Look at this
Working Demo
html
<div ng-app="myApp" ng-controller="PostController">
<br/>
<textarea ng-model="mypost" ui-tinymce="tinymceOptions"></textarea>
<br/>
<input type="button" value="Submit" ng-click="submit()"/>
<br/>
<ul>
<li ng-repeat="post in posts | orderBy:orderProp:true">
<input type="button" value="Edit" ng-click="edit=!edit;newpost=post.content"/>
<input ng-hide="edit" type="button" value="Delete" ng-click="deletepost(post)"/>
<br />
<div ng-hide="edit" style="white-space: pre-wrap"><ANY ng-bind-html-unsafe="post.content"></ANY></div>
<div ng-show="edit">
<textarea ng-model="newpost" ui-tinymce="tinymceOptions"></textarea>
<input type="button" value="Submit" ng-click="editpost(post, newpost);edit=!edit" />
</div>
<br /><br /><br/>
</li>
</ul>
</div>
script
var myApp = angular.module('myApp', ['ui.tinymce']);
function PostController($scope) {
$scope.posts = [];
$scope.time = 1;
$scope.orderProp = 'pseudo_time';
$scope.tinymceOptions = { menubar: false };
$scope.submit = function() {
newpost = {"content": $scope.mypost, "pseudo_time": $scope.time++};
$scope.posts.push(newpost);
};
$scope.editpost = function(post, newpost) {
var index = jQuery.inArray(post, $scope.posts);
$scope.posts[index].content = newpost;
};
$scope.deletepost = function(post) {
if (confirm("Delete Answer?") == true) {
var index = jQuery.inArray(post, $scope.posts);
$scope.posts.splice(index, 1);
}
};
}

Javascript validation error

I have written the following code in html and the javascript file is also embedded below
<!DOCTYPE html>
<meta charset="utf-8">
<HTML>
<head>
<link rel="stylesheet" href="admin.css"/>
<script type="text/javascript" src="common.js"></script>
</head>
<BODY>
<div class="adminnav" id="adminnav">
<ul>
<li>Insert
<ul>
<li>Insert Course</li>
<li>Insert Student</li>
<li>Insert Teacher</li>
<li>Insert Subject</li>
</ul>
</li>
</ul>
</div>
<div class="addcourse" >
<form name="course" onSubmit='return validcourse()' method="POST">
Course Name:
<input type="text" name="coursename" id="cname" /><br>
Duration:<input type="text" name="cd"/>
<br>
Course Id:<input name="cid" type="text" /><br>
<input type="submit" value="submit" name="submit"><input type="reset" name="coursereset">
</form>
</div>
</BODY>
</HTML>
common.js
function validcourse()
{
var course_name=document.course.coursename;
var course_duration=document.course.cd;
var course_id=document.course.cid;
if(course_name_valid(course_name))
{
{
if(course_duration_valid(course_duration))
{
if(course_id_valid(cid))
{
}
}
}
}
}
function course_name_valid(course_name)
{
var letters=/^[A-Za-z]+$/;
if(course_name.value.match(letters))
{
return true;
}
else
{
alert("Course name must have alphabets only");
course_name.focus();
return false;
}
}
function course_duration_valid(course_duration)
{
var letters=/^[1-9]+$/;
if(cd.value.match(letters))
{
return true;
}
else
{
alert("Course Duration can have numbers only");
course_duration.focus();
retun false;
}
}
function course_id_valid(course_id)
{
var letters=/^[0-9a-zA-z]+$/;
if(course_id.value.match(letters))
{
return true;
}
else
{
alert('Course ID must have character and numeric values only');
course_id.focus();
return false;
}
}
My problem is that nothing is happening no error messages are given.
Error messages are given only for course name but not for course duration and course id?
Here is a link to jsfiddle http://jsfiddle.net/amolkarale/aTfq6/1/
You are not returning anything from validcourse. Add a return true; and return false; in there, to either let the submission continue or stop the submission from happening:
function validcourse()
{
var course_name=document.course.coursename;
var course_duration=document.course.cd;
var course_id=document.course.cid;
if(course_name_valid(course_name))
{
{
if(course_duration_valid(course_duration))
{
if(course_id_valid(cid))
{
return true;
}
}
}
}
return false;
}
Looks like you have a syntax error in your third functioncourse_duration_valid(course_duration)
retrun false;
should be:
return false;
Okay, so I got your stuff to work. Here are the changes needed:
First, object references need to be cleaner in your DOM
var course_name=document.getElementById("cname");
var course_duration=document.getElementById("cd");
var course_id=document.getElementById("cid");
As you can see, the elements need to have their individual ids.
Course Name:
<input type="text" name="coursename" id="cname" /><br>
Duration:
<input type="text" name="cd" id="cd"/><br>
Course Id:
<input name="cid" type="text" id="cid" /><br>
Finally, the retrun needed to be corrected, as already pointed out by #Steve

Validate Dynamically Added Input fields

I have used this jquery validation plugin for the following form.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var obj = document.getElementById("list").cloneNode(true);
document.getElementById('parent').appendChild(obj);
}
</script>
<form id="commentForm" method="get" action="">
<p id="parent">
<input id="list" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>
When the add button is clicked a new input is dynamically added. However when the form is submitted only the first input field is validated. How can i validate dynamically added inputs?
Thank you...
You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.
And here is my solution that I've tested and it works:
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
</script>
And the html form part:
<form class="commentForm" method="get" action="">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
Good luck! Please approve answer if it suits you!
Reset form validation after adding new fields.
function resetFormValidator(formId) {
$(formId).removeData('validator');
$(formId).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(formId);
}
You need to re-parse the form after adding dynamic content in order to validate the content
$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));
The one mahesh posted is not working because the attribute name is missing:
So instead of
<input id="list" class="required" />
You can use:
<input id="list" name="list" class="required" />
Modified version
jquery validation plugin version work fine v1.15.0 but v1.17.0 not work for me.
$(document).find('#add_patient_form').validate({
ignore: [],
rules:{
'email[]':
{
required:true,
},
},
messages:{
'email[]':
{
'required':'Required'
},
},
});
In regards to #RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.
(function ($) {
$.fn.initValidation = function () {
$(this).removeData("validator");
$(this).removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(this);
return this;
};
}(jQuery));
This can be used like this:
$("#SomeForm").initValidation();
In case you have a form you can add a class name as such:
<form id="my-form">
<input class="js-input" type="text" name="samplename" />
<input class="js-input" type="text" name="samplename" />
<input class="submit" type="submit" value="Submit" />
</form>
you can then use the addClassRules method of validator to add your rules like this and this will apply to all the dynamically added inputs:
$(document).ready(function() {
$.validator.addClassRules('js-input', {
required: true,
});
//validate the form
$('#my-form').validate();
});
$('#form-btn').click(function () {
//set global rules & messages array to use in validator
var rules = {};
var messages = {};
//get input, select, textarea of form
$('#formId').find('input, select, textarea').each(function () {
var name = $(this).attr('name');
rules[name] = {};
messages[name] = {};
rules[name] = {required: true}; // set required true against every name
//apply more rules, you can also apply custom rules & messages
if (name === "email") {
rules[name].email = true;
//messages[name].email = "Please provide valid email";
}
else if(name==='url'){
rules[name].required = false; // url filed is not required
//add other rules & messages
}
});
//submit form and use above created global rules & messages array
$('#formId').submit(function (e) {
e.preventDefault();
}).validate({
rules: rules,
messages: messages,
submitHandler: function (form) {
console.log("validation success");
}
});
});
Try using input arrays:
<form action="try.php" method="post">
<div id="events_wrapper">
<div id="sub_events">
<input type="text" name="firstname[]" />
</div>
</div>
<input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
<input type="submit" name="submit" value="submit" />
</form>
and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:
<script>
$(document).ready(function(){
$("#add_another_event").click(function(){
var $address = $('#sub_events');
var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
var newNum = num + 1;
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*5 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$("#remove").click(function(){
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var indexVal = $("#index").val();
var index = parseInt(indexVal) + 1
var obj = '<input id="list'+index+'" name=list['+index+'] class="required" />'
$("#parent").append(obj);
$("#list"+index).rules("add", "required");
$("#index").val(index)
}
</script>
<form id="commentForm" method="get" action="">
<input type="hidden" name="index" name="list[1]" id="index" value="1">
<p id="parent">
<input id="list1" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>

Categories