assign unique id to radio button on selection - javascript

I am trying to assign unique id to radio button on select. I am not sure this is right way. I tried like this:
<!DOCTYPE html>
<html ng-app="radioExample">
<head>
<script data-require="angular.js#1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
</head>
<body>
<script>
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.startDate = {
id: new Date()
};
$scope.specialValue = {
"value": new Date().getMilliseconds()
};
$scope.uniqueId = new Date().getMilliseconds();
}]);
</script>
<form ng-controller="ExampleController" name="myForm">
<label>
<input type="radio" name="rdboption" ng-value="specialValue" ng-model="startDate.id" id="{{::uniqueId}}" />
Jan
</label>
<br />
<label>
<input type="radio" name="rdboption" ng-value="specialValue" ng-model="startDate.id" id="{{::uniqueId}}" />
Feb
</label>
<br />
<label>
<input type="radio" name="rdboption" ng-value="specialValue" ng-model="startDate.id" id="{{::uniqueId}}" />
Mar
</label>
<br />
<tt>ID = {{uniqueId | json}}</tt>
<br />
</form>
Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
</body>
</html>
This prints the same value for all the radio buttons even after adding timestamp in milliseconds

It's adding the same value, because it's the same value, you are using only one variable, assigning once on the controller and then using the same variable three times.
Anyway why do you need to assign a unique id, to each input.
You could solve it, decalring a function on your controller that returns the unique id, and invoking it from your view.

You can create a function in your scope like this:
JSFiddle Demo
HTML:
<!DOCTYPE html>
<html ng-app="radioExample">
<head>
<script data-require="angular.js#1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
</head>
<body>
<script>
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.startDate = {
id: new Date()
};
$scope.specialValue = {
"value": new Date().getMilliseconds()
};
$scope.getUId = function() {
var charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var charSetSize = charSet.length;
var id = '';
for (var i = 1; i <= 4; i++) {
var randPos = Math.floor(Math.random() * charSetSize);
id += charSet[randPos];
}
return id;
}
}]);
</script>
<form ng-controller="ExampleController" name="myForm">
<label>
<input type="radio" name="rdboption" ng-value="specialValue" ng-model="startDate.id" id="{{::getUId()}}" /> Jan
</label>
<br />
<label>
<input type="radio" name="rdboption" ng-value="specialValue" ng-model="startDate.id" id="{{::getUId()}}" /> Feb
</label>
<br />
<label>
<input type="radio" name="rdboption" ng-value="specialValue" ng-model="startDate.id" id="{{::getUId()}}" /> Mar
</label>
<br />
</form>
</body>
</html>
edit: You may change the charSet to suit your domain of acceptable characters in unique id.

Solution:
html:
<input type="radio" name="rdboption" ng-value="specialValue" ng-model="startDate.id" id="{{uniqueId()}}" />
js:
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.startDate = {
id: new Date()
};
$scope.specialValue = {
"value": new Date().getMilliseconds()
};
$scope.uniqueId = function() {
return new Date().getMilliseconds();
  };
}]);

Related

Cannot set property 'onclick' of null (I have already added id)

I have already added id in HTML for JS, but when I open the website, it still displays an error:
Uncaught TypeError: Cannot set property 'onclick' of null
Please help.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="jquery-1.7.2.js" type="text/javascript"></script>
<script>
var btn = document.getElementById("btn");
btn.onclick = function() {
var arrays = new Array();
var items = document.getElementsByName("check");
for(var i=0;i<items.length;i++) {
if(items[i].checked) {
arrays.push(items[i].value);`enter code here`
}
}
alert("numbers checked:" + arrays.length);
}
</script>
</head>
<body>
<input type="checkbox" value="1" name="check" checked/>
<input type="checkbox" value="2" name="check"/>
<input type="checkbox" value="3" name="check" checked/>
<input type="button" value="numbers you have checked" id="btn"/>
</body>
</html>
Try this
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<input type="checkbox" value="1" name="check" checked/>
<input type="checkbox" value="2" name="check" />
<input type="checkbox" value="3" name="check" checked/>
<input type="button" value="numbers you have checked" id="btn" />
<script src="jquery-1.7.2.js" type="text/javascript"></script>
<script>
var btn = document.getElementById("btn");
btn.onclick = function () {
var arrays = new Array();
var items = document.getElementsByName("check");
for (var i = 0; i < items.length; i++) {
if (items[i].checked) {
arrays.push(items[i].value);
}
}
alert("numbers checked:" + arrays.length);
}
</script>
</body>
</html>
Instead of using an input, use a button. and call the function as below:
<button id="btn" onclick="myFunction()">

