AngularJS 1.3 Migration Not Working - javascript

I have updated my script code to the following after reading about documentation on migrating from 1.2 to 1.3.
var app = angular.module("APP", []);
app.controller('Ctrl', function ($scope) {
$scope.id = [{
id: 'id #1'
}];
$scope.addNewId = function () {
var newId = $scope.id.length + 1;
$scope.id.push({
'id': 'id #' + newId
});
};
$scope.removeId = function (index) {
if (index >= 1) {
$scope.id.splice(index, 1);
}
};
});
This is the code for the form:
<!DOCTYPE html>
<html lang = "en" ng-app = "APP">
<head>
<meta charset = "utf-8">
<title>Add New ID</title>
<link rel="stylesheet" href="form.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
<script type = "text/javascript" src = "form.js"></script>
</head>
<body ng-controller="Ctrl">
<section>
<h1>Add New Stuff</h1>
<form name = "form" id = "form">
<div ng-model = "indiv">
<fieldset class="ids" data-ng-repeat="indiv in id">
<legend>ID</legend>
<label for="name">Name:</label>
<input type="text" name="name" id="name" size="60">&nbsp
<label for="age">Age:</label>
<input type="text" name="age" id="age" size="60">&nbsp
<button type="button" name="lookup" id="lookup">LOOKUP</button>&nbsp
<button class="remove" ng-click="removeId($index)">Remove ID</button><br>
</fieldset>
<br>
<button class="addfields" ng-click="addNewId()">Add ID</button>
</div>
<input type="submit" name="submit" id = "submit" value="SUBMIT">
</form>
</section>
</body>
It is supposed to add a new set of input fields to a form. Please help

An id attribute can't contain space nor sharp character here you are setting :
{id: 'id #1'}
May be a part of the answer if you're attributing this value to the id of each input in your ng-repeat.
can you show us the form ?

Related

I am having trouble with HTML Javascript inclusion

