I am trying to write a code where the control goes into a block of code only when the text in the input type changes or is cleared. I am using the below condition:
if(myfrm.textchecker.$dirty && !myfrm.textchecker.$pristine)
This doesn't work until I change it to :
if(!myfrm.textchecker.$dirty && !myfrm.textchecker.$pristine)//completely opposite
Here is my code for reference :
<html>
<head>
<script src="angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="outerCtrl">
<form name="myfrm">
<input type="password" name="textchecker" ng-change="processed(ngdata)" ng-model="ngdata" required/>
<input type="submit" name="submit" value="submit">
</form>
<span style="color:red" ng-show="myfrm.textchecker.$error.required">please enter the required text</span>
{{ngdata}}
<p>
{{final}}
</p>
<p>
$dirty : {{ myfrm.textchecker.$dirty }} </br>
$invalid : {{myfrm.textchecker.$invalid }}
</br>
$pristine : {{myfrm.textchecker.$pristine }}
</p>
</div>
</body>
</html>
<script>
var app=angular.module("myApp",[]);
app.controller("outerCtrl",function($scope){
$scope.processed=function(password)
{
if(!myfrm.textchecker.$dirty && !myfrm.textchecker.$pristine)
{
console.log('!myfrm.textchecker.$dirty + !myfrm.textchecker.$pristine');
console.log(!myfrm.textchecker.$dirty + !myfrm.textchecker.$pristine);
// var password=$scope.ngdata;
var strength=0;
//console.log(password);
// alert($scope.ngdata);
// if (password.length > 7) strength += 1
//if password contains both lower and uppercase characters, increase strength value
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
//if it has numbers and characters, increase strength value
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 2
//if it has one special character, increase strength value
if (password.match(/([!,%,&,#,#,$,^,*,?,_,~])/)) strength += 3
//if it has two special characters, increase strength value
if (password.match(/(.*[!,%,&,#,#,$,^,*,?,_,~].*[!,%,&,#,#,$,^,*,?,_,~])/)) strength +=5
//now we ha
if(strength<=2)
{
$scope.final="Poor";
}
else
if(strength>2 && strength<=5)
{
$scope.final="Weak";
}
else
if(strength>5 && strength<=9)
{
$scope.final="Good";
}
if(strength>9)
{
$scope.final="Strong";
}
}
}
});
</script>
In order to use the $dirty & $pristine of your form in your controller you have to access them with $scope.
if ($scope.myfrm.textchecker.$dirty && !$scope.myfrm.textchecker.$pristine) {
var app = angular.module("myApp", []);
app.controller("outerCtrl", function($scope) {
$scope.processed = function(password) {
if ($scope.myfrm.textchecker.$dirty && !$scope.myfrm.textchecker.$pristine) {
console.log('!myfrm.textchecker.$dirty + !myfrm.textchecker.$pristine');
console.log(!myfrm.textchecker.$dirty + !myfrm.textchecker.$pristine);
// var password=$scope.ngdata;
var strength = 0;
//console.log(password);
// alert($scope.ngdata);
// if (password.length > 7) strength += 1
//if password contains both lower and uppercase characters, increase strength value
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
//if it has numbers and characters, increase strength value
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 2
//if it has one special character, increase strength value
if (password.match(/([!,%,&,#,#,$,^,*,?,_,~])/)) strength += 3
//if it has two special characters, increase strength value
if (password.match(/(.*[!,%,&,#,#,$,^,*,?,_,~].*[!,%,&,#,#,$,^,*,?,_,~])/)) strength += 5
//now we ha
if (strength <= 2) {
$scope.final = "Poor";
} else
if (strength > 2 && strength <= 5) {
$scope.final = "Weak";
} else
if (strength > 5 && strength <= 9) {
$scope.final = "Good";
}
if (strength > 9) {
$scope.final = "Strong";
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="outerCtrl">
<form name="myfrm">
<input type="password" name="textchecker" ng-change="processed(ngdata)" ng-model="ngdata" required/>
<input type="submit" name="submit" value="submit">
</form>
<span style="color:red" ng-show="myfrm.textchecker.$error.required">please enter the required text</span>
{{ngdata}}
<p>
{{final}}
</p>
<p>
$dirty : {{ myfrm.textchecker.$dirty }} $invalid : {{myfrm.textchecker.$invalid }} $pristine : {{myfrm.textchecker.$pristine }}
</p>
</div>
</body>
Related
I have an input element with a minRange and maxRange set and am trying to get a custom validity message. I also have a Input TagHelper to write a custom message that I am trying to override on client-side.
I have tried this so far and it doesn't seem to be working.
<input asp-for="Amount" minRange="50.00" maxRange="100.00" oninput="check(this)" />
<script type="text/javascript">
function check(input) {
if (input.validity.rangeUnderflow || input.validity.rangeOverflow) {
input.setCustomValidity("Please enter an amount between $50.00 and $100.00.");
}
}
</script>
Rendered html:
<input oninput="check(this)" type="text" data-val="true" data-val-number="The field Amount must be a number." data-val-required="The Amount field is required." id="Model_Amount" name="Model.Amount" value="97.95" data-val-range-min="50.00" data-val-range-max="100.00" data-val-range="Please enter an Amount between 50.00 and 100.00" class="form-control valid" placeholder="Amount" aria-required="true" aria-invalid="false" aria-describedby="Model_Amount-error">
It still inputs "Please enter Amount between 50.00 and 100.00"
input taghelper:
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (MinRange != null && MaxRange != null)
{
TagHelperAttribute minAttr = new TagHelperAttribute("data-val-range-min", MinRange);
output.Attributes.Add(minAttr);
TagHelperAttribute maxAttr = new TagHelperAttribute("data-val-range-max", MaxRange);
output.Attributes.Add(maxAttr);
TagHelperAttribute rangeAttr = new TagHelperAttribute("data-val-range", string.Format("Please enter a {0} between {1} and {2}", DisplayName, MinRange, MaxRange));
output.Attributes.Add(rangeAttr);
}
}
Any help is appreciated.
Thanks
NH
Changed your code with some comments added. Hope this helps
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<!-- Change minRange/maxRange to just min/max -->
<input asp-for="Amount" min="50.00" max="100.00" oninput="check(this)" />
<span id="display"></span>
</body>
<script type="text/javascript">
function check(input) {
//Get current input field value
var num = parseInt(document.querySelector('input').value);
//Check if num is < or > than input.min/max
if(num >= input.min && num <= input.max){
document.getElementById('display').innerText = '';
}else{
document.getElementById('display').innerText = 'Number must be between 50 and 100';
}
}
</script>
</html>
Hey I'm trying to figure out what is wrong with my code. The code is supposed to validate password with the requirement of having few special characters and setting its minimum length.
I got it to set on the right length but I can't seem to get the directive file working.
app.directive('myPassord',function()
{
return{
require:'ngModel',
link:function(scope,element,attr,myFormCtrl){
function myValidation(value)
{
if (value.indexOf("$") > -1 || value.indexOf("%") > -1 || value.indexOf("^") > -1 || value.indexOf("&") > -1 || value.indexOf("*") > -1){
myCtrl.$setValidity('Charactervalidator', false);
}else{
myCtrl.$setValidity('Charactervalidator', false);
}
return value;
}
myFormCtrl.$parsers.push(myValidation);
}
}
});
The html file
<div ng-controller = "myFormCtrl" class="form-group">
<form name ="Form1" novalidate="novalidate" class="Form1">
<p>
<label for = "password1" class= "col-lg-2">Password</label>
<input type="text" name="Password1" ng-model="user.password" ng-minlength ="8" required data-my-password>
<span ng-show="Form1.Password1.$touched && Form1.Password1.$invalid" style="color:red"> Password must contain at least 8 characters and a special character</span>
</p>
</form>
</div>
I correct your code. Try this code. Hope this helps you
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div class="form-group">
<form name="Form1" novalidate="novalidate" class="Form1">
<p>
<label for="password1" class="col-lg-2">Password</label>
<input type="text" name="Password1" ng-model="user.password" ng-minlength="8" required my-password>
<span ng-show="Form1.Password1.$touched && Form1.Password1.$invalid" style="color:red">
Password must contain at least 8 characters and a special character</span>
</p>
</form>
</div>
<h1>{{myForm.myInput.$valid}}</h1>
<script>
var app = angular.module('myApp', []);
app.directive('myPassword', function() {
return {
require: 'ngModel',
link: function(scope, element, attr, myFormCtrl) {
function myValidation(value) {
if (value.indexOf("$") > -1 ||
value.indexOf("%") > -1 ||
value.indexOf("^") > -1 ||
value.indexOf("&") > -1 ||
value.indexOf("*") > -1) {
myFormCtrl.$setValidity('Charactervalidator', true);
} else {
myFormCtrl.$setValidity('Charactervalidator', false);
}
return value;
}
myFormCtrl.$parsers.push(myValidation);
}
}
});
</script>
</body>
</html>
I have a pretty simple calculator that I am trying to setup.
<!DOCTYPE html>
<p>Crypto Currency Diversifier</p>
<div class="container">
<h1>Crypto Currency Diversifier</h1>
<form action="/action_page.php">
Dollars:<br>
<input type="text" name="dollars" value="500"><br><br>
# of Currencies:<br>
<input type="text" name="quantity" value="20"><br><br>
<input type="submit" value="Submit">
</form>
The next step is I need to pull the top 20 (quantity) cryptocurrencies, then divide the 500 (dollars) between them relative to market cap.
Here's the API website: https://coinmarketcap.com/api/
Clicking on https://api.coinmarketcap.com/v1/ticker/?limit=10 shows me the top 10 currencies.
How can I ADD up all the market caps of each individual currency on the page. Then create ratios from them?
Math part is pretty straightforward, what I don't get is how to actually pull the data from the API link and get it in a workable format.
Lookup Jquery and Ajax:
You can implement this like this:
function getCurrencies()
{
$.ajax(
{url:"https://api.coinmarketcap.com/v1/ticker/?limit=20",
success:function(data) {
//console.log(data);
var totalcap=0.0;
var u=$("<ul>");
for(var i=0;i<data.length;i++) {
var currency=data[i];
var cap=parseFloat(currency["market_cap_usd"]);
var li=$("<li />").html(currency["name"] + " " + cap.toFixed(2).replace(/./g, function(c, i, a) {
return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
}));
u.append(li);
totalcap+=cap;
}
$('#currlist').html('').append(u);
$('#cap').html(totalcap.toFixed(2).replace(/./g, function(c, i, a) {
return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
}));
$('#data').val(JSON.stringify(data));
},
error:function() {
alert("Error");
},
dataType:"json",
type:"get"}
);
}
textarea {width:600px;height:250px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<p>Crypto Currency Diversifier</p>
<div class="container">
<h1>Crypto Currency Diversifier</h1>
<form action="/action_page.php">
Dollars:<br>
<input type="text" name="dollars" value="500"><br><br>
# of Currencies:<br>
<input type="text" name="quantity" value="20"><br><br>
<input type="submit" value="Submit" onclick="getCurrencies(); return false"
>
Total Market Cap:<div id="cap"></div><br />
Currencies: <div id="currlist"></div><br />
<textarea id="data"></textarea>
</form>
The below code generates several forms depending on data returned from the server. Everything generates fine, but after clicking on an AnswerOpenQuestion button the input does not clear/reset. What's going on here?
angularJs code:
var availableInterviewController = function($scope, $http) {
// define initial model
$scope.interviews = [];
// retrieve available interviews
$http.get('/api/UserInterviewsApi/AvailableInterviews')
.success(function(data) {
// update interviews
$scope.interviews = [];
$scope.interviews = data;
});
// define open question answer selection
$scope.Answer = "";
// define multiple choice selection
$scope.selectedChoice = "";
// define answer open question button
$scope.AnswerOpenQuestion = function() {
$scope.Answer = ans;
alert(q.Question + ' and ' + $scope.Answer);
$scope.Answer = ''; // <---This is not clearing/resetting the HTML form inputs
};
// define answer multiple choice button
$scope.AnswerMultipleChoice = function() {
//
};
};
// assign the new controller to the main angular app
myAngApp.controller('availableInterviewCtrl', availableInterviewController);
Html code:
<form class="form-group" ng-repeat="q in inter.Questions">
<fieldset style="display: inline-block;">
<legend>Question {{$index + 1}}</legend>
<!--Open Ended-->
<div class="form-group" ng-show="q.MultipleChoices.length === 0">
<label for="{{'quest-' + $index}}">
<strong class="text-info">{{q.Question}}</strong><br />
</label>
<input name="openQuestion" id="{{'quest-' + $index}}" type="text"
class="form-control" ng-model="Answer" />
<button ng-click="AnswerOpenQuestion()">Answer</button><br />
<span class="text-info">
asked by {{q.AskedByUserName ==
'Administrator' ? 'staff' : q.AskedByUserName}}
</span>
</div>
<!--Multiple Choice Question-->
<div class="form-group" ng-show="q.MultipleChoices.length > 0">
<label for="{{'quest-' + $index}}">
<strong class="text-info">{{q.Question}}</strong>
</label>
<div>
Select an answer:
<label ng-repeat="x in q.MultipleChoices">
<input name="currentChoice" type="radio" value="{{x.Id}}"
ng-model="selectedChoice" />
{{x.Choice}}
</label>
<button ng-click="AnswerMultipleChoice()">Answer</button><br />
<span class="text-info">
asked by {{q.AskedByUserName ==
'Administrator' ? 'staff' : q.AskedByUserName}}
</span>
</div>
</div>
</fieldset>
</form>
UPDATE - Solution
AngularJs:
// define open question answer selection
$scope.OpenAnswer = { Answer: '' };
// define answer open question button
$scope.AnswerOpenQuestion = function (q, ans) {
$scope.OpenAnswer.Answer = ans;
alert(q.Question + ' and ' + $scope.OpenAnswer.Answer);
// clear the input
$scope.OpenAnswer.Answer = '';
};
Html:
<input id="{{'quest-' + $index}}" type="text"
class="form-control" ng-model="OpenAnswer.Answer" />
Don't use the scope as a model instead make an object that wraps the data model and assign it to a property of the scope.
$scope.myModel = {Answer:''}
Also don't use value in most cases ngmodel is all you need for two way binding.
In js strings are immutable so the original reference is not being updated instead a new string is being made, the digest cycle won't see this as a change to the original string.
I'm trying to write this extremely simple javascript app where the user can input two numbers and the sum of these two is automatically outputted to screen. I'm very new to javascript so I'm not sure where I went wrong. The following code will print NaN for a second after I press the button. Any idea as to how I handle this input better?
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var x = parseInt(first_num);
var y = parseInt(second_num);
var z = x + y;
var a = z.toString();
document.getElementById("demo").innerHTML = a;
}
</script>
</head>
<body>
<p>Enter two numbers to be added together.</p>
<form>
<input id="first_num" name="first_num" > first num<br>
<input id="second_num" name="second_num" > second num
<button onclick="myFunction()">calculate</button>
<p id="demo"></p>
</body>
</html>
var x = parseInt(first_num);
var y = parseInt(second_num);
Instead of first_num and second_num, you need to retrieve the value from the input boxes, like this
var x = parseInt(document.getElementById("first_num").value);
var y = parseInt(document.getElementById("second_num").value);
You have to use a selector to get the value of the two input elements:
var x = parseInt(document.getElementById('first_num').value);
var y = parseInt(document.getElementById('second_num').value);
...
And you have to close your form tag in your HTML use and use a <input type="button"> instead of <button> so your form doesn't post unnecessarily.
<form>
<input id="first_num" name="first_num" > first num <br />
<input id="second_num" name="second_num" > second num <br />
<input type="button" onclick="myFunction()" value="calculate">
</form>
Here is working demo.
The reason of NaN is you trying to parseInt with not initialized variable. beside this input tag is not closed.
function myFunction() {
document.getElementById("demo").innerHTML = parseInt(document.getElementById('first_num').value) + parseInt(document.getElementById('second_num').value);
}
and html:
<p>Enter two numbers to be added together.</p>
<input id="first_num" name="first_num" />first num
<br>
<input id="second_num" name="second_num" />second num
<button onclick="myFunction()">calculate</button>
<p id="demo"></p>
Here is a working sample:
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
</head>
<body>
<p>Enter two numbers to be added together.</p>
<input id="first_num" name="first_num">first num<br />
<input id="second_num" name="second_num">second num<br />
<button onclick="myFunction()">calculate</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("first_num").value;
var y = document.getElementById("second_num").value;
var z = ((x && x != "") ? parseInt(x) : 0) + ((y && y != "") ? parseInt(y) : 0);
document.getElementById("demo").innerHTML = z;
}
</script>
</body>
</html>
Do the following:
<p>Enter two numbers to be added together.</p>
<form>
<input id="first_num" name="first_num" > first num<br>
<input id="second_num" name="second_num" > second num
<button onclick="myFunction(parseInt(document.getElementById("first_num").value),parseInt(document. getElementById("second_num").value))">calculate</button>
<p id="demo"></p>
function myFunction(first_num,second_num)
{
var x = parseInt(first_num);
var y = parseInt(second_num);
var z = x + y;
var a = z.toString();
document.getElementById("demo").innerHTML = a;
}