Function name is not defined at HTMLButtonElement.onclick - javascript

Searched a lot of question with the same error but nothing helped.
Am using Python/Django and here the HTML code am trying to make it work.
here is my code:
<tr class="gradeA odd" role="row">
<td class="sorting_1">
{{ item.book_name }}
</td>
<td>{{ item.book_subject }}
</td>
<td>{{ item.book_level }}
</td>
<td>{{ item.book_teacher }}
</td>
<td><input type="number" id="price_{{ item.id }}" style="width: 50px;"/>
</td>
<td><input type="number" id="commission_{{ item.id }}"style="width: 50px;"/>
</td>
<td>
<button class="btn btn-primary" id="submit_button" onclick="addingTheBook_{{ item.id }}()">
إضافة
</button>
</td>
</tr>
<script>
function addingTheBook_{{ item.id }}() {
var the_price = document.getElementById('price_{{ item.id }}');
var the_commission = document.getElementById('commission_{{item.id}}');
window.location.href = '/vip/add/pricelist/' + {{ item.id }} +'/' + the_price.value + '/' + {{ current_vip }} +'/' + the_commission.value + '/';
}
</script>
Whenever I click the button with onclick attribute, it gives me the error addingTheBook_3 is not defined at HTMLButtonElement.onclick

Define the function as:
function addingTheBook_(itemId){
}
And use the itemId variable to fetch price, commission, etc. like below:
var the_price = document.getElementById('price_'+ itemId);
var the_commission = document.getElementById('commission_'+itemId);

Related

Add more button in JavaScript not working

I am trying to add rows in my django template using JavaScript but it is not working like it's supposed to:
HTML
<html>
<head>
<title>gffdfdf</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/static/jquery.formset.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form id="myForm" action="" method="post" class="">
{% csrf_token %}
<h2> Team</h2>
{% for field in form %}
{{ field.errors }}
{{ field.label_tag }} : {{ field }}
{% endfor %}
{{ form.player.management_form }}
<h3> Product Instance(s)</h3>
<table id="table-product" class="table">
<thead>
<tr>
<th>player name</th>
<th>highest score</th>
<th>age</th>
</tr>
</thead>
{% for player in form.player %}
<tbody class="player-instances">
<tr>
<td>{{ player.pname }}</td>
<td>{{ player.hscore }}</td>
<td>{{ player.age }}</td>
<td> <input id="input_add" type="button" name="add" value=" Add More " class="tr_clone_add btn data_input"> </td>
</tr>
</tbody>
{% endfor %}
</table>
<button type="submit" class="btn btn-primary">save</button>
</form>
</div>
<script>
var i = 1;
$("#input_add").click(function() {
$("tbody tr:first").clone().find(".data_input").each(function() {
if ($(this).attr('class')== 'tr_clone_add btn data_input'){
$(this).attr({
'id': function(_, id) { return "remove_button" },
'name': function(_, name) { return "name_remove" +i },
'value': 'Remove'
}).on("click", function(){
var a = $(this).parent();
var b= a.parent();
i=i-1
$('#id_form-TOTAL_FORMS').val(i);
b.remove();
$('.player-instances tr').each(function(index, value){
$(this).find('.data_input').each(function(){
$(this).attr({
'id': function (_, id) {
var idData= id;
var splitV= String(idData).split('-');
var fData= splitV[0];
var tData= splitV[2];
return fData+ "-" +index + "-" + tData
},
'name': function (_, name) {
var nameData= name;
var splitV= String(nameData).split('-');
var fData= splitV[0];
var tData= splitV[2];
return fData+ "-" +index + "-" + tData
}
});
})
})
})
}
else{
$(this).attr({
'id': function (_, id) {
var idData= id;
var splitV= String(idData).split('-');
var fData= splitV[0];
var tData= splitV[2];
return fData+ "-" +i + "-" + tData
},
'name': function (_, name) {
var nameData= name;
var splitV= String(nameData).split('-');
var fData= splitV[0];
var tData= splitV[2];
return fData+ "-" +i + "-" + tData
}
});
}
}).end().appendTo("tbody");
$('#id_form-TOTAL_FORMS').val(1+i);
i++;
});
</script>
</body>
</html>
the above code creates a form with three fields i.e player name, highest score and age with a add more button
but according to this it should create the following :
<!-- First row of the table -->
<tr>
<td><input type="text" name="form-0-name" id="id_form-0-name" /></td>
<td>
<input type="number" name="form-0-quantity" id="id_form-0-quantity" />
</td>
<td><input type="number" name="form-0-price" id="id_form-0-price" /></td>
<td>
<input
id="input_add"
type="button"
name="add"
value=" Add More "
class="tr_clone_add btn data_input"
/>
</td>
</tr>
<!-- Second row of the table -->
<tr>
<td><input type="text" name="form-1-name" id="id_form-1-name" /></td>
<td>
<input type="number" name="form-1-quantity" id="id_form-1-quantity" />
</td>
<td><input type="number" name="form-1-price" id="id_form-1-price" /></td>
<td>
<input
id="remove_button"
type="button"
name="remove_button1"
value=" Remove "
class="tr_clone_add btn data_input"
/>
</td>
</tr>
<!-- more inline formset are going to rendered here -->
But when I create another row in the form it creates another row with same name and id.
See:
<tbody class="player-instances">
<tr>
<td><input type="text" name="form-0-pname" id="id_form-0-pname"></td>
<td><input type="number" name="form-0-hscore" id="id_form-0-hscore"></td>
<td><input type="number" name="form-0-age" id="id_form-0-age"></td>
<td> <input id="input_add-0-undefined" type="button" name="add-0-undefined" value=" Add More " class="tr_clone_add btn data_input"> </td>
</tr>
<tr>
<td><input type="text" name="form-0-pname" id="id_form-0-pname"></td>
<td><input type="number" name="form-0-hscore" id="id_form-0-hscore"></td>
<td><input type="number" name="form-0-age" id="id_form-0-age"></td>
<td> <input id="remove_button-1-undefined" type="button" name="name_remove1-1-undefined" value="Remove" class="tr_clone_add btn data_input"> </td>
</tr></tbody>
Why does it not add the row with updated name and id ?
Update:
Models.py
class Player(models.Model):
pname = models.CharField(max_length=50)
hscore = models.IntegerField()
age = models.IntegerField()
def __str__(self):
return self.pname
class Team(models.Model):
tname = models.CharField(max_length=100)
player= models.ManyToManyField(Player)
def __str__(self):
return self.tname
Views.py
def post(request):
if request.POST:
form = TeamForm(request.POST)
print("form", form)
form.player_instances = PlayerFormset(request.POST)
if form.is_valid():
team= Team()
team.tname= form.cleaned_data['tname']
team.save()
if form.player_instances.cleaned_data is not None:
for item in form.player_instances.cleaned_data:
player = Player()
player.pname= item['pname']
player.hscore= item['hscore']
player.age= item['age']
player.save()
team.player.add(player)
team.save()
else:
form = TeamForm()
return render(request, 'packsapp/employee/new.html', {'form':form})
Forms.py
class PlayerForm(forms.Form):
pname = forms.CharField()
hscore= forms.IntegerField()
age = forms.IntegerField()
PlayerFormset= formset_factory(PlayerForm)
class TeamForm(forms.Form):
tname= forms.CharField()
player= PlayerFormset()

