Gone fishing, because i like it - django

I have been trying to create Task manager with JavaScript and HTML. I'm quite new to programming, so hopefully someone will help me out with the following issue:
For some reason, the items of the array will not get into the table. Any helpful idea to solve this enigma? All help is appreciated!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
window.onload = init;
var descriptionS = new Array();
function init(){
var delBtn = document.getElementById("buttonDel");
delBtn.addEventListener('click', deleteRow, false);
var addTaskBtn = document.getElementById("addTask");
addTaskBtn.addEventListener('click', getTaskData, false);
var displayListBtn = document.getElementById("displayList");
displayListBtn.addEventListener('click', generateList, false);
var sortByNumBtn = document.getElementById("sortByNumber");
sortByNumBtn.addEventListener('click', sortListByNum, false);
}
function getTaskData(){
var myDescription = document.getElementById("descriptionField").value;
var myDate = document.getElementById("dateField").value;
var myPriority = document.getElementById("selRow0").value;
var description = new Object();
description.descriptionData = myDescription;
description.descriptionDate = myDate;
description.descriptionPriority = myPriority;
descriptionS.push(description);
}
function generateList(){
var myTaskList = document.getElementsByTagName("td");
myTaskList.innerHTML ="";
for(var p = 0; p < descriptionS.length; p++){
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
//Select cell
var cell0 = row.insertCell(0);
var selT = document.createElement("input");
selT.type = 'checkbox';
selT.name = 'chkBox';
selT.id = 'chkBox';
cell0.appendChild(selT);
// ID cell
var cell1 = document.createElement("td");
cell1 = row.insertCell(1);
var idFill = document.createTextNode(iteration);
cell1.appendChild(idFill);
cellSelect.appendChild(cell1);
//Description cell
var cell2 = document.createElement("td");
cell2 = row.insertCell(2);
var elF = document.createTextNode(descriptionS[p].descriptionData);
//elF.innerHTML = document.getElementById("descriptionField").value;
cell2.appendChild(elF);
// Priority cell
var cellPri = document.createElement("td");
cellPri = row.insertCell(3);
var pri = document.getElementbyId('selRow0').value;
pri.name = 'selRow' + iteration;
cellPri.appendChild(pri);
//Date
var cell4 = document.createElement("td");
cell4 = row.insertCell(4);
var elF1 = document.createTextNode(descriptionS[p].descriptionDate);
//elF.innerHTML = document.getElementById("descriptionField").value;
cell4.appendChild(elF1);
// Delete cell
var cell5 = document.createElement("td");
cell5 = row.insertCell(5);
var del1 = document.createElement('input');
del1.type = 'button';
del1.name = 'buttonDel';
del1.id = 'buttonDel';
del1.value = "Delete";
del1.onclick = function () {
var table = document.getElementById("tblSample");
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
};
cell5.appendChild(del1);
}
}
function sortListByNum(){
descriptionS.sort(sortFunctionByNumber);
generateList();
}
function sortFunctionByNumber(a, b){
return a.descriptionData-b.descriptionData;
}
function deleteRow(tableID) {
var table = document.getElementById("tblSample");
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
</head>
<body>
<form action="">
<p>
Description: <input type="text" id="descriptionField" />
Date: <input type="text" id="dateField" />
Priority: <select name="selRow0" id="selRow0" />
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="button" id="addTask" value="Add Task" />
<input type="button" id="displayList" value="Display Task" />
<input type="button" id="sortByNumber" value="Sort" />
</p>
<p>
<span id="spanOutput" style="border: 1px solid #000; padding: 3px;"> </span>
</p>
<table border="1" id="tblSample">
<tr>
<th>Select</th>
<th>ID</th>
<th>Description</th>
<th>Priority</th>
<th>Date</th>
<th>Delete</th>
</tr>
<tr>
<td><INPUT type="checkbox" name="chk"/></td>
<td>1</td>
<td>Example</td>
<td>
<select name="selRow1">
<option value="value1">1</option>
<option value="value2">2</option>
<option value="value3">3</option>
</select>
</td>
<td>06/06/2013</td>
<td>
<input type="button" value="Delete" id="buttonDel" />
</td>
</tr>
</table>
</form>
</body>
</html>

Use ExtJS GridPanel http://docs.sencha.com/ext-js/4-1/#!/example/grid/cell-editing.html
(Click to edit cell)

Related

How do I add more songs to my music player code, and get them to play?

As of now I have an html, javascript, and css file for a music player that plays 5 songs. I want it to play more songs, but when I add a sixth song to the code it will not display, or play it. Is there something written here that limits the song capacity? My goal is to ultimately upload a library of mp3 files into this initial player, then make subset players that are playlists catering to selective audiences.
HTML
<!DOCTYPE html>
<html>
<head>
<title>music player</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="main">
<p id="logo"><i class="fa fa-music"></i>Music</p>
<!-- show_song_number -->
<div class="show_song_no">
<p id="present">1</p>
<p>/</p>
<p id="total">5</p>
</div>
<!--- left part --->
<div class="left">
<!--- song img --->
<img id="track_image">
<div class="volume">
<p id="volume_show">90</p>
<i class="fa fa-volume-up" aria-hidden="true" onclick="mute_sound()" id="volume_icon"></i>
<input type="range" min="0" max="100" value="90" onchange="volume_change()" id="volume">
</div>
</div>
<!--- right part --->
<div class="right">
<!--- song title & artist name --->
<div class="song_detail">
<p id="title">title.mp3</p>
<p id="artist">Artist name</p>
</div>
<!--- middle part --->
<div class="middle">
<button onclick="previous_song()" id="pre"><i class="fa fa-step-backward" aria-hidden="true"></i></button>
<button onclick="justplay()" id="play"><i class="fa fa-play" aria-hidden="true"></i></button>
<button onclick="next_song()" id="next"><i class="fa fa-step-forward" aria-hidden="true"></i></button>
</div>
<!--- song duration part --->
<div class="duration">
<input type="range" min="0" max="100" value="0" id="duration_slider" onchange="change_duration()">
<button id="auto" onclick="autoplay_switch()">Auto <i class="fa fa-circle-o-notch" aria-hidden="true"></i></button>
</div>
</div>
</div>
<!--- Add javascript file --->
<script src="main.js"></script>
</body>
</html>
JAVASCRIPT
let previous = document.querySelector('#pre');
let play = document.querySelector('#play');
let next = document.querySelector('#next');
let title = document.querySelector('#title');
let recent_volume= document.querySelector('#volume');
let volume_show = document.querySelector('#volume_show');
let slider = document.querySelector('#duration_slider');
let show_duration = document.querySelector('#show_duration');
let track_image = document.querySelector('#track_image');
let auto_play = document.querySelector('#auto');
let present = document.querySelector('#present');
let total = document.querySelector('#total');
let artist = document.querySelector('#artist');
let timer;
let autoplay = 0;
let index_no = 0;
let Playing_song = false;
//create a audio Element
let track = document.createElement('audio');
//All songs list
let All_song = [
{
name: "first song",
path: "audio/a-million-views.mp3",
img: "images/logo.png",
singer: "1"
},
{
name: "second song",
path: "2.mp3",
img: "img2.jpg",
singer: "2"
},
{
name: "third song",
path: "3.mp3",
img: "img3.jpg",
singer: "3"
},
{
name: "fourth song",
path: "4.mp3",
img: "img4.jpg",
singer: "4"
},
{
name: "fifth song",
path: "5.mp3",
img: "img5.jpg",
singer: "5"
}
];
// All functions
// function load the track
function load_track(index_no){
clearInterval(timer);
reset_slider();
track.src = All_song[index_no].path;
title.innerHTML = All_song[index_no].name;
track_image.src = All_song[index_no].img;
artist.innerHTML = All_song[index_no].singer;
track.load();
timer = setInterval(range_slider ,1000);
total.innerHTML = All_song.length;
present.innerHTML = index_no + 1;
}
load_track(index_no);
//mute sound function
function mute_sound(){
track.volume = 0;
volume.value = 0;
volume_show.innerHTML = 0;
}
// checking.. the song is playing or not
function justplay(){
if(Playing_song==false){
playsong();
}else{
pausesong();
}
}
// reset song slider
function reset_slider(){
slider.value = 0;
}
// play song
function playsong(){
track.play();
Playing_song = true;
play.innerHTML = '<i class="fa fa-pause" aria-hidden="true"></i>';
}
//pause song
function pausesong(){
track.pause();
Playing_song = false;
play.innerHTML = '<i class="fa fa-play" aria-hidden="true"></i>';
}
// next song
function next_song(){
if(index_no < All_song.length - 1){
index_no += 1;
load_track(index_no);
playsong();
}else{
index_no = 0;
load_track(index_no);
playsong();
}
}
// previous song
function previous_song(){
if(index_no > 0){
index_no -= 1;
load_track(index_no);
playsong();
}else{
index_no = All_song.length;
load_track(index_no);
playsong();
}
}
// change volume
function volume_change(){
volume_show.innerHTML = recent_volume.value;
track.volume = recent_volume.value / 100;
}
// change slider position
function change_duration(){
slider_position = track.duration * (slider.value / 100);
track.currentTime = slider_position;
}
// autoplay function
function autoplay_switch(){
if (autoplay==1){
autoplay = 0;
auto_play.style.background = "rgba(255,255,255,0.2)";
}else{
autoplay = 1;
auto_play.style.background = "#148F77";
}
}
function range_slider(){
let position = 0;
// update slider position
if(!isNaN(track.duration)){
position = track.currentTime * (100 / track.duration);
slider.value = position;
}
// function will run when the song is over
if(track.ended){
play.innerHTML = '<i class="fa fa-play" aria-hidden="true"></i>';
if(autoplay==1){
index_no += 1;
load_track(index_no);
playsong();
}
}
}

Django Dynamic form for manytomany relationship

I am trying to make a form which includes the functionality of Add/Delete Row. And I am following this tutorial.
The problem that I am facing is that I am unable to show the Add or remove button as well as the input fields in the form.
Screenshot:
Here's the template:
<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="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form action="" method="post" class="">
{% csrf_token %}
<h2> Team</h2>
{% for field in form %}
{{ field.errors }}
{{ field.label_tag }} : {{ field }}
{% endfor %}
{{ form.players.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.players %}
<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>
Please help me figure out what the code is missing, I tried the solution given in comments too but that only solves the input fields problem
You can do this by looping through the last row added to the table and then updating all id & name attributes with new incremented i value like:
$("tbody tr:last :input").each(function() {
$(this).attr({
'id': function(_, id) {
return id.replace(/\d/g, i)
},
'name': function(_, name) {
return name.replace(/\d/g, i)
}
})
})
Also as Paul mentioned change players to player
I haven't reproduced your code so I can't be sure, but when I look at your models I read:
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()
You pass the Teamform to the template in the variable form. That means you can access the individual player forms with:
{% for player in form.player %}
...
{% endfor %}
In your code I read form.players instead of form.player. Also at the top I read form.players.management_form. Django will not recognize these variables so return empty values. You can check this by looking at the HTML elements in your browser. In the example in the comments in the link you provided it says correctly form.player. I am not sure why in that case the add / remove button would not show.

Data is not displayed on the browser from the blockchain server on solidity

I am trying to make a voting app using Blockchain on truffle framework. The data from the network is not rendered on the webpage.
Only loading is displayed but the actual content is not displayed even though I have connected by Blockchain accounts from Ganache to my metamask extension.
Here is my code:
Election.sol
pragma solidity ^0.5.0;
contract Election {
// Model a Candidate for first past the post system
struct Candidatepost {
uint id;
string name;
uint voteCount;
}
// Model as candidate for proportional party system
struct Candidateparty {
uint id;
string name;
uint voteCount;
}
// Store accounts that have voted
mapping(address => bool) public voters;
// Store Candidates
// Fetch Candidate
mapping(uint => Candidatepost) public cand_post;
mapping(uint => Candidateparty) public cand_party;
// Store Candidates Count
uint public partyCount;
uint public postCount;
uint[] public candidatesCount = [postCount,partyCount];
constructor () public {
addpostCandidate("Candidate 1");
addpostCandidate("Candidate 2");
addpartyCandidate("Candidate 1");
addpartyCandidate("Candidate 2");
candidatesCount = [postCount,partyCount];
}
function addpostCandidate (string memory _name) private {
postCount ++;
cand_post[postCount] = Candidatepost(postCount, _name, 0);
}
function addpartyCandidate (string memory _name) private {
partyCount ++;
cand_party[partyCount] = Candidateparty(partyCount, _name, 0);
}
// voted event
event votedEvent (
uint indexed _candidateId1,
uint indexed _candidateId2
);
function vote (uint _candidateId1, uint _candidateId2) public {
// require that they haven't voted before
require(!voters[msg.sender]);
// require a valid candidate
require(_candidateId1 > 0 && _candidateId1 <= postCount && _candidateId2 > 0 && _candidateId2 <= partyCount);
// record that voter has voted
voters[msg.sender] = true;
// update candidate vote Count
cand_post[_candidateId1].voteCount ++;
cand_party[_candidateId2].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId1, _candidateId2);
}
}
App.js
App = {
web3Provider: null,
contracts: {},
account: '0x0',
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// TODO: refactor conditional
if (typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask.
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
web3 = new Web3(App.web3Provider);
}
return App.initContract();
},
initContract: function() {
$.getJSON("Election.json", function(election) {
// Instantiate a new truffle contract from the artifact
App.contracts.Election = TruffleContract(election);
// Connect provider to interact with contract
App.contracts.Election.setProvider(App.web3Provider);
App.listenForEvents();
return App.render();
});
},
// Listen for events emitted from the contract
listenForEvents: function() {
App.contracts.Election.deployed().then(function(instance) {
// Restart Chrome if you are unable to receive this event
// This is a known issue with Metamask
// https://github.com/MetaMask/metamask-extension/issues/2393
instance.votedEvent({}, {
fromBlock: 0,
toBlock: 'latest'
}).watch(function(error, event) {
console.log("event triggered", event)
// Reload when a new vote is recorded
App.render();
});
});
},
render: function() {
var electionInstance;
var loader = $("#loader");
var content = $("#content");
loader.show();
content.hide();
// Load account data
web3.eth.getCoinbase(function(err, account) {
if (err === null) {
App.account = account;
$("#accountAddress").html("Your Account: " + account);
}
});
//load contract data
App.contracts.Election.deployed().then(function(instance) {
electionInstance = instance;
return electionInstance.candidatesCount();
}).then(function(1) {
var postcandidatesResults = $("#postcandidatesResults");
postcandidatesResults.empty();
var partycandidatesResults = $("#partycandidatesResults");
partycandidatesResults.empty();
var postcandidatesSelect = $('#postcandidatesSelect');
postcandidatesSelect.empty();
var partycandidatesSelect = $('#partycandidatesSelect');
partycandidatesSelect.empty();
for (var i = 1; i <= 2; i++) {
electionInstance.cand_post(i).then(function(candidate) {
var id = candidate[0];
var name = candidate[1];
var voteCount = candidate[2];
// Render candidate Result
var candidateTemplate = "<tr><th>" + id + "</th><td>" + name + "</td><td>" + voteCount + "</td></tr>";
postcandidatesResults.append(candidateTemplate);
// Render candidate ballot option
var candidateOption = "<option value='" + id + "' >" + name + "</ option>";
postcandidatesSelect.append(candidateOption);
});
}
for (var j = 1; j <= 2; j++) {
electionInstance.cand_party(i).then(function(candidate) {
var id2 = candidate[0];
var name2 = candidate[1];
var voteCount2 = candidate[2];
// Render candidate Result
var candidateTemplate2 = "<tr><th>" + id2 + "</th><td>" + name2 + "</td><td>" + voteCount2 + "</td></tr>";
partycandidatesResults.append(candidateTemplate2);
// Render candidate ballot option
var candidateOption2 = "<option value='" + id2 + "' >" + name2 + "</ option>";
partycandidatesSelect.append(candidateOption2);
});
}
return electionInstance.voters(App.account);
}).then(function(hasVoted) {
// Do not allow a user to vote
if(hasVoted) {
$('form').hide();
}
loader.hide();
content.show();
}).catch(function(error) {
console.warn(error);
});
},
castVote: function() {
var candidateId1 = $('#postcandidatesSelect').val();
var candidateId2 = $('#partycandidatesSelect').val();
App.contracts.Election.deployed().then(function(instance) {
return instance.vote(candidateId1, candidateId2, { from: App.account });
}).then(function(result) {
// Wait for votes to update
$("#content").hide();
$("#loader").show();
}).catch(function(err) {
console.error(err);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Election Results</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container" style="width: 650px;">
<div class="row">
<div class="col-lg-12">
<h1 class="text-center">
<div class="row d-flex justify-content-center" style="border:none;background:white;">
<div class="col-md-1 col-3">
<img class="mx-auto d-block img-fluid" src="images/logo.png" style="" alt="">
</div>
</div></h1>
<hr/>
<br/>
<h1 class="text-center">National Election-2075</h1>
<h1 class="text-center">Election Updates</h1>
<div id="loader">
<p class="text-center">Loading...</p>
</div>
<div id="content" style="display: none;">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody id="postcandidatesResults">
</tbody>
</table>
<hr/>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody id="partycandidatesResults">
</tbody>
</table>
<hr/>
<form onSubmit="App.castVote(); return false;">
<div class="form-group">
<label for="postcandidatesSelect">Select Candidate</label>
<select class="form-control" id="postcandidatesSelect">
</select>
</div>
<div class="form-group">
<label for="partycandidatesSelect">Select Candidate</label>
<select class="form-control" id="partycandidatesSelect">
</select>
</div>
<button type="submit" class="btn btn-primary">Vote</button>
<hr />
</form>
<p id="accountAddress" class="text-center"></p>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Any call to the blockchain is async(returns a promise). You need to either handle the promise with a .then() or you can use async await. Basically anything chained after electionInstance is async. For example:
electionInstance.candidatesCount();
electionInstance.cand_party
electionInstance.voters

Select2, need to group results into one for display

I use "multiple select boxes" (select2 examples) and I want to group showing results:
like (only if selected more then X options):
Whithout this the field with the results will be too large. Also, I don't want to make a scroll in the field results.
Is there any ready solution to do this?
I created the solution:
$(document).ready(function() {
$(".test").select2();
});
function select_grouping(obj) {
var min_grouping_count = 3;
var title = ' elements selected';
var count = 0;
if (obj.children('li').length > min_grouping_count) {
if (obj.children('li').length > min_grouping_count) {
count = obj.children('li').length - 1;
obj.children('li').each(function(index, el) {
if (index > 0 && index < count) {
$(this).remove();
}
});
}
obj.children('li:eq(0)').html(count + title);
}
}
$(".test").on("select2:select", function(obj) {
var obj = $('#filtr_test').find('.select2-selection__rendered');
select_grouping(obj);
});
$(".test").on("select2:unselect", function(obj) {
var obj = $('#filtr_test').find('.select2-selection__rendered');
select_grouping(obj);
});
.test {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<div id="filtr_test">
<select class="test" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
<option value="6">six</option>
<option value="7">seven</option>
</select>
</div>

Knockoutjs list in a list select binding

I have seen so many example of this problem but not as a list. Here's my code:
<div>
<form>
<p>You have asked for <span data-bind='text: gifts().length'> </span> gift(s)</p>
<input id='giftname' type='text'/><button data-bind='click: createGift'>Add Gift</button>
<table>
<thead>
<tr>
<th>Gift name</th>
<th>Pack</th>
<th>Price</th>
<th />
</tr>
</thead>
<tbody data-bind='foreach: gifts'>
<tr>
<td><input data-bind='value: name' readonly='readonly'/></td>
<td><select data-bind="options: packs,
optionsText: 'pack',
value: price" /></td>
<td><input data-bind="value: price ? price.packprice : 'unknown'" readonly="readonly"/></td>
<td><a href='#' data-bind='click: $root.removeGift'>Delete</a></td>
</tr>
</tbody>
</table>
<button data-bind='enable: gifts().length > 0' type='submit'>Submit</button>
</form>
</div>
<script type="text/javascript">
var GiftModel = function(gifts) {
var self = this;
self.gifts = ko.observableArray(gifts);
self.addGift = function(gift) {
var newGift = {
name: gift.name,
packs: gift.packs,
price: gift.price
};
self.gifts.push(newGift);
};
self.removeGift = function(gift) {
self.gifts.remove(gift);
};
self.createGift = function() {
var gname = $('#giftname').val();
//should be getting gift options from webservice
var newGift = {name: gname,
packs: [{pack:'Each', packprice: '2'}, {pack:'Dozen', packprice: '12'}], price: {pack:'', packprice: ''}};
self.addGift(newGift);
$('#giftname').val('');
};
};
var viewModel = new GiftModel([]);
ko.applyBindings(viewModel);
</script>
When I add gifts, it creates options of packs. Each pack has a certain price. My problem is just simple. How will I show the price on the next column for the selected pack of the gift line? Sorry im just new to knockoutjs. Thanks!
System will automatically update price after selecting package if you make it observable. I made a little refactoring to you code, now it works:
<div>
<form>
<p>You have asked for <span data-bind='text: gifts().length'> </span> gift(s)</p>
<input
id='giftname' type='text' data-bind='value: giftName' />
<button data-bind='click: createGift'>Add Gift</button>
<table>
<thead>
<tr>
<th>Gift name</th>
<th>Pack</th>
<th>Price</th>
<th />
</tr>
</thead>
<tbody data-bind='foreach: gifts'>
<tr>
<td>
<input data-bind='value: name' readonly='readonly' />
</td>
<td>
<select data-bind="options: packs,
optionsText: 'pack',
optionsValue: 'packprice',
value: price" />
</td>
<td>
<input data-bind="value: price() || 'unknown'" readonly="readonly"
/>
</td>
<td><a href='#' data-bind='click: $root.removeGift'>Delete</a>
</td>
</tr>
</tbody>
</table>
<button data-bind='enable: gifts().length > 0' type='submit'>Submit</button>
</form>
</div>
function GiftModel(name) {
var self = this;
self.name = ko.observable(name);
self.price = ko.observable();
self.packs = ko.observable([{
pack: 'Each',
packprice: '2'
}, {
pack: 'Dozen',
packprice: '12'
}]);
}
var ViewModel = function (gifts) {
var self = this;
self.gifts = ko.observableArray(gifts);
self.giftName = ko.observable();
self.removeGift = function (gift) {
self.gifts.remove(gift);
};
self.createGift = function () {
self.gifts.push(new GiftModel(self.giftName()));
};
};
var viewModel = new ViewModel([]);
ko.applyBindings(viewModel);
Here is working fiddle: http://jsfiddle.net/vyshniakov/pzJaH/
P.S. Don't use jQuery to get field value if you using knockout. It is much easier to do this with knockout.