Use data from localStorage in HTML

By using the advanced settings page.
And I try, depending on the selected radiobatton change the name of the units (units themselves vary in the query (!)).
Example:
$scope.savecity=function(){
localStorage["var"]=$scope.username;
localStorage["SystemOfNumbers"]=$scope.SystemOfNumbers;
<label>
<input type="radio" ng-model="SystemOfNumbers" value="metric">
Metric
</label>
<label>
<input type="radio" ng-model="SystemOfNumbers" value="imperial">
Imperial
</label><br/>
<button ng-click='savecity()'>Submit</button>
$scope.savecity=function(){
localStorage["var"]=$scope.username;
localStorage["SystemOfNumbers"]=$scope.SystemOfNumbers;
if (localStorage[SystemOfNumbers]="metrical"){
localStorage["icon"]="°C"
}
else {
localStorage["icon"]="°F"
}
}
And popup.html:
{{vm.data.list[0].temp.day}}{{localStorage["icon"]}}
That is, the selector is activated, changing the way of translation, but does not change the display unit.
Source: http://zalil.su/9855055
Answer:
You can enter city name on options page (but onle English)
(function(angular) {
'use strict';
angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
$scope.username = '';
$scope.sayHello = function() {
$scope.greeting = 'Hello ' + $scope.username + '!';
};
$scope.savecity=function(){
localStorage["var"]=$scope.username;
localStorage["SystemOfNumbers"]=$scope.SystemOfNumbers;
};
}]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
-<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Angular JS</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="angular.min.js"></script>
<script src="weather 2.js"></script>
</head>
<body ng-app="scopeExample">
<div ng-controller="MyController">
Enter city name:
<input type="text" ng-model="username">
<label>
<input type="radio" ng-model="SystemOfNumbers" value="metric">
Metric
</label>
<label>
<input type="radio" ng-model="SystemOfNumbers" value="imperial">
Imperial
</label><br/>
<button ng-click='savecity()'>greet</button>
Назад
</div>
</body>
</html>

How do I combine input type date and input type time in one

I have an angularjs UI which asks the user to input a date and a time. Now I want to combine the two in one date type so that I can send it to REST API. How do I do it?
My html code is
<div class="col-md-7">
<input type="date" id="exampleInput" ng-model="UIcontroller.JobDataModel.date"
placeholder="yyyy-mm-dd" required/>
<div class="col-md-7">
<input type="time" id="exampleInput1" ng-model="UIcontroller.JobDataModel.time"
placeholder="hh:mm:ss:" required/>
How do I do it in the controller ? Should I just concatenate the two ng- models?
no need to add to input field, you can use one input field for both date and time, here is the code
<html>
<head>
<title>User Input</title>
<link rel="stylesheet" href="styles.css">
<script src="https://code.angularjs.org/2.0.0-beta.0/angular2-polyfills.js"></script>
<script src="https://code.angularjs.org/tools/system.js"></script>
<script src="https://code.angularjs.org/tools/typescript.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.0/Rx.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.0/angular2.dev.js"></script>
<script>
System.config({
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true },
packages: {'app': {defaultExtension: 'ts'}}
});
System.import('app/boot')
.then(null, console.error.bind(console));
</script>
</head>
<body>
<my-app>Loading... </my-app>
</body>
</html>
you need to import app/boot
You can combine date & time input by following way-
<input type="datetime-local" name="dateTime" id="exampleInput3" ng-model="UIcontroller.JobDataModel.datetime">
Hope this will hep you.
Try this... for your input field add "ng-model-options="{ getterSetter: true }"
example:
<input type="date" id="exampleInput" ng-model="UIcontroller.JobDataModel.date"
placeholder="yyyy-mm-dd" ng-model-options="{ getterSetter: true }" required/>
once you have getterSetter set to true you can access the value entered by user in your controller...
var _date = new Date();
var _time = new Date();
$scope.UIcontroller = {};
$scope.UIcontroller.JobDataModel = {
date: function(newDate) {
return arguments.length ? (_date = newDate) : _date;
},
time: function(newTime) {
return arguments.length ? (_time = newTime) : _time;
},
finalDate: function() {
return (_date.getMonth() + 1) + '/' + _date.getDate() + '/' + _date.getFullYear() + ' ' + _time.getHours() + ':' + _time.getMinutes();
}
};
You can see my rough solution here: https://plnkr.co/edit/BjXL114HLl2qMqy0wpOR?p=preview
Good luck!
You can combine date and time, by creating a date-time string by joining both of them first and then, parsing it into a date.
var myApp = angular.module('myApp', []);
myApp.controller('myController', ['$scope',
function($scope) {
$scope.UIcontroller = {
JobDataModel: {
date: new Date(),
time: new Date()
}
};
$scope.result = '';
$scope.updateResult = function() {
var myDate = $scope.UIcontroller.JobDataModel.date,
myTime = $scope.UIcontroller.JobDataModel.time,
combinedDateString = (myDate.toDateString() + " " + myTime.toTimeString()),
combinedDate = new Date(combinedDateString);
$scope.result = combinedDate;
}
$scope.updateResult();
}
]);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form ng-app="myApp" ng-controller="myController">
<div class="col-md-7">
<input type="date" class="form-control" id="myDate" ng-model="UIcontroller.JobDataModel.date" placeholder="yyyy-mm-dd" ng-change='updateResult()' required/>
</div>
<div class="col-md-7">
<input type="time" class="form-control" id="myTime" ng-model="UIcontroller.JobDataModel.time" placeholder="hh:mm:ss:" ng-change='updateResult()' required/>
<div>Result: [{{result.toString()}}]</div>
</div>
</div>
</form>
</body>
</html>