I'm trying to use the information that I obtain through a form via a submit button, do a little processing, and print it out onto the web page, preventing it from being submitted to a web server by including (return false).
Here is the code to the page:
<html>
<head>
<title>SmithSellsStuff</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
var myData = {
price: "4.25",
taxRate: "0.07",
shipRate: "0.02"
};
myData.calculateTotal = function() {
myData.name = document.getElementById("name");
myData.date = document.getElementById("date");
myData.numItems = document.getElementById("number of items");
var itemTotal = myData.numItems * myData.price;
var taxTotal = (myData.numItems * myData.price) * myData.taxRate;
var shipTotal = (myData.numItems * myData.price) * myData.shipRate;
document.writeln(itemTotal);
document.writeln(taxTotal);
document.writeln(shipTotal);
};
</script>
<form>
</p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
</p>
<label>Number of items: <input type="number" name="number of items" id="number of items" tabindex="3"/></label>
</p>
<input type="submit" onclick="calculateTotal(); return false;"/>
</form>
</body>
</html>
On the first page, I have a simple form with a field for name, date, number of items total, and a submit button. One error I'm getting is in the onclick tag. It says '_kof_1' is defined but never used. I don't think it is allowing my calculateTotal function to call.
It's because the function was not declared in the global scope, but rather as a property of myData.
myData.calculateTotal = function() {
To solve this, simply change the call to:
<input type="submit" onclick="myData.calculateTotal(); return false;"/>
Furthermore, since you want to get the name, date, and number of items from the text fields, you have to get the .value property to get the contents of the input fields, like so:
myData.name = document.getElementById("name").value;
myData.date = document.getElementById("date").value;
myData.numItems = parseInt(document.getElementById("number of items").value);
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
function calculateTotal()
{
alert("hai");
var price="4.25";
var taxRate="0.07";
var shipRate="0.02";
var name = document.getElementById("name");
var date = document.getElementById("date");
var numItems = document.getElementById("number_of_items").value;
alert(numItems);
var itemTotal = numItems * price;
var taxTotal = (numItems * price) * taxRate;
var shipTotal = (numItems * price) * shipRate;
document.writeln("Total Items:"+itemTotal+"\tTax :"+taxTotal+"\tshipTotal:"+shipTotal);
}
</script>
<form>
<p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
<p>
<label>Number of items: <input type="number" name="number_of_items" id="number_of_items" tabindex="10"/></label>
</p>
<input type="submit" onclick="calculateTotal()"/>
</form>
</body>
</html>
alert is just for to know method is calling or not, Hope this will help you

Angularjs dynamic form contents

Here is my angular view,
<label class="control-label">skipColumns:</label>
<br />
<fieldset ng-repeat="skipColumn in config.skipColumns track by $index">
<input type="text" class="form-control" ng-model="skipColumn[0]" /><br />
</fieldset>
<button class="btn btn-default" ng-click="addNewSkipColumn(skipColumn)">Add SkipColumn</button>
<br />
which adds new textfield every time i click addSkipColumn button.
here is my js code:
$scope.config.skipColumns = [];
$scope.addNewSkipColumn = function (skipColumn) {
if($scope.config.skipColumns==null){
$scope.config.skipColumns=[];
}
$scope.config.skipColumns.push([]);
}
so the problem is when I display or see the structure of $scope.config.skipColumns, It gives the following output:
{
skipColumns:[["content of textfield1"],["content of textfield1"]..]
}
But what I need is,`
{
skipColumns:["content of textfield1","content of textfield1",..]
}
please help me.("content of textfield" resfers to form data)
What you need here is to change what you are pushing in config.skipColumns array. Like this:
$scope.addNewSkipColumn = function(skipColumn) {
$scope.config.skipColumns.push("");
}
And, ng-repeat would be like:
<fieldset ng-repeat="skipColumn in config.skipColumns track by $index">
<input type="text" ng-model="config.skipColumns[$index]" />
</fieldset>
(why did I not use skipColumn directly in the ng-model?)
Here's working example:
angular.module("myApp", [])
.controller("ctrl", function($scope) {
$scope.config = {};
$scope.config.skipColumns = [];
$scope.addNewSkipColumn = function(skipColumn) {
$scope.config.skipColumns.push("");
}
})
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp" ng-controller="ctrl">
<label class="control-label">skipColumns:</label>
<br />
<fieldset ng-repeat="skipColumn in config.skipColumns track by $index">
<input type="text" class="form-control" ng-model="config.skipColumns[$index]" />
</fieldset>
<button class="btn btn-default" ng-click="addNewSkipColumn()">Add SkipColumn</button>
<br />
<br>
<pre>{{config.skipColumns}}</pre>
</body>
</html>
See this... Just push value instead of array.
var app = angular.module('angularjs', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = ['choice1'];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push('choice'+newItemNo);
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div ng-app="angularjs" ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<select>
<option>Mobile</option>
<option>Office</option>
<option>Home</option>
</select>
<input type="text" ng-model="choice.name" name="" placeholder="Enter mobile number">
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
<div id="choicesDisplay">
{{ choices }}
</div>
</div>

HTML onsubmit event is not calling the JavaScript function

I have two buttons in my form for calling two JavaScript functions. The first button works good in its onclick event calling the payroll() function successfully but the second button is of type submit and it never calls the send() function on form submission. I don't know why this issue occurs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html >
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{{ g.sijax.get_js()|safe }}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript" >
function payroll() {
var basic=document.forms["salary"]["bsalary"].value;
var empid=document.forms["salary"]["empid"].value;
var ta,hra,da,pf,netsalary,grosssalary;
if (empid == ""||basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if(isNaN(basic))
{alert("Salary must be in Numbers");
return false;
}
hra=basic*40/100;
da=basic*15/100;
pf=basic*12/100;
basic=parseInt(basic);
hra=parseInt(hra);
da=parseInt(da);
grosssalary=basic + hra + da;
ta=basic*6.2/100;
netsalary=grosssalary-ta;
document.getElementById("hra").innerHTML=hra;
document.getElementById("ta").innerHTML=ta;
document.getElementById("da").innerHTML=da;
document.getElementById("netsalary").innerHTML=netsalary;
document.getElementById("pf").innerHTML=pf;
document.getElementById("grosssalary").innerHTML=grosssalary;
window.alert("HI"+grosssalary);
return true;
}
function send()
{
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.forms['salary']['hra'].value;
var da = document.forms['salary']['da'].value;
var ta = document.forms['salary']['ta'].value;
var pf = document.forms['salary']['pf'].value;
var gross_sal = document.forms['salary']['grosssalary'].value;
window.alert("HI"+gross_sal);
var net_sal = document.forms['salary']['netsalary'].value;
Sijax.request('send',[id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%" >
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return send()" >
<label id = "empid">Employee ID</label><br>
<input type = "text" name = "empid" placeholder = "Employee ID" /><br><br>
<label id = "bsalary">Basic Salary</label><br>
<input type = "text" name = "bsalary" placeholder = "Basic salary" /><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for ="hra">House Rent Allowance(HRA)</label>
<p id="hra" name="hra"></p><br>
<label for ="ta">Travel Allowance(TA)</label>
<p id="ta" name="ta"></p><br>
<label for ="da"> Dearness Allowance(DA)</label>
<p id="da" name="da"></p><br>
<label for ="netsalary">Net Salary</label>
<p id="netsalary" name="netsalary"></p><br>
<label for ="pf">Provident Fund(PF)</label>
<p id="pf" name ="pf"></p><br>
<label for ="grosssalary">Gross Salary</label>
<p id="grosssalary" name="grosssalary"></p><br><br>
<input type="submit" value="Upload Salary">
</form>
</div>
</body>
</html>
You can't act with <p> elements like as a form-elements. You may create a respective <input type="hidden"> elements and fill them in payroll(), or get values by .innerHtml on paragraphs.
P.S. You have actually a TypeError exception, calling undeclared form elements like document.forms['salary']['grosssalary'] and so on.
okay, quick fix, since you are using python flask library Sijax for ajax and therefore jQuery, you can alter your javascript send function like this:
function send(e){
e.preventDefault(); //it is as good as returning
//false from the function in all cases
var id = document.forms['salary']['empid'].value;
...
}
and change your onsubmit handler declaration like this:
<form id="salary" name="salary" style="margin-top: 2%" method="post"
onsubmit="return send(event)" >
please note that when you stop the event chain propagation, you will have to do a manual submission of the form.
So, you can modify your send function to do .preventDefault based on your custom criterias, otherwise, let the form submit
Your code actually works, if you're running this code as a snippet here in stack overflow, Form submission is actually blocked by default. Try running your code in codepen. I tried it and it's actually working.
http://codepen.io/jhonix22/pen/VPZagb
Check this out. It is nowhere close to a perfect solution but I think it helps. You can not access the paragraphs as if you would the form input elements. Im not entirely sure what Sijax thing is. I believe it is just a normal AJAX HTTP thing with some sort of CSRF security filters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{
{
g.sijax.get_js() | safe
}
}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript">
function payroll() {
var basic = document.forms["salary"]["bsalary"].value;
var empid = document.forms["salary"]["empid"].value;
var ta, hra, da, pf, netsalary, grosssalary;
if (empid == "" || basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if (isNaN(basic)) {
alert("Salary must be in Numbers");
return false;
}
hra = basic * 40 / 100;
da = basic * 15 / 100;
pf = basic * 12 / 100;
basic = parseInt(basic);
hra = parseInt(hra);
da = parseInt(da);
grosssalary = basic + hra + da;
ta = basic * 6.2 / 100;
netsalary = grosssalary - ta;
document.getElementById("hra").innerHTML = hra;
document.getElementById("ta").innerHTML = ta;
document.getElementById("da").innerHTML = da;
document.getElementById("netsalary").innerHTML = netsalary;
document.getElementById("pf").innerHTML = pf;
document.getElementById("grosssalary").innerHTML = grosssalary;
window.alert("HI" + grosssalary);
return true;
}
function send() {
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.getElementById('hra').innerHTML;
var da = document.getElementById('da').innerHTML;
var ta = document.getElementById('ta').innerHTML;
var pf = document.getElementById('pf').innerHTML;
var gross_sal = document.getElementById('grosssalary').innerHTML;
window.alert("HI" + gross_sal);
var net_sal = document.getElementById('netsalary').innerHTML;
// I think you are missing something here.
Sijax.request('send', [id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%">
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return false">
<label id="empid">Employee ID</label><br>
<input type="text" name="empid" placeholder="Employee ID"/><br><br>
<label id="bsalary">Basic Salary</label><br>
<input type="text" name="bsalary" placeholder="Basic salary"/><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for="hra">House Rent Allowance(HRA)</label><br>
<p id="hra" readonly name="hra"></p>
<label for="ta">Travel Allowance(TA)</label><br>
<p id="ta" readonly name="ta"></p>
<label for="da"> Dearness Allowance(DA)</label><br>
<p id="da" readonly name="da"></p>
<label for="netsalary">Net Salary</label><br>
<p id="netsalary" readonly name="netsalary"></p>
<label for="pf">Provident Fund(PF)</label><br>
<p id="pf" readonly name="pf"></p>
<label for="grosssalary">Gross Salary</label><br>
<p id="grosssalary" readonly name="grosssalary"></p><br>
<input type="button" onclick="send()" value="Upload Salary">
</form>
</div>
</body>
</html>

Filling data in form using angular

I am a true beginner at Angular (but not JS), started yesterday, so I hope you forgive me if this question sound stupid. Consider the following small application:
HTML:
<!doctype html>
<html ng-app="todoApp">
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="/js/TestController.js"></script>
</head>
<body ng-controller="TestController as myControl">
<div id="overlaybox">
<button ng-click="myControl.showUpd(4)">Test</button><br/><br/><br/>
<form ng-submit="myControl.updTodo()">
Note:<br/>
<textarea rows="5" cols="30" id="updContent" ng-model="noteupd.content"></textarea><br/>
Deadline (format YYYY-MM-DD HH:MM):<br/>
<input type="text" id="updDeadline" ng-model="noteupd.deadline" /><br/>
Completed:
<input type="checkbox" id="updCompleted" ng-model="noteupd.completed" /><br/>
<input type="hidden" id="updID" ng-model="noteupd.id" /><br/>
<input type="submit" value="Update" />
</form>
</div>
</body>
</html>
Angular-controller:
angular.module('todoApp', []).controller('TestController', function($scope, $http) {
var thisApp = this;
thisApp.showUpd = function(noteID) {
$http({method : 'GET', url : 'http://localhost:8000/notes/' + noteID})
.then (function(response) {
console.log(response.data.content);
console.log(response.data.deadline);
console.log(response.data.id);
console.log(response.data.completed);
document.getElementById("updContent").innerHTML = response.data.content;
document.getElementById("updDeadline").value = response.data.deadline;
document.getElementById("updID").value = response.data.id;
if (response.data.completed == 1) {
document.getElementById("updCompleted").checked = true;
} else {
document.getElementById("updCompleted").checked = false;
}
}, function() {
alert("Error getting todo note");
});
}
thisApp.updTodo = function(noteupd) {
console.log("TEST");
console.log($scope.noteupd);
}
});
After clicking Test-button I get the following output in my console:
TestController.js:7 123123
TestController.js:8 2016-01-05 10:28:42
TestController.js:9 4
TestController.js:10 0
By then, the fields in the form have been filled in (and the hidden field has a value). And after clicking Update I get this in the console:
TestController.js:27 TEST
TestController.js:28 undefined
If i change the values in the fields manually, I do get something else instead of "undefined", but the idea is that one should not have to change the values. Also, the object does not contain the hidden "id" even if all fields are changed.
Obviously, I'm a beginner at this, and obviously I'm doing it wrong, but do anyone have a suggestion on how I can make this work?
Your html is fine but your code needs fixing
First define noteupd in your code
Use noteupd to change your html values rather then document.getElementById
That should fix your code it will end up looking like this
angular.module('todoApp', []).controller('TestController', function($scope, $http) {
var thisApp = this;
$scope.noteupd={}; //defining noteupd
var noteupd=$scope.noteupd; //preventing scope issues
thisApp.showUpd = function(noteID) {
$http({method : 'GET', url : 'http://localhost:8000/notes/' + noteID})
.then (function(response) {
console.log(response.data.content);
console.log(response.data.deadline);
console.log(response.data.id);
console.log(response.data.completed);
//updating your html
noteupd.content= response.data.content;
noteupd.deadline = response.data.deadline;
noteupd.id= response.data.id;
if (response.data.completed == 1) {
noteupd.completed = true;
} else {
noteupd.completed = false;
}
}, function() {
alert("Error getting todo note");
});
}
thisApp.updTodo = function(noteupd) {
console.log("TEST");
console.log($scope.noteupd);
}
});
If you are using this variable against $scope .. you have always ng-controller with alias , and you can only access properties or methods of controller with controller alias only ..
if you didnt use ng-controller= "TestController as myController"
and not access methods as myController.method() .. your example won't be worked...(section 2)
Here is some examples to describe you how it is work
Check this tutorial too ..
http://plnkr.co/edit/FgBcahr6WKAI2oEgg4cO?p=preview
angular.module('todoApp', []).controller('TestController', function($scope, $http) {
var thisApp = this;
$scope.readedTodo = {};
this.noteupd = {};
thisApp.showUpd = function(noteID) {
// changed your url as defat json data
$http({
method: 'GET',
url: 'data.json'
})
.then(function(response) {
console.log(response.data);
console.log(response.data.content);
console.log(response.data.deadline);
console.log(response.data.id);
console.log(response.data.completed);
thisApp.noteupd = response.data;
$scope.readedTodo = response.data;
}, function() {
alert("Error getting todo note");
});
}
thisApp.updTodo = function(noteupd) {
console.log("TEST");
console.log(thisApp.noteupd);
}
});
<!doctype html>
<html ng-app="todoApp">
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="overlaybox" ng-controller="TestController as myControl">
<button ng-click="myControl.showUpd(4)">Test</button>
<br/>
<br/>
<br/>
<form ng-submit="myControl.updTodo()">
<h3>if you use binding h this against $scope</h3> Note:
<br/>
<textarea rows="5" cols="30" id="updContent" ng-model="myController.noteupd.content"></textarea>
<br/> Deadline (format YYYY-MM-DD HH:MM):
<br/>
<input type="text" id="updDeadline" ng-model="myController.noteupd.deadline" />
<br/> Completed:
<input type="checkbox" id="updCompleted" ng-model="myController.noteupd.completed" />
<br/>
<h3>if you use binding with $scope</h3> Note:
<br/>
<textarea rows="5" cols="30" id="updContent2" ng-model="readedTodo.content"></textarea>
<br/> Deadline (format YYYY-MM-DD HH:MM):
<br/>
<input type="text" id="updDeadline222" ng-model="readedTodo.deadline" />
<br/> Completed:
<input type="checkbox" id="updCompleted" ng-model="readedTodo.completed" />
<br/>
<input type="hidden" id="updID" ng-model="readedTodo.id" />
<br/>
<input type="submit" value="Update" />
</form>
</div>
<h3>SEction 2 </h3>
<div id="overlaybox2" ng-controller="TestController ">
<button ng-click="showUpd(4)">Test</button>
<button ng-click="showUpdate(4)">Test</button>
<br/>
<br/>
<br/>
<form ng-submit="updTodo()">
<h3>if you use binding h this against $scope</h3> Note:
<br/>
<textarea rows="5" cols="30" id="updContent" ng-model="readedTodo.content"></textarea>
<br/> Deadline (format YYYY-MM-DD HH:MM):
<br/>
<input type="text" id="updDeadline" ng-model="readedTodo.deadline" />
<br/> Completed:
<input type="checkbox" id="updCompleted" ng-model="readedTodo.completed" />
<br/>
<h3>if you use binding with $scope</h3> Note:
<br/>
<textarea rows="5" cols="30" id="updContent2" ng-model="readedTodo.content"></textarea>
<br/> Deadline (format YYYY-MM-DD HH:MM):
<br/>
<input type="text" id="updDeadline222" ng-model="readedTodo.deadline" />
<br/> Completed:
<input type="checkbox" id="updCompleted" ng-model="readedTodo.completed" />
<br/>
<input type="hidden" id="updID" ng-model="readedTodo.id" />
<br/>
<input type="submit" value="Update" />
</form>
</div>
</body>
</html>

How to specify a dynamically created object

Hi I'm trying to create a family tree of some sort. I have a drop down box that's it options are being dynamically added when I make a new family and prompts the user to add a child of the selected family.
I'm trying to append the child after the table of the selected family but I have no idea what kind of ID are being generated when they're dynamically made
code is below
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
//To Create Familes
$('#submit').on('click', function() {
var table = $('<table></table>').addClass('table');
var family = document.getElementById('famname').value;
$('#family input[type = text],input[type = text],input[type = text],input[type = text]').each( function() {
str = '<td>' + $(this).val() + '</td>';
$(this).val('');
table.append( str );
});
$('#container').append(table);
$('#select').append($('<option />', { text: family } ) );
});
//To Create child to right family
$('#submit2').on('click', function() {
var child = prompt("Enter the name of the child you wanna put to the selected family ");
something.after(child);
});
});
</script>
</head>
<body>
<form id ="family" method = "post" target="_parent">
Enter Family Name <input type = "text" name = "famname" id = "famname" > <br>
Enter Address <input type = "text" name = "address"> <br>
Enter Father's name <input type = "text" name = "dad"> <br>
Enter Mother's name<input type = "text" name = "mom"> <br>
<input id="submit" type="button" value="Submit" name="submit">
</form>
<p>Select Which family you want to add a child to</p>
<form id = "child">
<select id ="select"></select>
<input id="submit2" type="button" value="Submit" name="submit">
</form>
<div id = "container">
</div>
</body>
</html>
any idea's of how to append after the selected families? or is there a better of doing this
the best way is to actually add elements rather than HTML for example:
var test = document.createElement('table');
test.setAttribute('id', 'test_id');
document.body.appendChild(test);
console.log(document.getElementById('test_id'));
to reference it, be sure to add an id and/or a class using the setAttribute javascript call or the .attr() or .prop() methods in jquery.
That's not very clear as to exactly what you're trying to do, but here's a tidier version that adds the child as a new row after the family's row:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
<script>
$(function() {
var cur_id = 0;
//To Create Familes
$('#submit').on("click", function(ev) {
var id = "family" + cur_id++,
$row = $('<tr id="' + id + '"></tr>');
$('#select').append('<option value="' + id + '">' + $("#famname").val() + '</option>');
$('#family :text')
.each(function() {
$row.append('<td>' + $(this).val() + '</td>');
})
.val("");
$('#container table').append($row);
});
//To Create child to right family
$('#submit2').click(function(ev) {
var child = prompt("Enter the name of the child you wanna put to the selected family "),
id = $("#select").val();
$("#" + id)
.after("<tr><td>" + child + "</td></tr>");
});
});
</script>
</head>
<body>
<form id ="family" method = "post" target="_parent">
<label>Enter Family Name <input type="text" name="famname" id="famname"></label><br>
<label>Enter Address <input type="text" name="address"></label><br>
<label>Enter Father's name <input type = "text" name="dad"></label><br>
<label>Enter Mother's name <input type="text" name="mom"></label><br>
<input id="submit" type="button" value="Submit" name="submit">
</form>
<p>Select Which family you want to add a child to</p>
<form id="child">
<select id="select"></select>
<input id="submit2" type="button" value="Submit" name="submit">
</form>
<div id="container">
<table class="table"></table>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {
//To Create Familes
$('#submit').on('click',function(){
var table = $('<table></table>').addClass('table');
var family = document.getElementById('famname').value;
$('#family input[type = text],input[type = text],input[type = text],input[type = text]').each(function() {
str = '<td>' + $(this).val() + '</td>';
$(this).val('');
table.append(str);
table.addClass(family);
});
$('#container').append(table);
$('#select').append($('<option />', {text: family, value:family}));
});
//To Create child to right family
var fam, child, str;
$(document).on('change', '#select', function(){
$('#submit2').show();
$('#child_name').show();
fam = $(this).children('#select :selected').val();
});
$(document).on('click', '#submit2', function(){
child = $('#child_name').val();
$('#submit2').hide();
$('#child_name').hide();
str = '<td>' + child + '</td>'
$('.'+fam).append(str);
});
});
</script>
</head>
<body>
<form id ="family" method = "post" target="_parent">
Enter Family Name <input type = "text" name = "famname" id = "famname" > <br>
Enter Address <input type = "text" name = "address"> <br>
Enter Father's name <input type = "text" name = "dad"> <br>
Enter Mother's name<input type = "text" name = "mom"> <br>
<input id="submit" type="button" value="Submit" name="submit">
</form>
<p>Select Which family you want to add a child to</p>
<select id ="select">
</select>
<input type="text" id="child_name" style="display:none;">
<input id="submit2" type="submit" value="button" name="submit" style="display:none;">
<div id = "container">
</div>
</body>
</html>
this should do, I tested this already...hope this helps

Categories

Resources