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

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();
}
}
}

Related

adding fields of a formset dynamically

i have a formset inside my form on django and i need to do a button add to offer to the user the possibility to fill the fields of the formset as many time as he wants. i used a javascript code to do that and i do all the following steps to link the js file with the project, but when i click on the button nothing happens, i don't know why. please if anyone could help me.
i add staticfiles on my settings
STATIC_URL = '/static/'
STATICFILES_DIRS = (BASE_DIR / "static",)
part of my html file
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ordonnancement </title>
...
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body class="bg-gray-100">
<form action="/" method="post" class="join-form mt-8 m-auto">
{% csrf_token %}
...
{% for form_data in formset %}
<div class="mt-4 w-1/2 mx-1">
{{ form_data.nom_qualité }}
</div>
<div class="mt-4 w-1/2 mx-1">
{{ form_data.id_qualité }}
</div>
<div class="mt-4 w-1/2 mx-1">
{{ form_data.date_début }}
</div>
<div class="mt-4 w-1/2 mx-1">
{{ form_data.date_fin }}
</div>
{% endfor %}
<button type="button" class="btn btn-sm btn-success add-form-row"
id="{{ formset.prefix }}">
ajouter
</button>
{{ formset.management_form }}
...
</form>
<script type="text/javascript" src="{% static 'js/formset.js' %}">
</script>
js file
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());
if (formCount < 1000) {
// Clone a form (without event handlers) from the first form
var row = $(".item:last").clone(false).get(0);
// Insert it after the last form
$(row).removeAttr('id').hide().insertAfter(".item:last").slideDown(300);
// Remove the bits we don't want in the new row/form
// e.g. error messages
$(".errorlist", row).remove();
$(row).children().removeClass("error");
// Relabel or rename all the relevant bits
$(row).find('.formset-field').each(function () {
updateElementIndex(this, prefix, formCount);
$(this).val('');
$(this).removeAttr('value');
$(this).prop('checked', false);
});
// Add an event handler for the delete item/form link
$(row).find(".delete").click(function () {
return deleteForm(this, prefix);
});
// Update the total form count
$("#id_" + prefix + "-TOTAL_FORMS").val(formCount + 1);
} // End if
return false;
}
function deleteForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
if (formCount > 1) {
// Delete the item/form
var goto_id = $(btn).find('input').val();
if( goto_id ){
$.ajax({
url: "/" + window.location.pathname.split("/")[1] + "/formset-data-delete/"+ goto_id +"/
next="+ window.location.pathname,
error: function () {
console.log("error");
},
success: function (data) {
$(btn).parents('.item').remove();
},
type: 'GET'
});
}else{
$(btn).parents('.item').remove();
}
var forms = $('.item'); // Get all the forms
// Update the total number of forms (1 less than before)
$('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
var i = 0;
// Go through the forms and set their indices, names and IDs
for (formCount = forms.length; i < formCount; i++) {
$(forms.get(i)).find('.formset-field').each(function () {
updateElementIndex(this, prefix, i);
});
}
} // End if
return false;
}
$("body").on('click', '.remove-form-row',function () {
deleteForm($(this), String($('.add-form-row').attr('id')));
});
$("body").on('click', '.add-form-row',function () {
return addForm($(this), String($(this).attr('id')));
});

How to sort cart items in order

