When I click the span on html I cant make variable span id with id="mylink-${i}" I couldn't get this with var mylink = document.getElementById("mylink-"+id) in javascript part.
and also at onclick="theFunction(i)" console gives me i is not defined error but it should be defined because of {% for i in data %} i is one of the elements of data how can ı solve this
<div class="row sideBar">
{% for i in data %}
<div class="row sideBar-body">
<div class="col-sm-9 col-xs-9 sideBar-main">
<div class="row">
<a href= "{% url "start_chat" i.room %}" onclick="theFunction(i)" >
<div class="col-sm-8 col-xs-8 sideBar-name">
<span class="name-meta" id="mylink-${i}"> {{i.name}}
</span>
</div>
</a>
</div>
</div>
</div>
{% endfor %}
</div>
const rooms = JSON.parse(document.getElementById('data').textContent)
function theFunction(id) {
var mylink = document.getElementById("mylink-"+id)
}
here in my code i am displaying elements from a database using a loop
at the the user click buy button, i want to pass the particular product id to another page.
how i get the product id & how it passed to another page...
HTML page
{% for product in products %}
<div class="col-md-3">
<div class="card">
<img src="{{product.product_image}}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{product.product_name}}</h5>
<p class="card-text">₹{{product.product_price}}</p>
<a href="{% url 'buy' %}" class="btn btn-primary">
Buy</a>
</div>
</div>
</div>
{% endfor %}
Passing id to path
{% for product in products %}
<div class="col-md-3">
<div class="card">
<img src="{{product.product_image}}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{product.product_name}}</h5>
<p class="card-text">₹{{product.product_price}}</p>
<a href="{% url 'buy' product.id %}" class="btn btn-primary">
Buy</a>
</div>
</div>
</div>
{% endfor %}
Problem
I want to the following things but am unable to understand that how can I do the following things.
Firstly, I want that when the page is loaded the defualt values should be displayed from using the value from the combox. For example pack of 1KG is the defualt value so it's price and other values should be updated when the page is loaded.
Secondly, I want that when the product is added to the cart the page is not reloaded or refreshed and a popup is shown that the product is added to the cart.
CODE
Script
$(document).on("change", '.tranactionID', function (event) {
event.preventDefault();
//get closest outer div..
var selector = $(this).closest(".productID")
//find to get required elements..
selector.find('.id_price').text($(this).children(":selected").attr("price"));
selector.find('.price-sale').text($(this).children(":selected").attr("sale_price"));
selector.find('.id_discount').text($(this).children(":selected").attr("discount"));
let id = $(this).find("option:selected").attr('transID');
let Url = `{% url 'cart:cart_add' 0 %}`.replace(0, id);
selector.find("form").attr('action', Url);
});
HTML
{% regroup transaction by productID as ProductList %}
{% for productID in ProductList %}
<div class="col-sm-3 productID" >
<div class="product">
<a href="{% url 'main:product-detail' productID.grouper.id %}" class="img-prod"><img class="img-fluid" src={{productID.grouper.product_image.url}} alt="" height="200px">
<span class="status id_discount">%</span>
<div class="overlay"></div>
</a>
<div class="text py-3 pb-4 px-3 text-center">
<h3>{{productID.grouper}}</h3>
<div class="d-flex">
<div class="pricing">
<p class="price"><span class="mr-2 price-dc id_price">Rs. </span><span class="price-sale">Rs. </span></p>
</div>
</div>
<select class="tranactionID" id="ItemID" style="width: 250px;">
{% for val in productID.list %}
<option transID={{val.id}} price={{val.Price}} discount={{val.discount_percentage}} sale_price={{val.get_sale}} class="price_value" >{{val.AUID}} - {{val.Description}}</option>
{% endfor %}
</select>
<form id='transactionIDValue' class="d-inline" method="post">
{{cart_product_form}}
{% csrf_token %}
<input type="submit" id="Id_submit" class="btn btn-primary shadow px-5 py-2" value="Add To Cart">
<!-- <button type="submit" class="btn btn-primary shadow px-5 py-2">Add to Cart</button> -->
</form>
</div>
</div>
</div>
{% endfor %}
I am new to programming and this is also my first question on this platform. I have tried implementing applicable solutions I could find here for similar questions raised but is still stuck. Should you believe that a previously answered question might answer mine, please share the link to such answer. Also please correct me should you find that I have broken some guidelines on how to properly ask questions on this platform.
Now, on to the actual issues.
The following are the relevant sections (please, let me know if I have missed something that might be relevant). The issues are stated on my comments on modals.js.
modals.js
$(document).ready(function(){
$('#frmAddProduct').on('submit', function aj (event) {
event.preventDefault();
$.ajax({
cache: false,
type : 'POST',
url : '/products/new',
data : $('#frmAddProduct').serialize(),
datatype: 'html'
})
.done(function process (data) {
/* The modal has to be shown unless the user clicks on 'close'*/
$('#modalAdd').modal('show');
let err = $(data).find(".invalid-feedback").html();
if (err){
/* replace the contents of the modal with section from
ajax result to show validation messages*/
let cont = $(data).find("#targetModalContent").html();
$('#targetModalContent').html(cont);
/* Once the code above executes, clicking the submit button again
terminates the whole process.
Maybe this section requires a loop or recursion? But this part
is already on the "on submit" listener, right?*/
}
else {
/* Show success flash message on the modal instead of the original
below nav location */
console.log(data);
let msg = $(data).closest("#targetFlash").html();
/* using the .find doesn't work and results in msg=undefined.
I don't understand why that is the case, I tried using .parent
but it also did not work, or maybe I was using the .parent improperly.
I also tried $($(data).closest("#targetFlash")).parent().html but
it too didn't worked.
Why is it returning only the message and not the whole node
with the enclosing div?
*/
$('#frmAddProduct fieldset>div:first').prepend(msg);
}
});
});
});
products.html
{% extends "tblayout.html" %}
<!-- Main Content -->
{% block thead %}
{% endblock %}
{% block tbody %}
{% endblock %}
{% block tfoot %}
{% endblock %}
{% block maincont %}
<!-- ModalAdd -->
<div class="modal fade" id="modalAdd" tabindex="-1" role="dialog" aria-labelledby="modalAddTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content" id="targetModalContent">
<div class="modal-header">
<h5 class="modal-title" id="modalAddLongTitle">Add {{ legend }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST" action="" id="frmAddProduct">
{{ formAdd.csrf_token }}
<div class="modal-body">
<div class="container-fluid">
<fieldset class="form-group">
<div class="form-group row">
{{ formAdd.productSubCategory.label(class="col-form-label col-sm-5") }}
{% if formAdd.productSubCategory.errors %}
{{ formAdd.productSubCategory(class="form-control col-sm-7 is-invalid") }}
<div class="invalid-feedback">
{% for error in formAdd.productSubCategory.errors %}
<span class="col-sm-7 offset-5">{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ formAdd.productSubCategory(class="form-control col-sm-7") }}
{% endif %}
</div>
<div class="form-group row">
{{ formAdd.brand.label(class="col-form-label col-sm-5") }}
{% if formAdd.brand.errors %}
{{ formAdd.brand(class="form-control col-sm-7 is-invalid") }}
<div class="invalid-feedback">
{% for error in formAdd.brand.errors %}
<span class="col-sm-7 offset-5">{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ formAdd.brand(class="form-control col-sm-7") }}
{% endif %}
</div>
<div class="form-group row">
{{ formAdd.description.label(class="col-form-label col-sm-5") }}
{% if formAdd.description.errors %}
{{ formAdd.description(class="form-control col-sm-7 is-invalid") }}
<div class="invalid-feedback">
{% for error in formAdd.description.errors %}
<span class="col-sm-7 offset-5">{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ formAdd.description(class="form-control col-sm-7") }}
{% endif %}
</div>
</fieldset>
</div>
</div>
<div class="modal-footer">
<div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
<div>
{{ formAdd.submit(class="btn btn-primary") }}
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
<!-- Optional Body scipt loaded after the main content has loaded -->
{% block bodyscript %}
<script src="../static/js/modals.js"></script>
{% endblock %}
AJAX result on Issue #1
<!-- ModalAdd -->
<div class="modal fade" id="modalAdd" tabindex="-1" role="dialog" aria-labelledby="modalAddTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content" id="targetModalContent">
<div class="modal-header">
<h5 class="modal-title" id="modalAddLongTitle">Add Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST" action="" id="frmAddProduct">
<input id="csrf_token" name="csrf_token" type="hidden" value="ImNlZDc1Njc0MTY4NTg5NTNhNDg0NWEyNGYyZjYzZmIyYmFmMTZhZmQi.YAamUA.WGi03w__AklqccdIQgK_pWG5oJg">
<div class="modal-body">
<div class="container-fluid">
<fieldset class="form-group">
<div class="form-group row">
<label class="col-form-label col-sm-5" for="productSubCategory">Product Sub-Category</label>
<select class="form-control col-sm-7 is-invalid" id="productSubCategory" name="productSubCategory" required><option selected value="1">ProductCategory1, ProductSubCategory1</option><option value="2">ProductCategory1, ProductSubCategory2</option><option value="3">ProductCategory2, ProductSubCategory3</option></select>
<div class="invalid-feedback">
<span class="col-sm-7 offset-5">Product combination is already enrolled.</span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-5" for="brand">Brand</label>
<select class="form-control col-sm-7 is-invalid" id="brand" name="brand" required><option selected value="1">Brand1</option><option value="2">Brand2</option><option value="3">Brand3</option></select>
<div class="invalid-feedback">
<span class="col-sm-7 offset-5">Product combination is already enrolled.</span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-5" for="description">Product Description</label>
<input class="form-control col-sm-7 is-invalid" id="description" name="description" placeholder="New Product" required type="text" value="45">
<div class="invalid-feedback">
<span class="col-sm-7 offset-5">Product combination is already enrolled.</span>
</div>
</div>
</fieldset>
</div>
</div>
<div class="modal-footer">
<div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
<div>
<input class="btn btn-primary" id="submit" name="submit" type="submit" value="Add Product">
</div>
</div>
</form>
</div>
</div>
</div>
AJAX result on Issue #2 (I have copied only the target div since the rest of the html data is just the same, this is right below the nav)
<div class="alert alert-success" id="targetFlash">
Product 45 has been added!
</div>
main.routes.py
#main.route("/products", methods=['GET', 'POST'])
#login_required
def products():
formAdd = frmAddProduct()
formMod = frmModProduct()
q = sess.query(Product.id.label("PId"),
Product.description.label("PDesc"),
Product.isactive.label("PIsactive"),
ProductSubCategory.id.label("PSCid"),
ProductCategory.description.label("PCDesc"),
ProductSubCategory.description.label("PSCDesc"),
Brand.id.label("BId"), Brand.name.label("BName"))\
.select_from(Product)\
.join(ProductSubCategory)\
.join(ProductCategory)\
.join(Brand)\
.all()
page = request.args.get('page', 1, type=int)
qp = paginate.Page(q, items_per_page=5, page=page)
data = sqlaq2dict(qp)
npage = qp.pager(url= url_for('main.products') + "?page=$page",
link_attr=dict({'class':'btn btn-outline-primary mb-4'}),
curpage_attr=dict({'class':'btn btn-primary mb-4'}),
dotdot_attr=dict())
pagenav = Markup(npage)
return render_template("products.html", title='Products', legend='Product',
data=data, pagenav=pagenav, formAdd=formAdd, formMod=formMod)
#main.route("/products/new", methods=['POST'])
#login_required
def addProduct():
formAdd = frmAddProduct()
if formAdd.validate_on_submit():
p = Product()
p.productSubCategory_id = formAdd.productSubCategory.data
p.brand_id = formAdd.brand.data
p.description = formAdd.description.data
p.isactive = formAdd.isactive.data
syncNext('management', 'Product', 'id') # Ensures right ID for Postgres
sess.add(p)
sess.commit()
flash(
f'Product {formAdd.description.data} has been added!', 'success')
# return jsonify({"status" : "success"}) #Cannot have multiple returns
return redirect(url_for('main.products'))
return render_template("products.html", title='Products', legend='Product',
formAdd=formAdd)
forms.py
class frmAddProduct(FlaskForm):
# productSubCategories = sess.query(ProductSubCategory.id,\
# ProductSubCategory.fullDesc)\
# .filter(ProductSubCategory.isactive==True)\
# .all()
psc = sess.query(ProductCategory.description.label("PCDesc"),
ProductSubCategory.id.label("PSCId"),
ProductSubCategory.description.label("PSCDesc"))\
.join(ProductSubCategory)\
.all()
pscDict = sqlaq2dict(psc) #Converts the resulting tuple to dict
productSubCategories = []
for r in pscDict:
i = (r['PSCId'], r['PCDesc'] + ', ' + r['PSCDesc'])
productSubCategories.append(i)
productSubCategory = SelectField('Product Sub-Category',
choices=productSubCategories,
coerce=int,
validators=[InputRequired()])
brands = sess.query(Brand.id, Brand.name)\
.filter(Brand.isactive == True)\
.all()
brand = SelectField('Brand', choices=brands, coerce=int,
validators=[InputRequired()])
description = StringField('Product Description', validators=[
DataRequired()], render_kw={"placeholder": "New Product"})
isactive = BooleanField('Status', default=True)
submit = SubmitField('Add Product')
#---------------------------------------------Should be composite Key
def validate_productSubCategory(self, productSubCategory):
user = sess.query(Product)\
.filter(Product.productSubCategory_id == self.productSubCategory.data,
Product.brand_id == self.brand.data, Product.description ==
self.description.data)\
.first()
if user:
raise ValidationError('Product combination is already enrolled.')
def validate_brand(self, brand):
user = sess.query(Product)\
.filter(Product.productSubCategory_id == self.productSubCategory.data,
Product.brand_id == self.brand.data, Product.description ==
self.description.data)\
.first()
if user:
raise ValidationError('Product combination is already enrolled.')
def validate_description(self, description):
user = sess.query(Product)\
.filter(Product.productSubCategory_id == self.productSubCategory.data,
Product.brand_id == self.brand.data, Product.description ==
self.description.data)\
.first()
if user:
raise ValidationError('Product combination is already enrolled.')
I am learning jQuery and I have issues on how to hide and show a button during page reload. I tried my code below, it hides and shows the button on click, but when the page loads, the button changes back to former state. This is what I've tried:
Template:
<span class="load-requests-sections"> <!-- Load page if request sent in Ajax -->
<!-- Main -->
<main>
<!-- Container -->
<div class="container-fluid" id="suggested-people-cont" style="position:relative;top:170px;padding-bottom:100px;">
<!-- Row Grid Container -->
<div class="row d-flex justify-content-center">
<div class="col-lg-6 col-md-9 col-12">
{% if following %}
<h6 class="suggested-people-header mb-3" style="font-weight:500;">Following {{ following.count|human_format }}</h6>
{% endif %}
<div class="card news-card mb-2" id="suggested-people-card" style="width:700px;padding:13px;box-shadow:none;">
{% for data in profile_and_button_status %}
<!-- Copy and paste for another post below -->
<div class="row mb-3">
{% if data.0.to_user.profile.profile_pic %}
<a href="{% url 'site:profile-view' data.0.to_user.username %}">
<img src="{{ data.0.to_user.profile.profile_pic.url }}" class="rounded-circle avatar-img ml-4" height="50" width="50" style="border:none;padding:0px;position:relative;top:-1px;object-fit: cover;">
</a>
{% endif %}
<div class="suggestionfrndnamemutual-cont mt-1 ml-3">
<p class="dark-grey-text text-lowercase font-weight-bold">
<a href="{% url 'site:profile-view' data.0.to_user.username %}"><span class="suggestionfrnd-username username dark-grey-text text-truncate" style="">
{{ data.0.to_user.username }}</span></a>
</p>
<p class="card-text" style="position:relative;top:0px;">
<span class="suggestionfrnd-mutual text-muted" style="font-size:13px;">New to Pixmate</span>
</p>
</div>
{% if not data.0.to_user == request.user %}
<div class="mt-2" style="position:absolute;right:30px;">
{% if data.1 == 'not_friend' %}
<a href="{% url 'site:send_friend_request' data.0.to_user.id %}" class="friend-request">
<button type="button" class="btn btn-primary btn-sm btn-block waves-effect text-capitalize font-weight-bold p-1" style="box-shadow:none;font-size:13px;width:100px;border-radius:30px;">
<span style="padding-right:10px;" class="ml-2">Follow</span>
</button>
</a>
{% elif data.1 == 'cancel_request_sent' %}
<a href="{% url 'site:cancel_friend_request' data.0.to_user.id %}" class="friend-request">
<button type="button" class="btn btn-amber btn-sm btn-block waves-effect text-capitalize font-weight-bold p-1" style="box-shadow:none;font-size:13px;width:100px;border-radius:30px;">
<span style="padding-right:10px;" class="ml-2">Cancel</span>
</button>
</a>
{% elif data.1 == 'follow_back_request' %}
<!-- CLICK ON THIS BUTTON TO HIDE AND SHOW THE BELOW BUTTON -->
<a href="{% url 'site:accept_friend_request' data.0.to_user.id %}" class="friend-request followback-btn">
<button type="button" class="btn btn-primary btn-sm btn-block waves-effect text-capitalize font-weight-bold p-1" style="box-shadow:none;font-size:13px;width:100px;border-radius:30px;">
<span style="padding-right:10px;" class="ml-2">Follow Back</span>
</button>
</a>
<!-- SHOW THIS BUTTON AFTER PAGE RELOAD -->
<a href="{% url 'site:remove_friend' data.0.to_user.id %}" class="friend-request following-btn" style="display:none;">
<button type="button" class="btn btn-sm btn-block border waves-effect text-capitalize font-weight-bold dark-grey-text p-1" style="box-shadow:none;font-size:13px;width:100px;border-radius:30px;">
<span style="padding-right:10px;" class="ml-2">Following</span>
</button>
</a>
{% endif %}
</div>
{% endif %}
</div>
<!-- Row Grid -->
{% empty %}
{% if owner_of_the_following %}
<div class="container text-center image-post mt-0">
<!-- <img src="{{ '/static/' }}images/photo-camera-img.png" class="mb-3" width="60" height="60"> -->
<p class="dark-grey-text" style="font-size: 28px;">People you're Following</p>
<p class="dark-grey-text">When you follow someone, it will show here.</p>
<a href="{% url 'site:people-suggested' %}" class="btn btn-primary btn-md waves-effect mx-auto my-4" style="box-shadow:none;border-radius:30px;">
<strong>Find People to Follow</strong></a>
</div>
{% else %}
<div class="container text-center image-post mt-0">
<p class="dark-grey-text"><strong>No users</strong></p>
</div>
{% endif %}
{% endfor %}
</div>
<!-- Card -->
</div>
<!-- Column Grid -->
</div>
<!-- Row Grid Container -->
</div>
<!-- Container -->
</main>
<!-- Main -->
</span>
Jquery:
//SEND FRIEND REQUESTS WITHOUT PAGE RELOAD THIS WORKED
$('.load-requests-sections').on('click', '.friend-request', function(event){
event.preventDefault();
var page = $(this).attr('href');
$('.load-requests-sections').load(page);
});
//HIDE AND SHOW BUTTON AFTER PAGE RELOAD RETURN BACK TO OLD STATE WHEN PAGE RELOAD
$('.followback-btn').on('click', function(event){
event.preventDefault();
$('.followback-btn').hide();
$('.following-btn').show();
})
I also tried using localstorage, to show the hidden button after the page reloads, but the old button clicked is still shown. How do I hide the old button after a page reload.
$(document).ready(function(){
var $hidden = $('.following-btn');
if (localStorage.getItem('show')) {
$hidden.show();
$('.followback-btn').hide();
}
$('.followback-btn').on('click', function() {
localStorage.setItem('show', true);
window.location.reload(false);
});
})
There seems to be a problem in how you test if the .followback-btn was pressed.
In your second jQuery example, try replacing this line:
localStorage.getItem('show') && $hidden.show();
With this:
if (localStorage.getItem('show')) {
$hidden.show();
$('.followback-btn').hide();
}
This means that if the show variable is set in the local storage, the .following-btn will be shown when the page loads, instead of the .followback-btn one.
Hope this helps.