I have a flask app that has a bunch of checkboxes, some of the pre-checked. I would like to have a button that checks/unchecks all the checkboxes.
I realized that I should do it with a javascript function, so I created a file script.js in the static folder and put these functions in it:
$("#check-all").click(function(){
$("input[type='checkbox']").prop('checked',false);
});
$("#uncheck-all").click(function(){
$("input[type='checkbox']").prop('checked',true);
})
This is the html page:
<script type="text/javascript" src="{{ url_for('static', filename = 'script.js') }}"></script>
<div class="row" style="border:solid ; background-color:lightgray">
<form method="POST" , action="{{ url_for('submitting') }}">
<div class="col-md-6">
<br>Please select detached object(s):<br>
{% for o in data.objects %}
<h4><input type="checkbox" name="word_objs" value="{{ o }}"> {{ o }} <br></h4>
{% endfor %}
<input type="button" id="uncheck-all" value="UncheckAll"/>
<input type="button" id="check-all" value="CheckAll"/><br>
</div>
</form>
{% endblock %}
</div>
But unfortunately, none of them work. I would appreciate it if anyone helps me with it.
Related
I'm trying to prevent/allow the user from clicking a button depending on whether a key is present in the request.session data.
It works for blocking it, but once the key is added to the session, that isn't reflected on the webpage/template and the key remains blocked. I presume I'll have to do this in JS but I'm not sure how to approach it. Any ideas?
Thanks
{% if choices not in request.session %}
<form class="submit-form" action="{% url 'search' %}" method="post" onsubmit="return false;">
{% csrf_token %}
<input type="submit" class="show-more-button cunt" style="margin-left: 5px" name="mybtn"
value="Search" data-bs-toggle="popover"
data-bs-placement="right" data-bs-trigger="focus"
data-bs-content="Please select one or more ingredient">
</form>
{% else %}
<form action="{% url 'search' %}" method="post">
{% csrf_token %}
<input type="submit" class="show-more-button" style="margin-left: 5px" name="mybtn"
value="Search">
</form>
{% endif %}
if request.POST.get('button_color') == 'green':
selected_ingredients = request.session.get('choices', [])
selected_ingredients.insert(len(selected_ingredients), ingredients_name)
request.session['choices'] = selected_ingredients
request.session.modified = True
I'm working on a quiz app and want to generate a number of input fields representing the answers based on the value that the user types.
I'm using a button named "create" to do that Using JavaScript, but when clicking the button it submits the form.
Please Check the two images below.
Input
Output
HTML Code
{% load static %}
{% block body %}
<button class="btn btn-primary new">Add a question</button>
<form class="question" method="POST" style="display: none">
{% csrf_token %}
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" class="form-control" id="title" placeholder="Question title">
</div>
<div class="form-group" id="answers_num">
<label for="exampleInputPassword1">Number of answers</label>
<input type="number" class="form-control" id="ans_number">
<button class="create_answers">Create</button>
</div>
<div class="form-group">
{% comment %} Generated input fields {% endcomment %}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% block script %}
<script src="{% static 'mcq/index.js' %}"></script>
{% endblock %}
{% endblock %}```
JS code
document.querySelector(".new").addEventListener("click", ()=> {
document.querySelector(".question").style.display = 'block';
document.querySelector("#create_answers").addEventListener("click", ()=> {
answers = this.value;
console.log(answers);
// Create input fields
for (let i = 0; i < answers; i++) {
input = document.createElement("input");
input.classList.add('form-control');
answersDiv = document.querySelector("#answers").appendChild(input);
}
})
})```
You need to explicitly set the type of the button, like
<button class="create_answers" type="button">Create</button>
in order to avoid submitting the form upon click.
Based on the following image, I am trying to make the fields category and current points non-editable when the status of the task is Finalized or Cancelled, otherwise the fields should be editable.
Below is the code from my html file.
{% extends "base.html" %} {% load widget_tweaks %}
{% block content %}
<div id="form-group">
<form method="POST" action="." enctype="multipart/form-data">
{% csrf_token %}
<label>Select your category</label>
{{ form.category|add_class:"card" }}
<label>What's the status of the task?</label>
{{ form.status|add_class:"card" }}
<label>Current points:</label>
{{ form.points|add_class:"card" }}
<label>Finalized date:</label>
{{ form.ending_date|add_class:"card" }}
<button type="submit" class="btn btn-success">Send</button>
</form>
</div>
Below is the code from my forms.py file.
class TaskModelForm(forms.ModelForm):
class Meta:
model= Task
fields = ['category', 'status', 'points']
def __init__(self, *args, **kwargs):
super(TaskModelForm, self).__init__(*args, **kwargs)
self.fields['status'].required = False
self.fields['points'].required = False
When I want to edit the contents of this form I need to verify if the status is Finalized, so the fields are non-editable, otherwise the fields should be editable and I am thinking something about:
{% extends "base.html" %} {% load widget_tweaks %}
{% block content %}
{% if form.status.value == 'Active' %} <!--make the fields editable -->
<div id="form-group">
<form method="POST" action="." enctype="multipart/form-data">
{% csrf_token %}
<label>Select your category</label>
{{ form.category|add_class:"card" }}
...
<button type="submit" class="btn btn-success">Send</button>
</form>
</div>
{% endif %}
{% if form.status.value == 'Finalized' %} <!--make the fields non-editable -->
<div id="form-group">
<form method="POST" action="." enctype="multipart/form-data">
{% csrf_token %}
<label>Select your category</label>
{{ form.category|add_class:"card" }}
...
<button type="submit" class="btn btn-success">Send</button>
</form>
</div>
{% endif %}
However, I believe my approach might not work because this could be a more front-end problem rather than back-end one (just a guess). Can you point me out to the right direction to solve this problem?
Since the status is something that the user selects, you can't address your requirement with Python (Django) running on the server. You have to address it with a JavaScript running in the web page that displays the form. Something like this will definitely do the trick.
{% extends "base.html" %} {% load widget_tweaks %}
{% block content %}
<body onload="makeReadOnly();">
<div id="form-group">
<form method="POST" action="." enctype="multipart/form-data">
{% csrf_token %}
<div class="tweet-composer">
<label>Insert your task</label>
{{ form.task|add_class:"card js-keeper-editor" }}
</div>
<label>Select your category</label>
{{ form.category|add_class:"card" }}
<label>Current points:</label>
{{ form.points|add_class:"card" }}
<button type="submit" class="btn btn-success">Send</button>
</form>
</div>
</body>
{% endblock content %}
<script type="text/javascript">
{% block jquery %}
function makeReadOnly()
{
if (document.getElementById('id_status').value == 'Finalized'){
document.getElementById('id_task').readOnly=true;
document.getElementById('id_category').readOnly=true;
}else if (document.getElementById('id_status').value == 'Active'){
document.getElementById('id_task').readOnly=true;
document.getElementById('id_category').readOnly=false;
}
}
document.getElementById('id_status').addEventListener('change', makeReadOnly);
{% endblock %}
</script>
With the "view page source" you can see the HTML structure that Django generates out of your form, so that you can identify the right bits with JQuery selectors. Alternatively you can do
f = SomethingForm()
f.as_p()
in the ./manage.py shell console.
At the Django end, you may need custom form validation to handle the inter-dependency between the value of status and whether the other fields are required or not.
Currently I'm trying to get Shopify's cart.js to add my products to cart.
It used to work perfectly but when I added variants it's started to break and for the life of me I can't get it to work. When clicking the button - it doesn't add the product to the bag at all.
<form action="/cart/add" method="post" data-cart-submit>
{% if product.variants.size > 1 %}
<div class="w-form">
<div class="inpost-form-option w-clearfix">
<label class="inpost-form-label">{{ product.options.first }}</label>
<select id="variant-select" class="inpost-quantity w-select">
{% for variant in product.variants %}
{% if variant.available == true %}
<option value="{{ variant.id }}">{{ variant.title }}</option>
{% endif %}
{% endfor %}
</select>
</div>
</div>
{% endif %}
<button class="inpost-buy w-button" type="submit" data-cart-add="{{ variant.id }}">Add to Bag →</button>
</form>
Added Javascript
<script type="text/javascript">
jQuery(function() {
CartJS.init({{ cart | json }});
});
</script>
Console Error
shop_events_listener-91b4691….js:1 POST
https://monah-uk.myshopify.com/cart/add.js 404 (Not Found)
When I try to use the below code with jfiddle, I comment out the jinja and the buttons hide as expected, but in the browser, the input buttons don't hide
{% extends "layout.html" %}
{% block body %}
<div>
{% if session.logged_in %}
<form action="{{ url_for('add_entry') }}" method=post class=add-entry>
<dl>
<dt>Stock Ticker:
<dd><input type=text size=30 name=stockname>
<dt>Date:
<dd><input id="datePicker" type="date" name='start_date'>
<dd><input type=submit value=Add>
</dl>
</form>
{% endif %}
</div>
<div>
<form action="{{ url_for('edit_entry') }}" method=post class=edit-entry>
<table class="entries">
<tr>
<th>stock ticker</th>
<th>date bought</th>
<th> Edit</th>
</tr>
{% for entry in entries %}
<tr>
<td><h2>{{ entry.stockname }}</h2></td>
<td>{{ entry.start_date|safe }}</td>
<td>
<input type="hidden" name="name" value="Edit"/>
<input class="show" type="button" id="edit-button" value="Edit"/>
<input class="hide" type="button" id="cancel-button" value="Cancel Changes"/>
<input class="hide" type="submit" id="save-button" value="Save Changes"/>
</td>
</tr>
{% else %}
<em>Unbelievable. No entries here so far</em>
{% endfor %}
</table>
</form>
</div>
{% endblock %}
<script>
$(document).ready( function() {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
$('#datePicker').val(today);
$(".hide").hide();
});
</script>
and layout.html consists of...
<!doctype html>
<title>Flaskr</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
<h1>Flaskr</h1>
<div class=metanav>
{% if not session.logged_in %}
log in
{% else %}
log out
{% endif %}
</div>
{% for message in get_flashed_messages() %}
<div class=flash>{{ message }}</div>
{% endfor %}
{% block body %}{% endblock %}
</div>
Fiddle: http://jsfiddle.net/5ZNTf/
You are defining lots of
<input type="submit" id="save-button" value="Save Changes"/>
in your for loop, so you have multiple input tags with the same id on the page, thus it does not work. Try giving the inputs a class instead.
Use class instead of id for your input elements.
<input type="hidden" class="name" value="Edit"/>
<input type="button" class="edit-button" value="Edit"/>
<input type="button" class="hide" value="Cancel Changes"/>
<input type="submit" class="hide" value="Save Changes"/>
Change the selector to use class.
$("input[class=hide]").hide();
Try this: http://jsfiddle.net/5ZNTf/1/
Id's need t be unique. If you would like to hide multiple elements with the same name use a class.
<button class="hide">Cancel</button>
<button class="hide">Save</button>
Then add a css class to hide them. It's more reliable IMO.
.hide {
display: none;
}
The issue had to do with localhost not property reading in jquery -_-
"//url" instead of "http://" or "https://" only works remotely