How to get data from angular expressions {{}} in to script - javascript

I am using angular xeditable text and I am trying to edit a text in a table row. whenever I click on a text it creates a textbox properly but it does not put the data in which should be edited. I do not know how to assign that text to the $scope object.
please help!
Here is my HTML table code
<tbody>
{% for user in User %}
<tr>
<td> {{ user.uid }} </td>
<td> {{ user.taskname }}
<span style="padding-right:3px; padding-top: 3px; display:inline-block;" ></span>
<input type="image" class="deleteImg"
src="static/img/trash_can.png" height="15px"
width="18px" name="removeId"
value={{user.uid}} ></input>
<input type="image" src="static/img/editbtn.svg"
height="15px" width="18px" name="editId"
value={{user.uid}} ></input>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
Here is my Script
<script>
var newItem ={};
var app = angular.module("app", ['xeditable']);
app.controller('myctrl', function($scope) {
$scope.myname="Howdy";
$scope.user={
taskname: 'Here goes the main logic'
};
});
app.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('//').endSymbol('//');
});
app.run(function(editableOptions) {
editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});
</script>

Related

How to increment a value on a button click in JQuery?

Another query on a JQuery function as a newbie in this. With the help of you guys I was able to modify the code to return the corresponding value from an input tag.
The problem that I am facing now is that on the Add button click I want the <p class="item-quantity">0</p> to display the value returned by the JQuery .get() in the corresponding row.
Here's my HTML:
{% for item in menu_category %}
<tr class="item">
<td><p class="item-name">{{item.item_Name}}</p></td>
<td><p class="item-price">{{item.item_Price}}</p></td>
<td>
<button type="button" class="btn btn-primary add-item" data-name="{{item.item_Name}}" data-price="{{item.item_Price}}" data-id="{{item.item_Id}}">+</button>
</td>
<td><p class="item-quantity">0</p></td>
<td>
<button type="button" class="btn btn-primary remove-item" data-name="{{item.item_Name}}" data-price="{{item.item_Price}}" data-id="{{item.item_Id}}">-</button>
</td>
</tr>
{% endfor %}
And my function:
<script>
$(function() {
$('.add-item').on('click', function() {
$.get('{{ url_for("func_add_to_cart") }}',
{
item_id: $(this).attr("data-id"),
},
function(data) {
$(this).parents().find(".item-quantity").html(data);
});
return false;
});
});
</script>
Thanks for your help!

Django & js : My formset forms are dependent on each other

I have the following js that adds forms to my template whenever I click on the button ""
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '-\\d+)');
var replacement = prefix + '-' + ndx;
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}
function addForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
var row = $('.dynamic-form:first').clone(true).get(0);
$(row).removeAttr('id').insertAfter($('.dynamic-form:last')).children('.hidden').removeClass('hidden');
$(row).children().not(':last').children().each(function() {
updateElementIndex(this, prefix, formCount);
$(this).val('');
});
$('#id_' + prefix + '-TOTAL_FORMS').val(formCount + 1);
return false;
}
I call this script in my header :
$(function () {
$('#add-row').click(function() {
return addForm(this, 'form');
//$('.add-row').hide();
});
})
and this is my template :
<form action="/caisse" method="POST" enctype="multipart/form-data" id="personForm" data-tiers-url="{% url 'ajax_load_tiers' %}" >{% csrf_token %}{{ form.non_field_errors }}
<table align="center"> <!-- <div class="row" style="padding-left: 24%; padding-top: 3%"></div> -->
<tr>
<td width="10%"></td>
<td><input id="uploadFile" placeholder="Choose File" class="form-control" /></td>
<td><div class="btn btn-primary" id="divInput"><span>importer</span>
{% render_field form1.myfile id="uploadBtn" style=" position: absolute;top: 0;right: 0;margin: 0; padding: 0;font-size: 20px;cursor: pointer;opacity: 0;filter: alpha(opacity=0);" %}
</div></td>
</tr>
</table>
<table style ="border-collapse: separate;border-spacing: 15px;" id="id_forms_table">
{% for form in formset %}
<tr style="border:1px solid black;" id="{{ form.prefix }}-row" class="dynamic-form" >
<td><div class="col-xs-1"><b><p name="np1">1</p></b></div></td>
<td >
{% render_field form.dateOperation class="form-control" %}{{form.dateOperation1.errors}}
</td>
<td>{% render_field form.designation class="form-control" %}{{form.errors}}
</td>
<td>
{% render_field form.typeTiers class="form-control" %}{{form.typeTiers.errors}}
</td>
<td>
{% render_field form.tiers class="form-control" %}{{form.tiers.errors}}
</td>
<td>{% render_field form.numfacture class="form-control" %}{{form.numfacture.errors}}
</td>
<td>{% render_field form.montant class="form-control" %}{{form.montantdebit.errors}}
</td>
<td>{% render_field form.typeMontant %}{{form.typeMontant.errors}}
</td>
</tr>
{% endfor %}
</table>{{ formset.management_form }}
<tr><td><input type="submit" name="ajoutligne" value="Ajouter une ligne" class="btn btn-primary" id="add-row" style="background-color: #8C1944; border-color: #8C1944; float:right;margin: 5px;" onclick=""></td></tr>
The button Ajouter une ligne is the one called on the js to add a new row of my formset.
My problem here is that my forms are not independent.
for example the the last field typeMontant is a Radio button, when I add a new row as bellow :
Only One radio of the four radio buttons got selected. which means that the two rows are dependent on each other.
So what's the problem that makes my forms dependent when I need them to be totally independent of each other.
any help please.
I'm really stucking here, Thank You so much.
That is because the names and the ids of the form fields are the probably the same, since you are adding the same form over and over again, and all your radio buttons reference to the same name.
Django can already handle multiple forms in a page via formsets.
I found a tutorial that helped me a lot to understand and implement it on my own project:
http://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html