Error in AngularJS script output

I'm new to AngJS and I'm trying to write code on my own. I got stuck in one part.
Code:
<!DOCTYPE HTML>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<title> First page </title>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="person.firstName"> <br>
Last Name: <input type="text" ng-model="person.lastName"> <br>
<p> {{person.firstName + " " + person.lastName}} age is: {{age[0]}}</p>
</div>
<div ng-app="mApp" ng-controller="mCtrl">
Registration number: <input type="number" ng-model="person.regNum"> <br>
Class number: <input type="text" ng-model="person.classNum"> <br>
<p> {{person.regNum, person.classNum}} </p>
</div>
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope) {
$scope.person = {firstName:"Nikhil",lastName:"Hegde"};
$scope.age = [20,21,22];
});
var app1 = angular.module('mApp',[]);
app1.controller('mCtrl',function($scope) {
$scope.person = {regNum:"122503",classNum:"12EC48"};
});
</script>
</body>
</html>
I'm not really sure what is wrong with the second pair of fields but the output as you can see is incorrect.
Also can I reuse the app variable?
app = angular.module('myApp',[]);
Instead of using a separate 'app1' variable, can I also reuse the same variable 'app' as:
app = angular.module('mApp',[]);
You should have only one app
<!DOCTYPE HTML>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<title> First page </title>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl">
First Name: <input type="text" ng-model="person.firstName"> <br>
Last Name: <input type="text" ng-model="person.lastName"> <br>
<p> {{person.firstName + " " + person.lastName}} age is: {{age[0]}}</p>
</div>
<div ng-controller="mCtrl">
Registration number: <input type="number" ng-model="person.regNum"> <br>
Class number: <input type="text" ng-model="person.classNum"> <br>
<p> {{person.regNum, person.classNum}} </p>
</div>
<script>
var app = angular.module('myApp',[])
.controller('myCtrl',function($scope) {
$scope.person = {firstName:"Nikhil",lastName:"Hegde"};
$scope.age = [20,21,22];
})
.controller('mCtrl',function($scope) {
$scope.person = {regNum:"122503",classNum:"12EC48"};
});
</script>
</body>
</html>
<body>
<div ng-app="myApp">
<div ng-controller="myCtrl">
First Name: <input type="text" ng-model="person.firstName"> <br>
Last Name: <input type="text" ng-model="person.lastName"> <br>
<p> {{person.firstName + " " + person.lastName}} age is: {{age[0]}}</p>
</div>
<div ng-controller="mCtrl">
Registration number: <input type="number" ng-model="person.regNum"> <br>
Class number: <input type="text" ng-model="person.classNum"> <br>
<p> {{person.regNum+ " "+ person.classNum}} </p>
</div>
</div>
Script file
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope) {
$scope.person = {'firstName':"Nikhil",'lastName':"Hegde"};
$scope.age = [20,21,22];
});
app.controller('mCtrl',function($scope) {
$scope.person1 = {'regNum':"122503",'classNum':"12EC48"};
});
define your app only once. You can add multiple controller to ng-module.
Hope It will be useful.
You can have only 1 module in an app, have different scope variable inside same controller
var app = angular.module('myApp', []);
app.controller("myCtrl", ["$scope", "$http",
function($scope, $http) {
$scope.person = {
firstName: "Nikhil",
lastName: "Hegde"
};
$scope.registration = {
regNum: "122503",
classNum: "12EC48"
};
$scope.age = [20, 21, 22];
}
]);
DEMO

