how to append input fields using push() function in angularjs? - javascript

I am creating add more field functionality in angularjs. I am using below code
Javascript
<script>
function FruitsController($scope){
var div = 'Apple';
$scope.fruits=[];
$scope.addFruit=function(){
$scope.fruits.push(div);
}
}
<script>
HTML
<ul><li ng-repeat="fruit in fruits">{{fruit}}</li></ul>
<button ng-click="addFruit()">Add</button>
Above code works successfully and appends 'Apple' string in body. But I want to append input type text field like string. So I am using below script that does not works.
<script>
function FruitsController($scope){
var div = '<input type="text">';
$scope.fruits=[];
$scope.addFruit=function(){
$scope.fruits.push(div);
}
}
<script>
I know above my code is totally wrong. Please give me some ideo that how to add input type in angularjs

You can render UI element in html. Your HTML looks like
<ul>
<li ng-repeat="fruit in fruits">
<input ng-model="fruit">
</li>
</ul>
<button ng-click="addFruit()">Add</button>
Your controller looks like
<script>
function FruitsController($scope){
var fruit = 'apple';
$scope.fruits=[];
$scope.addFruit=function(){
$scope.fruits.push(fruit);
}
}
<script>

Try this. For input text boxes you need to use ng-model attribute as it is two way data binding.
<ul>
<li ng-repeat="fruit in fruits">
<input type="text" ng-model="fruit">
</li>
</ul>
<button ng-click="addFruit()">Add</button>

<ul>
<li ng-repeat="fruit in fruits">
<input ng-model="fruit">
</li>
</ul>
<button ng-click="addFruit()">Add</button>
Keep your UI/HTML code in your HTML template, keep pure data structures in your controller. Through Angular's two-way data binding, ng-model will directly update your entries in $scope.fruits when your input changes.

Related

angular2 ngFor won't work