I am building a Django e-commerce website and as I was working on my cart functionality I noticed that every time I try to change the quantity of a specific item in the cart, all the items in the cart are re-sorted in a different order. I was wondering if there's any way I can sort the items in the backend before they are displayed.
** I am getting this error only when the user is "Authenticated" ** Guest checkout is working correctly
This is my cart Views.py
def cart(request):
# Authenticated Checkout
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
cartItems = order.get_cart_items
items = order.orderitem_set.all()
if cartItems == 0:
context = {"items": items, "order": order, "cartItems": cartItems}
return render(request, "cart_empty.html", context)
#Guest Checkout
else:
data = cartData(request)
cartItems = data["cartItems"]
order = data["order"]
items = data["items"]
if cartItems == 0:
context = {"items": items, "order": order, "cartItems": cartItems}
return render(request, "cart_empty.html", context)
context = {"items":items, "order": order, "cartItems":cartItems}
return render(request, "cart.html", context)
def update_cart(request):
data = json.loads(request.body)
productId = data["productId"]
action = data["action"]
customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
if action == "add":
orderItem.quantity = (orderItem.quantity + 1)
elif action == "reduce":
orderItem.quantity = (orderItem.quantity - 1)
orderItem.save()
if action == "remove":
orderItem = orderItem.delete()
return JsonResponse("item was added", safe=False)
This is My JavaScript File
// Getting the cart cookie Value stored in the browser
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
var cart = JSON.parse(getCookie("cart"));
// Finding all the Minus buttons on the page and adding a click event listener to each one
const reduce_btn = document.getElementsByClassName("btn minus1 update-cart")
for (i = 0; i < reduce_btn.length; i++) {
reduce_btn[i].addEventListener("click", function(event){
var productId = this.dataset.id
var action = this.dataset.action
if (user === "AnonymousUser"){
addCookieItem(productId, action)
} else {
updateUserOder(productId,action)
}
})
}
// Finding all the Plus buttons on the page and adding a click event listener to each one
const increase_btn = document.getElementsByClassName("btn add1 update-cart")
for (i = 0; i < increase_btn.length; i++){
increase_btn[i].addEventListener("click", function(event){
var productId = this.dataset.id
var action = this.dataset.action
if (user === "AnonymousUser"){
addCookieItem(productId, action)
} else {
updateUserOder(productId,action)
}
})
}
// Finding all the remove buttons on the page and adding a click event listener to each one
const removeButton = document.getElementsByClassName("removeButton")
for (i = 0; i < removeButton.length; i++) {
removeButton[i].addEventListener("click", function(event){
var productId = this.dataset.id
var action = this.dataset.action
if (user === "AnonymousUser"){
removeFromCart(productId, action)
} else {
updateUserOder(productId,action)
}
})
}
// Removing the product from the order if the remove button is clicked
function removeFromCart(productId, action) {
if (action == 'remove'){
delete cart[productId];
}
document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
location.reload()
}
// (Guest Checkout) Updating the order of the customer if he is not authenticated
function addCookieItem(productId, action) {
console.log("not logged in..........")
if (action == 'add'){
cart[productId]['quantity'] += 1
}
if (action == 'reduce'){
cart[productId]['quantity'] -= 1
}
document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
location.reload()
}
// csrf token
var csrftoken = localStorage.getItem("csrftoken")
// (Authenticated Checkout) Updating the order of the customer if he is Authenticated
function updateUserOder(productId, action){
var url = "http://127.0.0.1:8000/update_cart/"
fetch(url, {
method: "POST",
headers: {
"Content-Type":"application/json",
"X-CSRFToken":csrftoken,
},
body:JSON.stringify({"productId": productId, "action": action})
})
.then((response) =>{
return response.json();
})
.then((data) => {
location.reload()
})
}
This is my HTML File
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cart</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/cart.css' %}">
<script type="text/javascript">
var user = "{{request.user}}"
</script>
</head>
<body>
<!-- navigation menu -->
{% include "topnav.html" %}
<div class="maincontent">
<h1 class="hhh1" style="font-size:50px; margin:0px; margin-bottom:30px">Your Cart</h1>
<div class="centerblock">
<!-- DYNAMIC CONTENT GOES HERE -->
<div class="cart-row">
<span class="cart-item cart-header cart-column">ITEM</span>
<span class="cart-header cart-column">PRICE</span>
<span class="cart-quantity cart-header cart-column">QUANTITY</span>
</div>
<div class="cart-items">
{% for item in items %}
<div>
<div class="cart-item cart-column">
<img class="cart-item-image" src="{{item.product.imageURL}}" width="100" height="100">
<span class="cart-item-title">{{item.product.title}}</span>
</div>
<span class="cart-price cart-column" data-price="{{item.product.price}}" >£{{item.product.price}}</span>
<div class="cart-quantity cart-column">
<div class="quantity">
<button data-id={{item.product.id}} data-action="reduce" id="minus" class="btn minus1 update-cart" >-</button>
<input class="cart-quantity-input quantity" type="number" id="id_form-0-quantity" name="quantity" min="1" max="5" value="{{item.quantity}}">
<button data-id={{item.product.id}} data-action="add" id="plus" class="btn add1 update-cart" >+</button>
<button data-id={{item.product.id}} data-action="remove" class="removeButton" type="button">REMOVE</button>
</div>
</div>
</div>
{% endfor %}
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price">£{{order.get_cart_total}}</span>
</div>
<div class="ordersummary">
<form action="checkout-info" method="post">
{% csrf_token %}
<input type="submit" value="CHECKOUT">
</form>
</div>
</div>
</div>
</div>
{% include "footer.html" %}
<script src="{% static 'js/test2.js' %}" ></script>
</body>
</html>
Assuming you want them sorted in the reverse order they were added to the cart, you can sort them by their id field:
items = order.orderitem_set.order_by('-id')

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