Making a sum with 4 values and a button

I'm trying to make a sum of 4 entries in 4 text type and everything seems fine except that when I click the button, it won't set the sum. Like if I enter 1 in each text input, the text input for the sum should show 4. Thanks!
here's my Javascript code :
(function(){
var oForm = document.forms;
oForm[2].querySelector("input[type='button']").
addEventListener("click",
sommeValeur,
false);
}) ()
function sommeValeur() {
var aTxt = document.forms[0].tEx1;
var total = document.forms[0].tEx2;
var txt1 = aTxt[0].value;
var txt2 = aTxt[1].value;
var txt3 = aTxt[2].value;
var txt4 = aTxt[3].value;
total = parseInt(txt1) + parseInt(txt2) + parseInt(txt3) + parseInt(txt4) ;
return true;
}
Here's my html code :
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/form.css" />
</head>
<body>
<section>
<form name="frm1">
<label> Valeur 1:
<input type="text" name="tEx1" />
</label>
<label> Valeur 2:
<input type="text" name="tEx1" />
</label>
<label> Valeur 3:
<input type="text" name="tEx1" />
</label>
<label> Valeur 4:
<input type="text" name="tEx1" />
</label>
</form>
</section>
<section>
<form name="frm2">
<label> Somme:
<input type="text" name="tEx2" />
</label>
</form>
</section>
<section>
<form name="frm3">
<label>
<input type="button"
value="bouton"
name="btn1" /></br>
</label>
</form>
</section>
</body>
<script src="js/exercise4.js"></script>
</html>
It looks like your input for total is in the second form, so you need form[1] and also you need to use total.value to set the value:
var total = document.forms[1].tEx2;
...
total.value = parseInt(txt1) + parseInt(txt2) + parseInt(txt3) + parseInt(txt4) ;
Live example:
(function(){
var oForm = document.forms;
oForm[2].querySelector("input[type='button']").
addEventListener("click",
sommeValeur,
false);
}) ()
function sommeValeur() {
var aTxt = document.forms[0].tEx1;
var total = document.forms[1].tEx2;
var txt1 = aTxt[0].value;
var txt2 = aTxt[1].value;
var txt3 = aTxt[2].value;
var txt4 = aTxt[3].value;
total.value = parseInt(txt1) + parseInt(txt2) + parseInt(txt3) + parseInt(txt4) ;
return true;
}
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/form.css" />
</head>
<body>
<section>
<form name="frm1">
<label> Valeur 1:
<input type="text" name="tEx1" />
</label>
<label> Valeur 2:
<input type="text" name="tEx1" />
</label>
<label> Valeur 3:
<input type="text" name="tEx1" />
</label>
<label> Valeur 4:
<input type="text" name="tEx1" />
</label>
</form>
</section>
<section>
<form name="frm2">
<label> Somme:
<input type="text" name="tEx2" />
</label>
</form>
</section>
<section>
<form name="frm3">
<label>
<input type="button"
value="bouton"
name="btn1" /></br>
</label>
</form>
</section>
</body>
</html>
You are changing the total instance and not the total.value.
In the line total = ...+...+..+...; you are basically replacing the label with the sum. You should set the label text instead: total.value = ...+..+...+...;

Categories