How do I take variables in javascript?

I made an AJAX request so that when I select drop down the results will be out. I am confused. The problem is that only a table is displayed. How come the data comes from the variable $grade (calculation of grade), the variable $value (calculation of total value)?
I try to get the element. $grade instead it is undefined
<script type="text/javascript">
$(document).ready(function(){
$('#kategori').on('change', function(e){
var id = e.target.value;
$.get('/khs/khs_semester/' + id, function(data){
console.log(id);
console.log(data);
$('#khs').empty();
$.each(data, function(index, element){
$('#khs').append("<tr><td>" + element.kode_mk + "</td><td>" + element.nama_mk + "</td>" + "<td>" + element.semester + "</td><td>" + element.jml_sks + "</td><td>" + element.$grade + "</td></tr>");
});
});
});
});
</script>
<table class="table table-bordered">
<thead>
<tr>
<th width="100">KODE MK</th>
<th width="350">NAMA MK</th>
<th width="50">SEMESTER</th>
<th width="50">SKS</th>
<th width="50">GRADE</th>
</tr>
</thead>
<tbody id="khs">
#foreach($mahasiswa as $row)
#php
$nilai = hitung_nilai($row->id);
$grade = hitung_grade($nilai);
$mutu = hitung_mutu($grade);
#endphp
<tr>
<td>{{ $row->kode_mk }}</td>
<td>{{ $row->nama_mk }}</td>
<td>{{ $row->semester }}</td>
<td>{{ $row->jml_sks}}</td>
<td>{{ $grade }}</td>
<td>{{ $mutu*$row->jml_sks }}</td>
</tr>
#php
$totalSKS=$totalSKS+$row->jml_sks;
$totalMutu = $totalMutu+$mutu*$row->jml_sks;
#endphp
#endforeach
</tbody>
</table>
What might help you is to identify each row by an ID, it could be an ID in the <tr id="KM003"> or in the specific TD of the grade, like <td id="KM003Grade"> so you could get the grade by the students code like: var Name = $('#IDused').innerHTML;
If you use by the ROW approach, you could use a class in each child TD to identify the attribute, for example:
<tr id="km003">
<td class="kode">{{ $row->kode_mk }}</td>
<td class="nama">{{ $row->nama_mk }}</td>
<td class="semester">{{ $row->semester }}</td>
<td class="jml_sks">{{ $row->jml_sks}}</td>
<td class="grade">{{ $grade }}</td>
</tr>
and then you could get the value by var grade = $("#km003 .grade").innerHTML;

