Semantic Form Dropdown get value - javascript

I am using a Semantic Dropdown in one of my forms. I am adding the options using jinja2 as shown below.
<div class="ui selection dropdown">
<input type="hidden" name="set">
<i class="dropdown icon"></i>
<div class="default text">Class</div>
<div class="menu">
{% for set in sets %}
<div class="item" data-value="{{ set.id }}">{{ set.name }}</div>
{% endfor %}
</div>
</div>
I am trying to get the data-value with javascript, and this is what I am currently using:
var setID = $('.ui.dropdown').dropdown('get value');
However when I use console.log(setID) nothing is printed.
Any help would be appreciated

I found the problem: I had an if statement further down with 1 = instead of two so it overwrote setID's value.

Related

How can I re-run a Django For Loop inside a HTML Div using Javascript on Click Event

I have a HTML div like this,
<div class="coment-area ">
<ul class="we-comet">
{% for j in comment %}
<div id="delete_comment{{j.id}}" class="mt-3">
{% if j.post_id.id == i.id %}
<li >
<div class="comet-avatar">
{% if j.user_id.User_Image %}
<img class="card-img-top" style=" vertical-align: middle;width: 50px;height: 50px;border-radius: 50%;" src= {{ j.user_id.User_Image.url }} alt="">
{% else %}
<img class="card-img-top" style=" vertical-align: middle;width: 60px;height: 60px;border-radius: 50%;" src="static\images\resources\no-profile.jpg">
{% endif %}
</div>
Inside of it is a For Loop that is executed when the page is first loaded.
Below this For Loop is a Comments Button
<div >
<button type="submit" onclick="comment_save(event,{{i.id}})" class= "my-2 ml-2 px-2 py-1 btn-info active hover:bg-gray-400 rounded ">Comment</button>
</div>
</div>
</li>
</ul>
</div>
Whenever this button of Comments is clicked, a function in Javascript is called which is defined below,
function comment_save(event,post_id)
{
var comment_value=$("#comment_value"+post_id).val();
var user_id=$("#comment_user_id"+post_id).val()
postdata={
"comment_value":comment_value,
"user_id":user_id,
"post_id":post_id
}
SendDataToServer("readmore",postdata,function()
{
alert()
})
$("#comment_value"+post_id).val(" ")
<! --- document.location.reload().. Something here that refresh that for loop --->
}
What I want is this that whenever the button is clicked, it re-executes that for Loop inside my main div without having to refresh the page. I have been trying to do this for two days but could not find any solution to this. Can anyone help me in doing this?
The Django Templating Language is executed server-side. That means the client (browser, running Javascript) has no access to it whatsoever.
Some of your options are:
Do everything back-end: Re-render the template (which you said don't want to do).
Do everything front-end: You could have your view function return the data used in your template loop and re-implement it in your front-end (but that makes the original template loop kind of pointless).
Hybrid: Return the data for only the new comment in your response and add it to the list with Javascript.

my select2 jquery only work for the first form

i want to use select2.min.js to auto-complete the choices (ForeignKey values) , but it only work for my first form , i used django formset for duplicate forms
this is my snippet
<tbody class="tbody tb1 " id="form_set">
{% for item in items.forms %}
<tr class="p-0 col-12">
<td class="">
<div class="col-12 p-0 mt-3 inp">
<input class="col-12 0qarz qarz" type="number" name="" placeholder="qarz">
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.price | add_class:'col-12 '}}
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.quantity | add_class:'col-12 '}}
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.model | add_class:'col-12 0model model' | attr:'id:model'}}
</div>
</td>
</tr>
{% endfor %}
</tbody>
<script type="text/javascript">
$(function(){
$('.tb1 tr:last').formset({
prefix:'{{items.prefix}}',
addText:'add',
deleteText:'remove',
addCssClass:'btn btn-success',
});
})
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#model").select2()
})
</script>
but the select2 only work for my first form then doesnt have any effect on other forms ! and how to set number of forms to add_class it will help to solve maybe?
thanks
First of all I would love to see a little bit more, for example how you actually define your formset. It is not also clear to me what are you trying to do here. Please paste more data.
I would suggest that you think about using django-select2 module that helps a lot with handling select2 stuff in django.
I am also not sure what you mean by "how to set number of forms", maybe you wish to include some incremental counter that can be done with {{ forloop }} inside for/endfor loop?
Please paste more stuff and answer will be better.
The selector you are using to initialize select2 #model is for element ids, which should be unique for each element in the DOM.
In most browsers the effect will be that only the first instance of an element id will be recognized, and the rest ignored as if they don't exist.
In this instance you want to use a class selector: .model. This will ensure select2 is initialized for all elements that have the class "model". So the code to initialize select2 would be:
<script type="text/javascript">
$(document).ready(function(){
$(".model").select2()
})
</script>
You have to reinitialize(like this way: $("#model").select2();) the select2 for other pages when they appear.
You should need separately initialize with different ids.
for example:
<script type="text/javascript">
$(document).ready(function(){
$("#id_1").select2();
$("#id_2").select2();
})
</script>
the way I found is sending the number of forms through context then apply for loop in the template.
views.py
get_context_data()
context.update({
"accessoryNum": len(StoreRequestAccessory.objects.filter(storeRequestId=self.object.pk)),
"oneDimensionalItemNum":len(StoreRequestOneDimensionalItem.objects.filter(storeRequestId=self.object.pk)),
"twoDimensionalItemNum":len(StoreRequestTwoDimensionalItem.objects.filter(storeRequestId=self.object.pk)),
})
template.html
{% block javascripts %}
<script>
{% comment %} get accessoryNum from context {% endcomment %}
var accessoryNum = {{accessoryNum}};
$(document).ready(function(){
for(let i = 0; i <=accessoryNum; i++){
$(`#id_storereq_accessory_form-${i}-accessoryId`).select2({
placeholder: "Select a Item",
allowClear: true
});
}
});
</script>
{% endblock javascripts %}