Trigger Jquery on an element immediately after it gets populated

I have a text area which gets populated after click of a button .
<textarea rows="4" cols="50" id="4321">
{{ data.classi}}
</textarea>
Now i want something to happen after it gets populated . I have tried onchange and a few other options but they only work after the textarea is populated an we change its content .
I want it to happen right after the textarea is populated with json from back-end . How can this be done
$('#4321').on('change', function() {
alert( this.value ); // or $(this).val()
});
This doesn't work
I am pasting the entire code here in case it helps
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/main.js"></script>
<script src="jquery.json-view.js"></script>
<link href="jquery.json-view.css" rel="stylesheet"></link>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body ng-controller="DebugController">
<div>
<input type="text" ng-model="query" placeholder="Search Query">
<input type="text" ng-model="pog" placeholder="Enter No of POGs">
<button ng-click="onSearch()" class="button" id ="abcd">Search</button>
</div>
<textarea rows="4" cols="50" id="abc">
{{ data.classi}}
</textarea>
<div>
<h4>Parameters</h4>
<table>
<tr ng-repeat="x in data.p ">
<td>{{ x[0] }}</td>
<td>{{ x[1] }}</td>
</tr>
</table>
</div>
<div>
<h4>Classifier Scores</h4>
<table>
<tr>
<th>Category URL</th>
<th>Additive Boost</th>
</tr>
<tr ng-repeat="x in data.classifier">
<td>{{ x[0] }}</td>
<td>{{ x[1] }}</td>
</tr>
</table>
</div>
<div>
<h4>Product Groups (POGs)</h4>
<table>
<tr>
<th>Id</th>
<th>Details</th>
<th>Score</th>
<th>HPSA Score</th>
<th>BF Score</th>
<th>Word Match</th>
<th>Classifier Score</th>
<th>QUL Score</th>
</tr>
<tr ng-repeat="x in data.items | limitTo: limit " >
<td><a href="{{ x.get }}">{{ x.id }}</td>
<td>
<p><b>{{ x.name[0] }}</b></p>
<p><u>Brand</u>: {{ x.Brand }}; <u>Category URL</u>: {{ x.mlnURL }};<u>Price</u>: Rs {{x.Price}} </p>
</td>
<td>
<p><b>{{ x.score }}</b></p>
Classifier Score: {{ x.cscore }} <br>
Document Score: {{ x.sscore }} </p>
</td>
<td>
<p><b> {{ x.hpsaScore_default }} </b></p>
</td>
<td>
<p><b> {{ x.bf_value }} </b></p>
</td>
<td>
</td>
<td>
<p> <b> {{ x.cscore }} </b></p>
</td>
<td>
</td>
</tr>
</table>
</div>
<div>
<h4>Solr Query</h4>
<p>{{ data.query }}</p>
</div>
<script>
var pog;
$(function() {
$('#abc').on('input', function() {
alert("hi");
});
});
</script>
</body>
</html>
The controller of the page
var app = angular.module('myApp', []);
app.controller('DebugController', function($scope, $http) {
$scope.onSearch = function () {
$scope.data = {}
number = $scope.pog
$scope.limit = number
$http.get('/search?q=' + $scope.query)
.then(function(response) {
console.log(response)
params = []
urls = []
for (p in response.data.params) {
params.push([p, response.data.params[p]])
}
for (i in response.data.bf_value) {
for(j in response.data.bf_value[i]) {
}
}
for( t in response.data.items ) {
p =""
for ( s in response.data.bf_value ) {
p+=response.data.bf_value[s][t]
}
response.data.items[t].bf_value = p
}
console.log(response.data.bf_value);
$scope.data = response.data
$scope.data.classi = response.data.classify
$scope.data.p = params
$scope.data.u = urls
});
}
});
Use the input event. (mdn)
$('#hello').on('input', function() {
console.log($(this)[0].value) // console logs the value of the textarea
});
$("#4321").change(function(){
alert("The text has been changed.");
});
This should work.