I'm trying to make some textboxes appear everytime a user clicks a button.
i'm doing this with ngFor.
For some reason, the ngFor won't iterate.
I've tried using slice to change the array reference, but still, the text boxes won't appear.
Any idea what i'm doing wrong??
Below are the HTML and component codes.
Thanks!!!
export class semesterComponent {
subjectsNames = [];
addSubject(subjectName: string) {
if (subjectName) {
this.subjectsNames.push(subjectName);
this.subjectsNames.slice();
console.log(subjectName);
console.log(this.subjectsNames);
}
};
<div class="semester-div">
<ul>
<li ngFor="let subject of subjectsNames">
<span>
<input #subjectName type="text" />
<input id = "subjectGrade" type = "number"/>
<input id = "subjectWeight" type = "number"/>
</span>
</li>
</ul>
<br>
<button (click)="addSubject(subjectName.value)">add</button>
<br>
</div>
You are missing the * in *ngFor
<li *ngFor="let subject of subjectsNames">
The way you have your controls written subjectName does not exist because the array is empty and therefore the *ngFor does not render it. Clicking the Add button results in a exception that the value doesn't exist on undefined where undefined is really subjectName.
Moving it outside of the *ngFor will make things work:
<input #subjectName type="text" />
<ul>
<li *ngFor="let subject of subjectsNames">
<span>
{{subject}}
<input id="subjectGrade" type="number"/>
<input id="subjectWeight" type="number"/>
</span>
</li>
</ul>
I suspect you also want to further bind the data as you iterate over the subject names but that's outside the scope of the question.
Here's a plunker: http://plnkr.co/edit/HVS0QkcLw6oaR4dVzt8p?p=preview
First, you are missing * in *ngFor.
Second put out
<input #subjectName type="text" />
from ngFor, should work.

can't get data attribute with jquery

I am trying to retrieve data-cost("#packages") and append it to #form next to Ticket-price. I am not getting any errors in console. I can't seen to understand what went wrong.
JS:
<script src="jquery-1.11.2.js"></script>
<script>
$(document).ready(function()
{
var price=$("#packages").data("cost");
var amount=$("<span>"+price+"</span>");
$("#form").next().next().append(amount);
});
</script>
HTML:
<div id="packages">
<h2><u>Tourism Packages:</u></h2>
<ul>
<li data-name="Southern Travels">Travels Name: Southern Travels</li>
<li data-cost="2000">Cost per person: 2000</li>
<li>Duration: 3 days & 4 nights</li>
</ul>
</div>
<div id="form">
<label>Number of persons </label>
<input id="input"type="text"/ autofocus>
<p id="ticket-price">Ticket Price</p>
</div>
For this to work as it is, you must edit your HTML as following:
<div id="packages" data-name="Southern Travels" data-cost="2000">
<h2><u>Tourism Packages:</u></h2>
<ul>
<li>Travels Name: Southern Travels</li>
<li>Cost per person: 2000</li>
<li>Duration: 3 days & 4 nights</li>
</ul>
</div>
Either that, or access the data properties of the <li> elements instead of the div#packages (i.e #packages ul li instead of #packages)
$(document).ready(function() {
// Targeting 2nd li element inside #packages
var price=$("#packages li").eq(2).data("cost");
// create a span element with text 'price'
var amount=$("<span>"+price+"</span>");
// append as last child of the form
$("#form").append(amount);
});
You need to look for your data attribute by name - and look at the LI's.
You also need to build your html string and append it properly to the #ticket-price
WOKING EXAMPLE (FIDDLE): http://jsfiddle.net/ojLo8ojz/
JS:
$(document).ready(function(){
var price = $("#packages li[data-cost]").attr("data-cost");
var amount = "<span> "+price+"</span>";
$("#ticket-price").append(amount);
});

angularjs ns-show logic flow

I am a newbie in angularjs. I'm trying to show an html element depending on a property of the $scope object but without using any form element.
This is the snipped of code:
<div id="ListApp">
<div ng-controller="ListCtrl">
{{ myData.prova }}: {{ myData.logged }}
<div id="secretContent" ng-show="myData.logged">
<ul>
<li ng-repeat="elemento in lista">
<input type="checkbox" ng-model="elemento.comprato" />
<span ng-if="!elemento.comprato">{{ elemento.nome }}</span>
<span ng-if="elemento.comprato" style="text-decoration:line-through;">{{ elemento.nome }}</span>
</li>
</ul>
<input type='text' id='input_nome'/><button ng-click="aggiungi()">Aggiungi</button>
</div>
</div>
</div>
And this is the controller part:
<script>
var listaViaggio = angular.module('listApp', ['directive.g+signin']);
listaViaggio.controller('ListCtrl', ['$scope',function ListCtrl($scope) {
$scope.lista = [];
$scope.myData={};
$scope.myData.prova="test";
$scope.myData.logged=0;
$scope.aggiungi = function(){
$scope.lista.push({
'nome':document.getElementById("input_nome").value,
'comprato':false
});
};
$scope.$on('event:google-plus-signin-success', function (event, authResult) {$scope.myData.logged=1;console.log($scope.myData.logged);});
$scope.$on('event:google-plus-signin-failure', function (event, authResult) {$scope.myData.logged=0;console.log($scope.myData.logged);});
}]);
</script>
As can be easily seen, I change the status of $scope.myData.logged on google+ sign in and I espect that the div with id secretContent will be shown or won't be shown depending on this property but I've seen that the truthfulness of the ng-show is evaluated only once and is not binded to the actual value of the property, so, when it changes, nothing happens.
What is wrong in my code? Which is the correct logic flow of the ng-show command and how to bind it to a $scope property?
Thanks in advance to everybody.
Use $scope.$apply() whenever the values get changed.
$scope.$apply() will update the page content.

how to fetch values of two hidden tags with different id

I have using two anchor tag to transfer the control to same page. and gives two hidden input with same id but different values. as shown in given code.
<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucher();">
<input type="hidden" id="PRVou" value="payment">PaymentReceipt Voucher</a></li>
<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucher();">
<input type="hidden" id="PRVou" value="receipt">ReceiptPayment Voucher</a></li>
and i want to get the values of these hidden tags by using following javascript code.
loadAccForPayVoucher = function() {
alert(document.getElementById('PRVou').value);
}
and it always alert payment. how can i get the value according to the link. Thanks.
id attributes are meant to be unique, regardless of their context. There should only be one element in the entire document with a given id.
Give the element a class name instead:
<input type="hidden" class="PRVou" value="payment">
And then use getElementsByClassName:
document.getElementsByClassName('PRVou')[0].value
Try this:
<li data-icon="false"> <a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucher('payment');">
<!--<input type="hidden" id="PRVou" value="payment">PaymentReceipt Voucher</a> --></li>
<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucher('receipt');">
<!-- <input type="hidden" id="PRVou" value="receipt">ReceiptPayment Voucher</a> --></li>
<script type="text/javascript">
loadAccForPayVoucher = function(type) {
alert(type);
//alert(document.getElementById('PRVou').value);
}
</script>
In HTML the ID attributes are always unique, thus when you call document.getElementById, the DOM of the browser will go out and fetch any (most likely the first) element with the given ID.
What can I do?
Give them separate IDs, your html will look like this:
<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucherPayment();">
<input type="hidden" id="PRVou-payment" value="payment"/>PaymentReceipt Voucher</a></li>
<li data-icon="false"><a href="#paymentReceiptVoucher" onclick="loadAccForPayVoucherReceipt();">
<input type="hidden" id="PRVou-receipt" value="receipt"/>ReceiptPayment Voucher</a></li>
And then your JavaScript will have separate event handlers:
loadAccForPayVoucherPayment = function() {
alert(document.getElementById('PRVou-payment').value);
}
loadAccForPayVoucherReceipt = function() {
alert(document.getElementById('PRVou-receipt').value);
}
Update: I made you a fiddle :) http://jsfiddle.net/YCXC8/