Spreadjs references from iframe

We use an iframe in the parent page, that is dynamically replaced with other pages.
Spread is loaded in the parent. Is there some type of plugin that will allow me to access the spread core that is loaded in the parent from the iframe pages without including spread(language="JavaScript" src="http://cdn.wijmo.com/spreadjs/gcspread.sheets.all.8.40.20151.0.min.js") in the multiple child (iframe) pages? Jquery is loaded fine.
Home page iframe with references
<iframe name="mainWindow" src="includes/View.asp frameborder="0" />
<link href="http://cdn.wijmo.com/spreadjs/gcspread.sheets.8.40.20151.0.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://cdn.wijmo.com/spreadjs/gcspread.sheets.all.8.40.20151.0.min.js"></script>
We just replace the iframe source at run time.
I use following code but spread is not initialized any suggestions ?
<script type="text/javascript">
var parentWindow = window.parent;// This refers to parent's window object
if (parentWindow && parentWindow.jQuery) { // Check to see if parentWindow and parentWindow.jQuery is truly
window.jQuery = parentWindow.jQuery;
window.$ = parentWindow.jQuery;
}
else {
var jScript = document.createElement('script');
jScript.setAttribute("type", "text/javascript");
jScript.setAttribute("src", "http://code.jquery.com/jquery-1.8.2.min.js"); // load jQuery here
}
if (parentWindow && parentWindow.wijmo && parentWindow.GcSpread) { // Check to see if parentWindow and parentWindow.wijmo and parentWindow.GcSpread is truly
window.GcSpread = parentWindow.GcSpread;
window.wijmo = parentWindow.wijmo;
}
else {
var jScript = document.createElement('script');
jScript.setAttribute("type", "text/javascript");
jScript.setAttribute("src", "http://cdn.wijmo.com/spreadjs/gcspread.sheets.all.8.40.20151.0.min.js"); // load gcspread here
}
$(document).ready(function () {
var test = window;
alert("JQuery loaded");
var spread = new GcSpread.Sheets.Spread(document.getElementById("ss"));
var spreadNS = GcSpread.Sheets;
spread.setSheetCount(3);
spread.bind(spreadNS.Events.ActiveSheetChanged, function (e, args) {
$("#activeSheetIndex").val(spread.getActiveSheetIndex());
});
$("#btnAddSheet").click(function () {
spread.addSheet(spread.getSheetCount());
});
$("#btnRemoveSheet").click(function () {
var activeIndex = spread.getActiveSheetIndex();
if (activeIndex >= 0) {
spread.removeSheet(activeIndex);
}
});
$("#btnClearSheets").click(function () {
spread.clearSheets();
});
$("#btnSetActiveSheetIndex").click(function () {
var index = $("#activeSheetIndex").val();
if (!isNaN(index)) {
index = parseInt(index);
if (0 <= index && index < spread.getSheetCount()) {
spread.setActiveSheetIndex(index);
}
}
});
});
</script>
<div class="sample-turtorial">
<div id="ss" style="width:100%; height:580px;border: 1px solid gray;"></div>
<div class="demo-options">
<div class="option-row">
<input type="button" style="width: 100px" value="Add Sheet" id="btnAddSheet" />
<input type="button" style="width: 100px" value="Remove Sheet" id="btnRemoveSheet" />
<input type="button" style="width: 100px" value="Clear Sheets" id="btnClearSheets" />
</div>
<div class="option-row">
<label>ActiveSheetIndex:</label>
<input type="text" id="activeSheetIndex" value="0" />
<input type="button" id="btnSetActiveSheetIndex" value="Set" />
</div>
</div>
</div>
I don't think what you're attempting work, how would the code execute without having a reference to the library (SpreadJS).
Can you please explain what your use case might be, may be we can help you find a different way of accomplishing what you need.