Define and get values from angularJS table

Here is my angularjs code to get values in a table and save. If I put some data in table and save, Its working fine but if I click save without entering any data in table it shows error as
TypeError: $scope.item is undefined
Here is my code and please help me. I am a newbie in angularJS
<div ng-app="Myapp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-messages.js"></script>
<script>
var Myapp = angular.module('Myapp', ["ngRoute"]);
</script>
<div ng-controller="orderFormController">
<table id="item_table">
<thead>
<tr class="headings">
<th class="column-title">Item </th>
<th class="column-title">Rate</th>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" name="item" ng-model='item[0]'>
</td>
<td>
<input type="text" name="rate" ng-model='rate[0]'>
</td>
</tr>
<tr>
<td>
<input type="text" name="item" ng-model='item[1]'>
</td>
<td>
<input type="text" name="rate" ng-model='rate[1]'>
</td>
</tr>
</tbody>
</table>
<button type="button" ng-click='saveorder()' >SAVE ORDER</button>
</div>
<script>
Myapp.controller('orderFormController', ['$scope', '$http', function ($scope, $http) {
var data = {};
data['item'] = [];
$scope.saveorder = function () {
var rowCount = 3;
for (i = 1; i < rowCount; i++) {
data['item'][i] = {'item': $scope.item[i], 'rate': $scope.rate[i]}
}
alert(data);
}
}]);
</script>
$scope.item is not defined anywhere except for in that for loop, if there are no values in the table, then $scope.item will remain undefined. You could simply declare it prior to the for loop, and set some init values, which could be done in the controller, or by using the ng-init directive.
Also, I would recommend using the ng-repeat directive for your table rows, it will create a template per item from a collection, which makes your code easier to manage. Here's the documentation: ngRepeat
modify your html to only include this not 2 rows of input
<td>
<input type="text" name="item" ng-model='item'>
</td>
<td>
<input type="text" name="rate" ng-model='rate'>
</td>
and modify your saveOrder
$scope.saveorder = function () {
if (!($scope.item.length && $scope.rate.length)){
alert('can\'t be empty');
return;
}
data['item'].push({'item': $scope.item, 'rate': $scope.rate});
$scope.item = "";
$scope.rate = "";
console.log(data['item'][data['item'].length - 1]);
alert(data);
}

how to access to a html twig form field value through javascript in Symfony2?