Getting value from input control using jQuery

I am using the teleriks treeview control (asp.net mvc extensions), where I may have up to three children nodes, like so (drumroll...... awesome diagram below):
it has its own formatting, looking a bit like this:
<%=
Html.Telerik().TreeView()
.Name("TreeView")
.BindTo(Model, mappings =>
{
mappings.For<Node1>(binding => binding
.ItemDataBound((item, Node1) =>
{
item.Text = Node1.Property1;
item.Value = Node1.ID.ToString();
})
.Children(Node1 => Node1.AssocProperty));
mappings.For<Node2>(binding => binding
.ItemDataBound((item, Node2) =>
{
item.Text = Node2.Property1;
item.Value = Node2.ID.ToString();
})
.Children(Node2 => Node2.AssocProperty));
mappings.For<Node3>(binding => binding
.ItemDataBound((item, Node3) =>
{
item.Text = Node3.Property1;
item.Value = Node3.ID.ToString();
}));
})
%>
which causes it to render like this. I find it unsual that when I set the value it is rendered in a hidden input ? But anyway:...
<li class="t-item">
<div class="t-mid">
<span class="t-icon t-plus"></span>
<span class="t-in">Node 1</span>
<input class="t-input" name="itemValue" type="hidden" value="6" /></div>
<ul class="t-group" style="display:none">
<li class="t-item t-last">
<div class="t-top t-bot">
<span class="t-icon t-plus"></span>
<span class="t-in">Node 1.1</span>
<input class="t-input" name="itemValue" type="hidden" value="207" />
</div>
<ul class="t-group" style="display:none">
<li class="t-item">
<div class="t-top">
<span class="t-in">Node 1.1.1</span>
<input class="t-input" name="itemValue" type="hidden" value="1452" />
</div>
</li>
<li class="t-item t-last">
<div class="t-bot">
<span class="t-in">Node 1.1.2</span>
<input class="t-input" name="itemValue" type="hidden" value="1453" />
</div>
</li>
</ul>
</li>
</ul>
What I am doing is updating a div after the user clicks on a certain node. But when the user clicks on a node, I want to send the ID not the Node text property. Which means I have to get it out of the value in these type lines <input class="t-input" name="itemValue" type="hidden" value="1453" />, but it can be nested differently each time, so the existing code I ahve doesn't ALWAYS work:
<script type="text/javascript">
function TreeView_onSelect(e) {
//`this` is the DOM element of the treeview
var treeview = $(this).data('tTreeView');
var nodeElement = e.item;
var id = e.item.children[0].children[2].value;
...
</script>
So based on that, what is a better way to get the appropriate id each time with javascript/jquery?
edit:
Sorry to clarify a few things
1) Yes, I am handling clicks to the lis of the tree & want to find the value of the nested hidden input field. As you can see, from the telerik code, setting item.Value = Node2.ID.ToString(); caused it to render in a hidden input field.
I am responding to clicks anywhere in the tree, therefore I cannot use my existing code, which relied on a set relationship (it would work for first nodes (Node 1) not for anything nested below)
What I want is, whenever there is something like this, representing a node, which is then clicked:
<li class="t-item t-last">
<div class="t-bot">
<span class="t-in">Node 1.1.2</span>
<input class="t-input" name="itemValue" type="hidden" value="1453" />
</div>
</li>
I want the ID value out of the input, in this case 1453.
Hope this now makes a lot more sense.
if possible would love to extend this to also store in a variable how nested the element that is clicked is, i.e. if Node 1.1.2 is clicked return 2, Node 1.1 return 1 and node 1 returns 0
It's a little unclear what you're asking, but based on your snippet of JavaScript, I'm guessing that you're handling clicks to the lis of the tree & want to find the value of the nested hidden field? If so, you want something like this:
function TreeView_onSelect(e) {
var id = $(e.item).find(".t-input:first").val();
}
Edit: In answer to your follow-up question, you should be able to get the tree depth with the following:
var depth = $(e.item).parents(".t-item").length;
In jQuery you can return any form element value using .val();
$(this).val(); // would return value of the 'this' element.
I'm not sure why you are using the same hidden input field name "itemValue", but if you can give a little more clarity about what you are asking I'm sure it's not too difficult.
$('.t-input').live('change',function(){
var ID_in_question=$(this).val();
});

Categories

Resources