Input not being displayed

I have an input field. When the user clicks it some javascript converts the text to a Raphael JS library variable. I want to put each letter into a Raphael variable called string followed by a \n. When the user clicks on the button nothing is displayed. Can someone help me fix this?...
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
var string = "";
function animate() {
var txt = document.getElementById("words").value;
var splittxt = txt.split("");
var i;
for (i = 0; i < splittxt.length; i++) {
var string = splittxt[i] + "\n\n";
}
}
</script>
<style type="text/css">
#letters
{
text-align:center;
margin-left:10px;
width:25px;
float:left;
text-shadow:10px 5px 1px #4D4D4D;
filter:DropShadow(Color=#4D4D4D, OffX=10, OffY=5);
font-weight:bold;
}
</style>
</head>
<body>
Text: <input type="text" id="words" />
<input type="button" value="Animate" onclick="animate()" />
<div id='letters'></div>
<div id="draw-here-raphael" style="height: 200px; width: 400px; margin-top:0px; background-color:blue;">
</div>
<div id="elps" style="ma
rgin-left:100px;"/>
<script type="text/javascript"> //all your javascript goes here
var r = new Raphael("draw-here-raphael");
var string = r.text(50,50, string);
</script>
</body>
</html>
Instead of setting the variable string, you want add to it. Also, there were quite a few other updates I made to your excerpt...
Setting variables to reserved words can also cause a lot of problems.
http://jsfiddle.net/fN9Me/
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
var alpha = "";
var something = "";
var r = "";
var txt = "";
var splittxt = "";
$(function() {
r = new Raphael("draw-here-raphael");
$("#animate").click(function() {
txt = $("#words").val();
splittxt = txt.split("");
var i;
for (i = 0; i < splittxt.length; i++) {
something += splittxt[i] + "\n\n";
}
alpha = r.text(50, 50, something);
});
});
</script>
<style type="text/css">
#letters
{
text-align:center;
margin-left:10px;
width:25px;
float:left;
text-shadow:10px 5px 1px #4D4D4D;
filter:DropShadow(Color=#4D4D4D, OffX=10, OffY=5);
font-weight:bold;
}
</style>
</head>
<body>
Text: <input type="text" id="words" value="" />
<input id="animate" type="button" value="Animate" />
<div id='letters'></div>
<div id="draw-here-raphael" style="height: 200px; width: 400px; margin-top:0px; background-color:blue;">
</div>
<div id="elps" style="margin-left:100px;"/>
</body>
</html>
Update:
To remove the previous text, it is just a matter of utilizing the Raphael remove function. Also we have to reset the variable something
if (alpha) alpha.remove();
http://jsfiddle.net/fN9Me/1/
You're not actually displaying anything. This line:
document.getElementById("letters").innerHTML + splittxt[i] + "<br>";
needs to be something like:
document.getElementById("letters").innerHTML += splittxt[i] + "<br>";
The value of the words input is blank => when you call the split method var splittxt = txt.split(""); the splittxt has a length == 0, and therefore the body of the for statement is never executed.