I would like to know how to access to a html twig form field value through javascript in Symfony2. The explanation is as below:
This is the screen shot of the form that I have:
This is the form code:
<html>
<head>
<title> Wkayet </title>
<link rel="shortcut icon" href="{{asset('bundles/ikprojhome/images/icon-WKAYET.png')}}">
<link rel="stylesheet" type="text/css" href="{{asset('bundles/ikprojhome/css2/css.css')}}"/>
<script src='{{asset('bundles/ikprojhome/lib/jquery.min.js')}}'></script>
<script>
function f1(){
if(form_widget(form.start)>form_widget(form.end)){
alert("no");
}
}
</script>
</head>
<body>
<center>
<div id="container">
<div id="header">
</div>
<div id="content">
<table width="100%" height="100%" align="center">
<tr>
<td>
{% for x in groupe%}
<form id="EventForm" action='{{path('ikproj_groupe_homepaeventsAdd',{id:x['id']})}}' method="POST" {{ form_enctype(form) }} onsubmit="f1();">
<!--<form id="EventForm" action='{{path('ikproj_groupe_homepaeventsAdd',{id:x['id']})}}' method="POST" {{ form_enctype(form) }} >-->
{% endfor %}
{{ form_errors(form) }}
<table align="center">
<tr>
<td class="separation"><label for="groupname">Titre</label></td>
<td>
<!--<input id="titre" name="titre" required="required" type="text" size="50"/> -->
<div>
{{ form_errors(form.title) }}
{{ form_widget(form.title) }}
</div>
</td>
</tr>
<tr>
<td class="separation"><label for="debut">Début</label></td>
<td><!--<select id="debut" name="debut" class="select"></select>-->
<div>
{{ form_errors(form.start ) }}
{{ form_widget(form.start ) }}
</div>
</td>
</tr>
<tr>
<td class="separation"><label for="fin">Fin</label></td>
<td><!--<select id="fin" name="fin" class="select"></select>-->
<div>
{{ form_errors(form.end ) }}
{{ form_widget(form.end ) }}
</div>
</td>
</tr>
<tr>
<td class="separation"><label for="lieu">Lieu</label></td>
<td>
<div>
{{ form_errors(form.location) }}
{{ form_widget(form.location) }}
</div>
</td>
</tr>
<tr>
<td id="description" valign="top" class="separation"><label for="description">Description</label></td>
<td><textarea id="ikproj_groupebundle_eventsgroupe_description" name="ikproj_groupebundle_eventsgroupe[description]" rows="5" cols="40"></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center" id="button" valign="bottom"><input class="button" type="submit" value=""/></td>
</tr>
</table>
{{form_widget(form._token)}}
</form>
</td>
</tr>
</table>
</div>
</div>
</center>
</body>
</html>
And this is the form class code:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title','text')
->add('start','datetime',array(
'input' => 'datetime',
'format' => 'dd/MM/yyyy H:i',
'minutes' => array(
0,
30
)
))
->add('end','datetime',array(
'input' => 'datetime',
'format' => 'dd/MM/yyyy H:i',
'minutes' => array(
0,
30
)
))
->add('location','text')
->add('description','text')
;
}
Actually, what I would like to do is to compare the values of the two datetime fields "start" and "end". Therefore I need to access to the value of each of that fields. By the way, please focus on this part of JavaScript code (which is at the top of the html form code):
<script>
function f1(){
if(form_widget(form.start)>form_widget(form.end)){
alert("no");
}
}
</script>
So, my question is: what will be the correct code to do that?
Why you don't access directly to properties of the HTML generated elements at Javascript? Like for example ID or class or name or something else.
Anyway if you'll like to access any var that comes from controller to Twig view you can do it as follow:
<script>
alert('{{ myvar }}');
</script>
Notice you are tying to access form_widget and that returns the complete HTML element, for example:
<input type="text" name="form[title]" id="form[title]" />
and not the value of that input, take care of that.
Second solution based on your comments
Following your comments and your needs try this code instead:
<script>
$(document).ready(function(){
// I've to do it in this way since your button
// has none class or id to use in jQuery selector
// you should take care of that too
$('input [type=submit]).on('click', function() {
alert($('#ikproj_groupebundle_eventsgroupe_start').val());
})
});
</script>
A few things more:
I made a typo, yes, but remember I'm trying to help you with some ideas, I'm not doing your work so the best you can do is try to understand my code and apply to yours
As image shows you have Symfony datetime field so maybe my code won't work at all but give it a try
You can retrieve the id of the form fields in your javascript like this :
"{{ form.start.vars.id|e('js') }}"
Then, using this id, retrieve your javascript/jQuery/... element and get its value.
If you are planing to use this form field on different forms, it may be a good idea to create a custom FormType that will add classes to the html output of your to date fields and base your javascript selector on this classes.

Categories

Resources