How to get element id using v-for vuejs directive? - javascript

I'm a vue.js beginner, so I need help.
I write an HTML page which show a list of object in a simple table.
The table is made by a script which get a JSON object from a servlet and shows it using a v-for directive.
In each row of the table, there is a button that the user can click to book the object wrote in the corresponding row, using a form.
The problem is that I don't know how to get the object's information correspondent to the clicked line to put it in the form's fields.
This is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Repetition - catalog</title>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style2.css" />
</head>
<body>
<header><h1>REPETITIONS.com</h1></header>
<div id="app" class="float-container" style="height: 80%">
<table class="catalog-table">
<thead>
<tr>
<th style="width: 200px">Corso</th>
<th style="width: 250px">Docente</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="rep in reps">
<td>{{rep.teacherName}} {{rep.teacherSurName}}</td>
<td>{{rep.course}}</td>
<td>
<form action="/Repetition/controller/ServletController" method="post" id="i">
<input type="hidden" name="operation" value="booking">
<input type="hidden" name="id_t" value="rep.getId_teac"> <---set the value of the current row
<input type="hidden" name="id_c" value="rep.getId_cor"> <---set the value of the current row
<button type="submit">Book</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
<footer>xxxxxxx</footer>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var app = new Vue ({
el: '#app',
data: {
repetitions: [],
link: '/Repetition/ServletController?operation=catalog&device=x'
},
mounted(){
this.getRepetitions()
},
methods:{
getRepetitions: function(){
var self = this;
$.get(this.link, function(data) {
self.repetitions = data;
});
}
}
});
</script>
</body>
</html>
Alternatively the form request could be manage with another script, but there would be the same problem.

Related

How to make DataTable, but the row is only appended