Using v-bind to put data into a tag a in the property href (VUE.JS 2 + Laravel 5.3)

Here is my javascript/vue.js code:
import _ from 'lodash'
export default{
props:['campanha'],
data (){
return{
list:[],
filter: '',
href: '/campanha/9/edit'
}
},
methods:{
url: function (href){
return '/campanha/'+this.href+'/edit'
}
},
mounted: function (){
this.list = JSON.parse(this.campanha)
},
computed: {
filteredCampanhas(){
var self = this
return this.list.filter(function(campanhas) {
return campanhas.nome.indexOf(self.filter) > -1
})
}
}
}
And here it`s my html:
<template>
<div>
<div class="well">
Novo Cadastro <span class="glyphicon glyphicon-plus" aria-hidden="true"/><br></br>
<input type="text" class="form-control" placeholder="Filtrar Campanhas" v-model="filter">
</div>
<div class="table-responsive">
<table class="table table-borderless">
<thead>
<tr>
<th>Id</th>
<th>Nome</th>
<th>Data Início</th>
<th>Data Término</th>
<th>Hora Inícío</th>
<th>Hora Término</th>
</tr>
</thead>
<tbody>
<!--{{ url('/campanha/' . $item->id_campanha . '/edit') }}
href: '/campanha/9/edit'
<td><a v-bind:href="href">{{ c.nome }}</a></td>
!-->
<tr v-for="c in filteredCampanhas">
<td>{{ c.id_campanha }}</td>
<td><a :href="url(c.id_campanha)">{{ c.nome }}</a></td>
<td>{{ c.data_inicio }}</td>
<td>{{ c.data_termino }}</td>
<td>{{ c.hora_inicio }}</td>
<td>{{ c.hora_termino }}</td>
</tr>
</tbody>
</table>
</div>
<div>
</template>
I have tried to put some data into href section of my tag a, to link to another page, but it`s not working.
Try following:
methods:{
url: function (href){
return '/campanha/'+ href+'/edit'
}
},
When you are using this.href it will start to pick href from data of vue instance,

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.

Table viewby() function AngularJS

I have a table that can display data from database but in order to display the data, the API I am using is Post and has two variables for listcount and page. What I want is to display the list of data according to the list the user selects in the dropdown. My html code is of the following:
<tbody id="myTable">
<tr ng-repeat=" value in A ">
<td>{{ value.name }}</td>
<td>{{ value.number }}</td>
<td>{{ item.type }}</td>
<td style="text-align:center;">
<button class="btn btn-primary" >Edit</button>
</td>
</tr>
</tbody>
<div class="text-left">
<label>Show List Batch of:</label>
<select ng-model="listcount" ng-change="setItemsPerPage(listcount)">
<option>3</option>
<option>5</option>
<option>10</option>
<option>20</option>
<option>30</option>
</select> records at a time.
<br>
<pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()" class="pagination-sm" items-per-page="itemsPerPage"></pagination>
</div>
and my controller is like:
var page = "1";
var listCount = "5";
$scope.data = [];
$scope.viewby = 10;
$scope.totalItems = $scope.data.length;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.viewby;
$scope.maxSize = 5; //Number of pager buttons to show
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
console.log('Page changed to: ' + $scope.currentPage);
};
$scope.setItemsPerPage = function(num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1; //reset to first paghe
}
What am I doing wrong?
**Try It Once**
<tbody id="myTable">
<tr ng-repeat=" value in A | orderBy:'name'">
<td>{{ value.name }}</td>
<td>{{ value.number }}</td>
<td>{{ item.type}}</td>
<td style="text-align:center;">
<button class="btn btn-primary" >Edit</button>
</td>
</tr>
</tbody>

Categories

Resources