Get attribute from a specific element of a class

Basically I have to develop a Tic-Tac-Toe game, here is the HTML file which I can't rewrite only reformat a bit, but the idea should stay the same.
{% block content %}
<nav class="navbar fixed-top navbar-light">
<button id="retry-button" class="btn btn-success">Try again?</button>
Reset settings
</nav>
<div id="game-board" class="mb-3" data-row-num="{{ row_num }}" data-col-num="{{ col_num }}" data-win-size="{{ win_size }}">
{% for row in range(row_num) %}
<div>
{% for col in range(col_num) %}
<div class="game-cell"
data-coordinate-x="{{ col }}"
data-coordinate-y="{{ row }}"></div>
{% endfor %}
</div>
{% endfor %}
</div>
{% endblock %}
As you can see i have a game-cell class which contains by default 9 elements. I would like to return the data-coordinate-x and data-coordinate-y when I click one of the game-cells. I had a previous try but if I clicked it returned all of the blocks not just the one i clicked on. I have to write it in Js. If you can point me in the right direction that's more than enough for me.
Thanks!
If I understood correctly, you need to access data attributes of your game-cell element. In order to do this, you need to select the element by some ID or class. I have modified your code a little to make it run inside stackoverflow`s platform. I have added an ID which i called "unique" and I also set some values into your coordinate-x and y data attributes. Please review the code bellow and see how I managed to get those data attributes. It's important to notice that this is not the only way to access them.
var gamecell = document.getElementById('unique');
console.log(gamecell.dataset.coordinateX);
console.log(gamecell.dataset.coordinateY);
<nav class="navbar fixed-top navbar-light">
<button id="retry-button" class="btn btn-success">Try again?</button>
Reset settings
</nav>
<div id="game-board" class="mb-3" data-row-num="{{ row_num }}" data-col-num="{{ col_num }}" data-win-size="{{ win_size }}">
<div>
<div class="game-cell" id="unique"
data-coordinate-x="172"
data-coordinate-y="273"></div>
</div>
</div>
Its also possible to get these values using the getAttribute method.
var elem = document.getElementById('unique');
var coordX = elem.getAttribute('data-coordinateX');
var coordY = elem.getAttribute('data-coordinateY');
Please, take a look at this page, it explains some aspects of data attributes:
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
Simply access your clicked game-cell by: (it will find the clicked coordinateX and coordinateY)
document.querySelectorAll('.game-cell').forEach((game) => {
game.addEventListener('click',function(event){
console.log(game.dataset.coordinateX);
console.log(game.dataset.coordinateY);
});
});
you must to get your element by class name or id(add an id)
than you can get its attributes like this
let gameCell = document.getElementById('game-cell-id');// id for example
gameCell.getAttribute('data-coordinate-x')

How do I change the value of a Django Model field via a template function based view in django

I have a django function based view, inside it a I have a checklist of checkmarks and some text, when I tap one I want the database to update, how do I accomplish this?
Note that I don't have made any efforts yet to change the value and I hope someone here can help me with that!
#login_required
def detailStudyplanPage(request,pk):
username = request.user
tks = Task.objects.filter(studyplan__id=pk)
object = get_object_or_404(Studyplan,pk=pk)
return render(request, 'detailStudyplan.html',{'object':object, 'MyName': username, 'tasks': tks})
class Checker(models.Model):
name = models.CharField(max_length=100)
checked = models.BooleanField(default=False)
sender = models.ForeignKey(UserProfile, blank=True, on_delete=models.CASCADE, related_name="person_who_checks_checker")
canview = models.ManyToManyField(UserProfile, blank=True, related_name="can_view_checker")
<div>
<div class="progress">
<div class="progress-bar bg-success" style="width:42%;"></div>
</div>
<div class="d-flex justify-content-between text-small">
<div class="d-flex align-items-center">
<i class="material-icons">playlist_add_check</i>
<span>3/7</span>
</div>
<span>Ska vara färdig {{task.deadline}}</span>
</div>
</div>
{% for checker in Checkers %}
<div class="row">
<div class="form-group col">
<span class="checklist-reorder">
<i class="material-icons">reorder</i>
</span>
<form method="post" action="{% url checker_check checker.id %}"></form>
<input type="checkbox"
{% if checker.checked == True %}
checked
{% endif %}
>
<style>
.checkerName {
margin-left: 10px
}
</style>
<h class='checkerName'>{{ checker.name }}</h>
</div>
<!--end of form group-->
</div>
{% endfor %}
You create two new views with URLs like: /checker/{id}/check and /checker/{id}/uncheck and based on the tap you do a POST to the correct URL.
The URL is linked up to a view that retrieves the check object, changes its boolean property and saves it.
In the view:
checker = Checker.objects.get(pk=pk)
checker.checked = True
checker.save()

Toggle language of labels in flask wtforms form

I have a series of wtforms written in a flask app. One of my pages in my app will be used by people speaking English and Spanish. I would like to find a clean way of toggling the form element labels between English and Spanish with a toggle button on the webpage.
I found a nice solution to toggle languages using the HTML lang attribute here (2nd answer down, by J Grover):
Using Javascript to change website language
This encloses each language in a <span> element and then simply hides the one we don't want to see.
My problem is that the labels for the fields on my forms are coming from wtforms objects. I am unsure how to include multiple languages in my current setup. See below for an example of where I am now:
Form
class RoofCheck(FlaskForm):
"""
Class holding the form inputs for a roof check
"""
roofstate = RadioField('Roof Status',
validators=[validators.DataRequired('Please select roof closed or open')],
choices=[('closed', 'Closed'), ('open', 'Open')])
comments = TextAreaField('Comments on roof status',
[validators.optional(), validators.length(max=390)],
render_kw={"placeholder": "Enter comments here",
"rows": 4,
"style": "min-width: 100%"})
submit = SubmitField('Submit')
HTML
<div id='roof_check' class='col-md-6 padding-0'>
<form id="roof_check_form" action={{ url_for('roof_check')}} method="post" name="roof">
<fieldset class='form_group'>
{{ form1.hidden_tag() }}
<legend class='text-center'>
Daily visual check of the roof
</legend>
{% for subfield in form1.roofstate %}
<div class='form-check'>
{{ subfield }}
{{ subfield.label(class_="form-check-label") }} <br/>
</div>
{% endfor %}
<div class='form-check'>
{{ form1.comments }}
</div>
<div class='form-check'>
{% with messages = get_flashed_messages(category_filter=["form1"]) %}
{% if messages %}
{% for message in messages %}
<div> {{ message }} </div>
{% endfor %}
{% endif %}
{% endwith %}
{% for message in form1.roofstate.errors %}
<div> {{ message }} </div>
{% endfor %}
<div style="padding-top: 5px;">
{{ form1.submit(class_="btn btn-primary") }}
</div>
</div>
</fieldset>
</form>
</div>
I am not sure where to begin adding multiple labels to the RoofCheck class form objects. Any advice on how to insert support for two languages here would be great. Thanks in advance.
So it turns out that I can just add html directly to the label and place the language attribute there, then use the javascript solution in the link above to toggle the language. For example:
roof_status_text = ("<span lang='en'>Roof Status</span>"
"<span lang='es'>Estado del Techo</span>")
open_text = ("<span lang='en'>Open</span>"
"<span lang='es'>Abierto</span>")
closed_text = ("<span lang='en'>Closed</span>"
"<span lang='es'>Cerrado</span>")
roofstate = RadioField(roof_status_text,
validators=[validators.DataRequired('Please select roof closed or open')],
choices=[('closed', closed_text),
('open', open_text)])

Categories

Resources