I can't seem to understand why I can't spam click my "create board" button and keep creating boards
when I add a board the new empty board dict should be prepended to the front of the array but only one board will show up then no more..Thanks for the help!!!
<div id="target"></div>
<script id="template" type="text/ractive">
<button class="btn btn-primary" on-click="add_board"><i class="fa fa-plus"></i> Board</button>
<br><br>
editing: {% editing %}
{% #board_list:title %}
{% title %}
{% /board_list %}
<div class="board_list">
{% #board_list:name %}
<div class="board">
{% #if editing %}
<textarea id="editarea" on-blur="editdone" data-areaid="3" value="{% text %}"></textarea>
{% else %}
<div on-click="startedit"><p>{% text %}</p></div>
{% /if %}
</div>
{% /board_list %}
</div>
</script>
<script src='http://cdn.ractivejs.org/latest/ractive.min.js'></script>
<script>
$(function() {
// Ractive object
var MAIN = new Ractive({
el: '#target',
template: '#template',
delimiters: ['{%', '%}'],
tripleDelimiters: ['{%%', '%%}'],
data: {
editing: false,
board_id: -1,
text: "Edit Me",
board_list: [],
loading: false
},
});
MAIN.on("add_board", function() {
board_list = MAIN.get('board_list');
alert(board_list);
var empty_board = {title: ''};
board_list.splice(0, 1, empty_board);
MAIN.set('board_list', board_list);
});
MAIN.on("startedit", function() {
MAIN.set("editing", true);
$("#editarea").focus();
});
MAIN.on("editdone", function() {
MAIN.set("editing", false);
var text = MAIN.get("text");
alert(text);
if (text.trim().length > 0) {
//update_board()
alert('not empty');
}
else {
//delete_board()
alert('empty');
}
});
The second argument in splice is the number of elements to remove, you currently have it set to remove 1. If you change it to 0 then it will add more.
board_list.splice(0, 0, empty_board);
https://jsfiddle.net/6qz84476/
Related
I am trying to implement a drag and drop using FullCalendar.js.
I saw in documentation to enable option editable to true for moving event but this don't work.
On the render, you can see my task, i just want to move my task to monday (for exemple).
Do you have suggestion for where error come from ?
Or an issue ?
Thanks !
this is my code
{% extends 'base.html.twig' %}
{% block title %}Calendrier{% endblock %}
{% block body %}
<div>
<a class="btn btn-secondary" href="{{ path('home') }}">
<i class="fas fa-long-arrow-alt-left"></i> Retour</a>
</div>
<div class="row mt-5">
{% if is_granted("ROLE_MANAGER") %}
<div class="col d-flex my-3 justify-content-end">
{{ form_start (form, {'attr': {'class': 'd-flex'}}) }}
{{ form_widget(form.technicien, {'attr': {'class': 'd-inline me-2'}}) }}
{{ form_widget(form.techniciens, {'attr': {'class': 'd-none'}}) }}
<input id="submitBtn" class="btn btn-success d-inline" type="submit" value="Filtrer">
{{ form_end(form) }}
</div>
{% endif %}
<div class="col-12">
<div id="calendar" class="d-flex justify-content-center">
<div class="spinner-border" role="status">
<span class="sr-only">Loading...</span>
</div>
</div>
</div>
</div>
</div>
{{ include('loading_spinner.html.twig') }}
<script>
var mainRole = '{{mainRole}}';
if(mainRole == 'MANAGER') {
var idTechniciens = '{{partnerTechniciens}}';
var idTechniensArray = idTechniciens.split(' ');
var technicienSelect = $('#ticket_intervention_user_technicien');
var options = $('#ticket_intervention_user_technicien option');
var optionsToHide = $.map(options ,function(option) {
var extra = new Array();
if(!idTechniensArray.includes(option.value)) {
extra.push(option);
}
return extra;
});
optionsToHide.forEach(function(option) {
option.style.display = 'none'; });
}
</script>
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script src='fullcalendar/main.js'></script>
<script>
window.onload = () => {
calendar('#calendar', {
'events': {{ data|raw }},
'enventStartEditable': true,
'editable': true,
//'eventResizableFromStart': true,
'nowIndicator': true,
eventDidMount: function(info) {
let tooltip = new bootstrap.Tooltip(info.el, {
title: ('Client : ' + info.event.extendedProps.description),
placement: 'top',
trigger: 'hover',
container: 'body'
});
}
});
}
</script>
{% endblock %}
This is the render of my calendar:
in my app.js :
import { calendar } from "./full-calendar";
global.calendar = calendar;
How can i do it ?
ok i change the render with the documentation and it's work
window.onload = () => {
let calendarElt = document.querySelector("#calendar")
let calendar = new FullCalendar.Calendar(calendarElt, {
initialView: 'timeGridWeek',
locale: 'fr',
timeZone: 'Europe/Paris',
headerToolbar: {
start: 'prev,next today',
center: 'title',
end: 'dayGridMonth,timeGridWeek'
},
events: {{ data|raw }},
editable: true,
nowIndicator: true,
eventResizableFromStart: true,
eventDidMount: function(info) {
let tooltip = new bootstrap.Tooltip(info.el, {
//title: ('Client : ' + info.event.extendedProps.description),
placement: 'top',
trigger: 'hover',
container: 'body'
});
}
})
I am very new to javascript. I was working on a Django project. In the project, multiple forms are created by Django. I used event listener to all of the forms. Here is my javascript code:
document.addEventListener("DOMContentLoaded",function(){
document.querySelectorAll(`#likeform${posts_id}`).forEach(e =>{
e.addEventListener('submit',(event) => {
event.preventDefault();
like_function();
// return false;
});
});
})
function like_function(){
fetch(`/like/${posts_id}`,{
method:"POST",
body : JSON.stringify({
"is_like" : is_like,
"num_like" : num_like,
})
})
.then(response => response.json())
.then(result => {
if(result.is_like){
console.log("function is liked");
console.log(`${result.is_like} for post ${posts_id}`);
let num_like = result.num_like;
console.log(`Number of posts : ${num_like}`);
document.querySelector(`#likebtn${posts_id}`).innerHTML = "Unlike";
num_like = num_like + 1;
console.log(`Number of posts : ${num_like}`);
document.querySelector(`#num_of_likes_${posts_id}`).innerHTML = `${num_like} `
// location.replace("http://127.0.0.1:8000")
}
else{
console.log("function is unliked, back off!");
console.log(`${result.is_like} for post ${posts_id}`);
let num_like = result.num_like;
console.log(`Number of posts : ${num_like}`);
document.querySelector(`#likebtn${posts_id}`).innerHTML = "Like";
num_like = num_like - 1;
console.log(`Number of posts : ${num_like}`);
document.querySelector(`#num_of_likes_${posts_id}`).innerHTML = `${num_like} `
// location.replace("http://127.0.0.1:8000")
}
})
}
I used querySelectorAll so that all forms work nicely. Unfortunately, only one form works. What goes wrong here?
As everyone is asking where I've defined posts_id in the comments, I'm editing my question and sharing my templates.html file.
templates.html
{% load static %}
<div id="likeapost{{posts.id}}" class="card-footer">
{% if request.user in posts.likepost.all %}
<form action="{% url 'likepost' posts_id=posts.id %}" id="likeform{{posts.id}}" method="POST" style="display: inline;">
<!-- {% csrf_token %} -->
<button id="likebtn{{posts.id}}" class="btn btn-link" type="submit">Unlike</button>
</form>
{% else %}
<form action="{% url 'likepost' posts_id=posts.id %}" id="likeform{{posts.id}}" method="POST" style="display: inline;">
<!-- {% csrf_token %} -->
<button id="likebtn{{posts.id}}" class="btn btn-link" type="submit">Like</button>
</form>
{% endif %}
<small id="num_of_likes_{{posts.id}}" class="num_of_likes">{{ posts.likepost.all.count }}</small>
{% block script %}
<script>
posts_id = "{{ posts.id }}";
is_like = "{{is_like}}";
num_like = "{{ posts.likepost.all.count }}";
</script>
<script src="{% static 'network/controller.js' %}"></script>
{% endblock %}
<button class="btn btn-link" style="text-decoration: none;">Comment</button>
View Post
{% if request.user.id is posts.user.id %}
Edit
{% endif %}
<!-- <div class="likepost"></div> -->
</div>
If I need to share more pieces of code please tell me.
If you want to get all the elements with an id that starts with something, use the following :
document.querySelectorAll('[id^="likeform"]').forEach((e=>{ // ...
My Django application makes divs dynamically. Each div is a post of a blog post and also I have a like button on each div. Each button will automatically turn into unlike when a user clicks on it without reloading using javascript. I wrote a javascript function for this. Unfortunately, my javascript function works only the last post on a page (As I have pagination property).
document.addEventListener("DOMContentLoaded",function(){
// const colon = document.createElement('div');
// colon.setAttribute('id','colon')
// e.preventDefault()
// const likebtn = document.createElement('button');
// likebtn.setAttribute('class','likebtn btn btn-primary');
// likebtn.setAttribute('class','likebtn');
// document.querySelector('.card-footer').appendChild(likebtn);
// document.querySelector('.likebtn').innerHTML = "Like";
document.querySelector(`#likeform${posts_id}`).addEventListener('submit',(event) => {
event.preventDefault();
like_function();
// return false;
})
// document.querySelector('.likepost').addEventListener('click', ()=> like_function('likepost'));
})
// let is_like = "{{is_like}}";
// let num_like = "{{num_like}}";
function like_function(){
// document.createElement('button').innerHTML = "Love";
// console.log("Updated!")
fetch(`/like/${posts_id}`,{
method:"POST",
body : JSON.stringify({
"is_like" : is_like,
"num_like" : num_like,
})
})
.then(response => response.json())
.then(result => {
if(result.is_like){
console.log("function is liked");
console.log(`${result.is_like} for post ${posts_id}`);
let num_like = result.num_like;
console.log(`Number of posts : ${num_like}`);
document.querySelector(`#likebtn${posts_id}`).innerHTML = "Unlike";
num_like = num_like + 1;
console.log(`Number of posts : ${num_like}`);
document.querySelector(`#num_of_likes_${posts_id}`).innerHTML = `${num_like} `
// location.replace("http://127.0.0.1:8000")
}
else{
console.log("function is unliked, back off!");
console.log(`${result.is_like} for post ${posts_id}`);
let num_like = result.num_like;
console.log(`Number of posts : ${num_like}`);
document.querySelector(`#likebtn${posts_id}`).innerHTML = "Like";
num_like = num_like - 1;
console.log(`Number of posts : ${num_like}`);
document.querySelector(`#num_of_likes_${posts_id}`).innerHTML = `${num_like} `
// location.replace("http://127.0.0.1:8000")
}
})
}
// function like_function(){
// if (document.querySelector("#like").style.color == "blue"){
// document.querySelector("#like").style.color = "red";
// }else{
// document.querySelector("#like").style.color = "blue";
// }
// }
This is my full javascript code. Here I'm sharing my HTML template,
<div id="posts" class="card">
<ul class="card-body">
{% for posts in page_view %}
<li class="card">
<div class="card-header bg-success">
<h5 class="card-title"><a class="text-light" style="text-decoration: none;" href="{% url 'profile' posts.user.id %}">{{ posts.user }}</a></h5>
<h6 class="card-subtitle text-light">{{ posts.timestamp }}</h6>
</div>
<div class="card-body">
<h3 class="card-text">{{ posts.post }}</h3>
</div>
<div id="likeapost{{posts.id}}" class="card-footer">
{% if request.user in posts.likepost.all %}
<form action="{% url 'likepost' posts_id=posts.id %}" id="likeform{{posts.id}}" method="POST" style="display: inline;">
<!-- {% csrf_token %} -->
<button id="likebtn{{posts.id}}" class="btn btn-link" type="submit">Unlike</button>
</form>
{% else %}
<form action="{% url 'likepost' posts_id=posts.id %}" id="likeform{{posts.id}}" method="POST" style="display: inline;">
<!-- {% csrf_token %} -->
<button id="likebtn{{posts.id}}" class="btn btn-link" type="submit">Like</button>
</form>
{% endif %}
<small id="num_of_likes_{{posts.id}}" class="num_of_likes">{{ posts.likepost.all.count }}</small>
{% block script %}
<script>
posts_id = "{{ posts.id }}";
is_like = "{{is_like}}";
num_like = "{{ posts.likepost.all.count }}";
</script>
<script src="{% static 'network/controller.js' %}"></script>
{% endblock %}
<button class="btn btn-link" style="text-decoration: none;">Comment</button>
View Post
{% if request.user.id is posts.user.id %}
Edit
{% endif %}
<!-- <div class="likepost"></div> -->
</div>
</li>
{% empty %}
<h6>No post availabel 😔</h6>
{% endfor %}
</ul>
</div>
This is my HTML template. All the buttons should work like this,
Only this one button works perfectly, but others do not. This is what happening.
What should I do? I am about 90% done. Please help.
This question already has answers here:
onclick multiple elements in vue js
(2 answers)
Closed 1 year ago.
I would like to change text and image when I click on a button, I had tried this but I get stuck and I don't know how to use it to change multiple elements,
{% for variant in product.variants %}
<label for="variant_{{- variant.id }}">{{ variant.title }} - <img src="{{ variant.image | img_url: '100x100' }}" v-on:click="changeMessage('{{ variant.price | money_with_currency }}')"></label>
<input type="radio" {% if forloop.first %}checked{% endif %} class="variant_id" id="variant_{{- variant.id }}" name="productVariants" value="{{ variant.id }}"/>
<div class="variant_price d-none">{{ variant.price | money_with_currency }}</div>
<div class="variant_sku d-none">{{ variant.sku }}</div>
<div class="variant_img d-none">{{ variant.image | img_url: master }}</div>
{% endfor %}
{% raw %}{{ price }}{% endraw %}
{% raw %}{{ image }}{% endraw %}
Current look on the store
The price is now showing by default I have to click the radio button to show the price, I want it to be shown by default,
This is how it looks like after I click on the radio button
export default {
data () {
return {
price: document.getElementsByClassName('variant_price').innerHTML,
sku: document.getElementsByClassName('variant_sku').innerHTML,
img: document.getElementsByClassName('variant_img').innerHTML,
}
},
methods: {
changeMessage(message) {
this.message = message
}
},
}
I want when I click on the radio button it gives me the price and image, my skills on JS is so bad, please I need help 🙏🙏🙏
Try to use mounted() hook to set your defaults.
export default {
data () {
return {
price: document.getElementsByClassName('variant_price').innerHTML,
sku: document.getElementsByClassName('variant_sku').innerHTML,
img: document.getElementsByClassName('variant_img').innerHTML,
}
},
mounted(){
//set default here, like this
this.changeMessage(message);
}
methods: {
changeMessage(message) {
this.message = message
}
},
}
Also, could you elaborate it a little bit more so that I can help you in this regard
In order to change another element using v-on:click on a button you should add to these elements a parameter ref="nameOfRef" and then select them in the method you called on the v-on:click like: this.$refs.nameOfRef
Example:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<main id="vue-app">
<div ref="div">Hello world</div>
<button type="button" v-on:click="hideElements()">Hide!</button>
<button type="button" v-on:click="showElements()">Show!</button>
</main>
<script>
var app = new Vue({
el: "#vue-app",
methods: {
hideElements: function () {
this.$refs.div.style.display = "none";
},
showElements: function () {
this.$refs.div.style.display = "inherit";
}
}
});
</script>
I adapted a IAT (Implicit Association Task), I used this for an experiment using computers,but now I need to implement this IAT on tablets or cellulars,
This is how the IAT looks in a celullar:
The people get stuck on this screen, because they can't use the keyboard in their celullar to press E, I or SPACE. Someone can give an idea of how to make this works.
I have the next code in the models.
class Constants(BaseConstants):
name_in_url = 'iat'
players_per_group = None
LEFT, RIGHT = iat_order.LEFT, iat_order.RIGHT
FIRST, SECOND = iat_order.LEFT, iat_order.RIGHT
num_rounds = len(default_iat_blocks.iat_block_list)
LEFT_KEYCODE = 69
LEFT_KEY_NAME = '"E" (Presione E)'
RIGHT_KEYCODE = 73
RIGHT_KEY_NAME = '"I" (Presione I)'
META_KEYCODE = 32
META_KEY_NAME = 'Barra de Espacio'
OR = " o"
And this is the code that configure the keypresses.
const is_key_valid = (keycode) => {
return keycode === left_keycode || keycode === right_keycode;
};
const mark_wrong = () => {
$(".wrong_answer_mark").show();
};
const is_correct = (pressed_side, correct_side) => {
return (pressed_side === correct_side);
};
const which_side = (keycode) => {
if (keycode === left_keycode) return side['left'];
else if (keycode === right_keycode) return side['right'];
else return undefined;
};
This is my template
% extends "global/Page.html" %}
{% load otree static %}
{% block title %}
{% endblock %}
{% block app_scripts %}
<script>
/*
All variables which take their values from django tag should be placed here
with ES5 format. I.e., use var rather than let or const.
*/
var round_number = {{ subsession.round_number }};
var iat_items = {{ iat_items|json }};
var correct_sides = {{ correct_sides|json }};
var side = {
'left': {{ Constants.LEFT }},
'right': {{ Constants.RIGHT }},
};
var left_keycode = {{ Constants.LEFT_KEYCODE }};
var right_keycode = {{ Constants.RIGHT_KEYCODE }};
var category = {
'main': {
'left': {{ left_main_category|json }},
'right': {{ right_main_category|json }},
},
'sub': {
'left': {{ left_sub_category|json }},
'right': {{ right_sub_category|json }},
}
};
var main_items = {{ main_items|json }}
var sub_items = {{ sub_items|json }}
var META_KEYCODE = {{ Constants.META_KEYCODE }}
var left_category_name = {{ left_category_name|json }};
var right_category_name = {{ right_category_name|json }};
var current_item;
</script>
<script src="{% static 'iat/lib/iat.js' %}?{{ seed_for_refresh_js_cache }}"></script>
{% endblock %}
{% block content %}
<div class="container">
{# <div class="row" id="progress"> </div>#}
<div class="row" id="mainbox">
<div class = "col-lg-6 col-md-6 col-sm-6 col-xs-6"
style="" id="left_panel">
<h2 id = "left_key">
{{ Constants.LEFT_KEY_NAME }}
</h2>
<div id = "left_category">
{% if left_main_category %}
<h1 class="keyword main">
{{ left_main_category|safe|escape }}
</h1>
{% if left_sub_category %}
<h4>o</h4>
<h1 class="keyword sub">
{{ left_sub_category|safe|escape }}
</h1>
{% endif %}
{% elif left_sub_category %}
<h1 class="keyword sub">
{{ left_sub_category|safe|escape }}
</h1>
{% endif %}
</div>
</div>
<div class = "col-lg-6 col-md-6 col-sm-6 col-xs-6" id="right_panel">
<h2 id = "right_key">
{{ Constants.RIGHT_KEY_NAME }}
</h2>
<h1 id = "right_category">
{% if right_main_category %}
<h1 class="keyword main">
{{ right_main_category|safe|escape }}
</h1>
{% if right_sub_category %}
<h4>o</h4>
<h1 class="keyword sub">
{{ right_sub_category|safe|escape }}
</h1>
{% endif %}
{% elif right_sub_category %}
<h1 class="keyword sub">
{{ right_sub_category|safe|escape }}
</h1>
{% endif %}
</h1>
</div>
</div>
<div class="row">
<div class="wrong_key_box col-lg-12 col-md-12 col-sm-12 col-xs-12">
Tipeaste la letra equivocada! <br>
En la izquierda. <span class="emph">{{ Constants.LEFT_KEY_NAME }}</span>,
En la derecha. <span class='emph'>{{ Constants.RIGHT_KEY_NAME }}</span> Presiona la tecla!
</div>
</div>
<div class="row_keyword">
<div id="keyword">
Cargando... Por favor espera.
</div>
</div>
<div class="next_block_box">
Buen trabajo oprime <span class="emph">{{ Constants.META_KEY_NAME }}</span> para continuar
</div>
</div>
<div class="wrong_answer_mark">×</div>
<form id="form">
<input type="hidden" name="category_table" id="category_table">
<input type="hidden" name="item_table" id="item_table">
<input type="hidden" name="keypress_table" id="keypress_table">
<input type="hidden" name="iat_table" id="iat_table">
</form>
{% endblock %}
Thanks in advance
What about adding a visible input field outside of the viewport ?
$('body').append("<input type='text' id='dummy'>");
$("#dummy").css({"position":"fixed","left":"120%"});
Then set a touch event as follows
$(document).on("touchstart",
() => $(document).find("#dummy").focus()
)
?
To summarize, put this
$( document ).ready(function() {
$('body').append("<input type='text' id='dummy'>");
$("#dummy").css({"position":"fixed","left":"120%"});
$(document).on("touchstart",
() => $(document).find("#dummy").focus()
)
});
here :
<script src="{% static 'iat/lib/iat.js' %}?{{ seed_for_refresh_js_cache }}"></script>
/* HERE */
{% endblock %}