I have a table that add rows manually, but I want to make it into a DataTable to make it friendly user. But I don't know how to do it.
I tried to search it online and I see this, it is similar but it is not working or I'm doing something wrong... See here
Also this is my code :
const tbody = document.getElementById("choicesListTbodyADD");
const btnAdd = document.querySelector("button");
const inputChoices = document.querySelector("input");
var count = 1;
btnAdd.addEventListener("click", function () {
$(tbody).append(`<tr><td>${count}</td><td>${inputChoices.value.trim()}</td><td>DELETE</td></tr>`)
inputChoices.value = '';
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br><br>
<input type="text" id="choices"/>
<button id="appendChoices">Add Choices</button>
<br><br>
<table class="table text-center table-bordered table-striped dataTable dtr-inline" id="ADDchoicesARTableListSequence">
<tr>
<th>No.</th>
<th>Choices</th>
<th>Action</th>
</tr>
<tbody id="choicesListTbodyADD"></tbody>
</table>
Here is an approach, based on your non-DataTables code.
I have included the Bootstrap libraries I think you need - but you can adjust those if needed.
$(document).ready(function() {
var table = $('#ADDchoicesARTableListSequence').DataTable();
const tbody = document.getElementById("choicesListTbodyADD");
const btnAdd = document.querySelector("button");
const inputChoices = document.querySelector("input");
var count = 1;
btnAdd.addEventListener("click", function() {
table.row.add($(`<tr><td>${count}</td><td>${inputChoices.value.trim()}</td><td>DELETE</td></tr>`)).draw();
count += 1;
inputChoices.value = '';
})
});
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.1/css/dataTables.bootstrap5.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.13.1/js/dataTables.bootstrap5.js"></script>
</head>
<body>
<div style="margin: 20px;">
<input type="text" id="choices" />
<button id="appendChoices">Add Choices</button>
<br><br>
<table class="table text-center table-bordered table-striped dataTable dtr-inline" id="ADDchoicesARTableListSequence">
<thead>
<tr>
<th>No.</th>
<th>Choices</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
The main points to note:
Your HTML table does not need a <body> in this case, as DataTables will provide it for you.
Don't forget to use draw() after adding each row - to re-draw the table, so the new data is displayed.
In this case, I create a new DOM node from your data using $(<tr>...</tr>). But you can see from the documentation that there are other ways you can create new rows:
using an array
using an object
using a node (which is what we do here)
I chose to use a node because that is the closest to what your code already does.

How to update a number in HTML by incrementing it when a new text input is submited?

I need to add +1 to the total number of tweets when a new tweet (text input) is submitted:
Here is my HTML:
<!DOCTYPE html>
<html lang="en" data-ng-app="Twitter">
<head>
<meta charset="UTF-8">
<title>Twitter Clone</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="profileArea">
<img id="profile" src="http://potdeli.webs.com/twitter.png" alt="tweet">
<p style="color:white;"><strong>Tweeto</strong></p>
<p>#TweetoTwiteech</p>
<table style="width:100%">
<tr>
<th>Tweets</th>
<th colspan="1">Following</th>
<th colspan="1">Followers</th>
</tr>
<tr>
<td>2</td>
<td>0</td>
<td>0</td>
</tr>
</table>
</div>
<div class="tweets" ng-app="" ng-controller="TweetsController">
<form method="POST" action="" ng-submit="addTweet()">
<h2>Compose new tweet</h2>
<input name="tweet" type="text" ng-model="newTweet" ng-maxlength="140" placeholder="What's happening?">
<button type="submit" value="addTweets">Tweet!</button>
</form>
<div class="tweetDisplay" ng-repeat="tweet in tweets track by $index">{{ tweet }}
</div>
</div>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.5/angular.min.js">
</script>
<script src="tweets.js">
</script>
</body>
</html>
And here is the JavaScript:
function TweetsController($scope) {
$scope.tweets = ["First sample tweet", "Second sample tweet"];
$scope.addTweet = function() {
if(this.newTweet) {
$scope.tweets.push($scope.newTweet);
$scope.newTweet = "";
}
};
}
I tried a couple of things but I didn't get the desired result, also I checked out a few similar Stack Overflow questions but I wasn't able to get it figured out.
Oh man, I can't believe what a half-wit I am! I just added:
<td>{{ tweets.length }}</td>
Instead of number 2, as the number of tweets and placed this on the body:
<body ng-app="" ng-controller="TweetsController">
Thanks to all for pointing me in the right direction!!
Your table markup is outside of your controller scope. Make it part of your controller scope, and then you could print a counter value there, such as $scope.tweets.length

CSV to HTML table using d3 and an external javascript file

I'm found on the internet a simple example (http://bl.ocks.org/ndarville/7075823) how to convert a .csv file into a table in HTML. I implemented the same example inside a container and it works really well. So, I decided to put its javascript code in an external file in order to be implemented in my application, but it is not working. I'm wondering why does don't work. I would appreciate id anyone could help me because I don't have any kind of experience with D3.
//-------------------------file myscript.js -------------------------------------//
function sTest(){
d3.text("data.csv", function(data) {
var parsedCSV = d3.csv.parseRows(data);
var container = d3.select("#dataTable")
.append("table")
.selectAll("tr")
.data(parsedCSV).enter()
.append("tr")
.selectAll("td")
.data(function(d) { return d; }).enter()
.append("td")
.text(function(d) { return d; });
}
//----------------------------file index.html -------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<script src="myscript.js"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<div class="w3-container w3-cell-row w3-lobster">
<p class="w3-xxlarge">Data Table:</p>
</div> //container where should be contained a table
<div style="height:350px;" class="w3-cell-row">
<div id="dataTable" class="w3-container w3-cell w3-center w3-cell-middle w3-border w3-border-blue w3-round-xlarge">
</div>
<div style="width:320px;" class="w3-container w3-cell w3-cell-middle w3-border w3-border-green w3-round-xlarge">
<table class="w3-table w3-bordered">
<tr>
<th>$$Resistor\,(R):$$</th>
</tr>
<tr>
<td><center><input type="number" style="text-align:center" id="Res" value="0" >
<label style="font:16px">$$\Omega$$</label></center></td>
</tr>
<tr>
<th>$$Resistor\,(R_B):$$<th>
</tr>
<tr>
<td><center><input type="number" style="text-align:center" id="Resb" value="0">
<label style="font:16px">$$\Omega$$</label></center></td>
</tr>
<tr>
<th>$$Resistor\,(R_C):$$</th>
</tr>
<tr>
<td><center><input type="number" style="text-align:center" id="Resc" value="0">
<label style="font:16px">$$\Omega$$</label></center></p></td>
</tr>
</table>
</div>
</div>
<p align="center"><input type="button" name="start" id="start" value="Start" onclick="sTest()" style="color:#00cc00">
</body>
</html>
Swap the order of the javascript references around.
myscript.js (where you have the code invoking d3 methods) is dependent on the d3js library so ensure that the d3js library is loaded first as follows:
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="myscript.js"></script>
For additional explanation on loading js libraries, read the accepted answer on this SO question:
load and execute order of scripts

Getting total sum of rows and adding and removing rows using knockoutjs

I am fairly new to knockoutjs. I am creating a simple table and trying to sum up all the values in the "total" column. Plus, I am also implementing "Add column" and "Remove Column" functionalities using knockoutjs.
The problem is that both the Add and Remove funcitonalities and not working. Plus,the "TotalSurcharge" value is not displaying on the UI.
Here's my js:
// Class to represent a row in the table
function addMaterial() {
this.name = ko.observable("");
this.quantity = ko.observable("");
this.rate = ko.observable(0);
this.formattedTotal = ko.computed(function() {
return this.rate() * this.quantity();
}, this);
}
function documentViewModel(){
var self = this;
//create a mateirals array
self.materials = ko.observableArray([
new addMaterial()
]);
// Computed data
self.totalSurcharge = ko.computed(function() {
var total = 0;
for (var i = 0; i < self.materials().length; i++)
total += self.materials()[i].formattedTotal();
return total;
});
// Operations
self.addMaterial = function() {
self.materials.push(new addMaterial());
}
self.removeMaterial = function(material) { self.materials.remove(material) }
}
ko.applyBindings(new documentViewModel());
Here's my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type='text/javascript' src='knockout-2.2.0.js'></script>
</head>
<body>
<div class="container">
<table class="table table-bordered">
<thead>
<tr>
<th>Item</th>
<th>Quantity </th>
<th>Rate</th>
<th>Total</th>
</tr>
</thead>
<tbody "foreach: materials">
<tr class="info">
<td><input data-bind="value: name" /></td>
<td><input data-bind="value: quantity" /></td>
<td><input data-bind="value: rate" /></td>
<td data-bind="text: formattedTotal"></td>
<td>Remove</td>
</tr>
</tbody>
</table>
<button data-bind="click: addMaterial, enable: materials().length < 5">Add Row</button>
<h3 data-bind="visible: totalSurcharge() > 0">
Total surcharge: $<span data-bind="text: totalSurcharge().toFixed(2)"></span>
</h3>
</div>
</body>
<script type='text/javascript' src='application.js'></script>
</html>
I checked the console error on the browser but am not getting any error. Any idea what am I doing wrong?
I think you intended to bind the materials to the table body, this is not right:
<tbody "foreach: materials">
It should be:
<tbody data-bind="foreach: materials">
Once that is fixed, everything else appears to work.
fiddle

Checkbox when checked, should make a textbox too enable else disable

I've written the following code, which enables a textbox when the checkbox is checked. The code is working with a small defect. For the first time when we execute, the textbox is enabled irrespective of the checkbox is checked or unchecked. But after a couple of times, the code is working correctly. Please help me to find the bug.
<html>
<head>
<title>SHOP ALL</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script language="javascript" src="addcart.js"></script>
<script type="text/javascript">
function enableDisable(bEnable, textBoxID)
{
document.getElementById(textBoxID).disabled = !bEnable
}
</script>
</head>
<body>
<form>
<table align="center" width="100%" cellpadding="50px">
<tr>
<th> TICK ON THE THINGS YOU NEED </th>
<th> PRODUCT </th>
<th> DESCRIPTION </th>
<th> NO OF ITEMS </th>
</tr>
<tr>
<td><input type="checkbox" name="shoe" onclick="enableDisable(this.checked, '0')"></td>
<td><img src="images/1.jpg" alt="shoe1" width="180px" height="200px"></td>
<td><h4>-------</h4></td>
</tr>
--------------
</body>
</html`>
You should put your code:
<script type="text/javascript">
function enableDisable(bEnable, textBoxID)
{
document.getElementById(textBoxID).disabled = !bEnable
}
</script>
before closing the body, or to be invoked on DOM ready. In this way the code is being executed before even the checkbox and the text field exists.
By default the text input is enabled so you may need also to set the checkbox as checked.
Here is a working version:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
</head>
<body>
<input type="text" id="txtBox" />
<input type="checkbox" id="chkbox" onchange="document.getElementById('txtBox').disabled=!this.checked;" checked="checked" />
</body>
</html>
And a demo: http://jsbin.com/ulemim/2

Categories