how to get content in same div without getting in many boxes? - javascript

I have following code
<div class="col-md-9">
<div id="statbox">
{% for obj in product_type %}
{% for obj1 in vastu %}
<script type="text/javascript">
var product = "{{ obj.type_product }}";
var product1 = "{{ name }}";
var vastu = "{{ obj1.vastu_key.id }}";
var type_id = "{{ obj.id }}";
if (vastu == type_id)
{
var title = "{{ obj1.title }}";
var brand = "{{ obj1.brand }}";
var img = "{{ obj1.image }}";
var price = "{{ obj1.price }}";
$("#statbox").prepend("<div id='box2'>"
+ title
+ brand
+ price
+"</div>");
}
</script>
{% endfor %}
{% endfor %}
</div>
I am using two for loops here and the box2 which is styled in css, by running this code i got box2 multiple times as content contains in child for loop and that title,brand,img,price is displyed in each new box2.
But i want new box2 should be generate only according to content contains in parent for loop not according to content contains in child for loop
and the all contents i.e. title,brand,img,price which are associated with each content of parent for loop should disply in same box2.
Multiple box2 only create according to parent for loop and contents of child for loop in the same box2 created by parent for loop.
Thank you....

Create a JS object and loop that . Also change the ID to class
Something like this:
var boxes = [
{% for obj in product_type %}
{
{% for obj1 in vastu %}
"product":"{{ obj.type_product }}",
"product1":"{{ name }}",
"vastu": "{{ obj1.vastu_key.id }}",
"type_id":"{{ obj.id }}"
{% if obj1.vastu_key.id == obj.id %}
,
"title":"{{ obj1.title }}",
"brand":"{{ obj1.brand }}",
"img":"{{ obj1.image }}",
"price":"{{ obj1.price }}"
{% endif %}
{% endfor %}
}
{% endfor %}
];
$.each(boxes,function(obj) {
$("#statbox").prepend("<div class='box2'>"
+ obj.title || ""
+ obj.brand || ""
+ obj.price || """
+"</div>");
});

Related

Select a variant on product page load Shopify

I wrote a piece of code that works in a way where once I select a variant on the product page, only media with the same alt text as the variant name, will display while the rest of the media is hidden. My only problem is when the product page loads it displays all the media, even if I go directly to the URL with variant ID in it. So a variant has to be selected, for my page to show only matching alt-text media. I'm wondering if there is a way to either change this or make it so that on the website load the first variant gets selected.
Here is the HTML & Liquid code I'm using:
{% unless product.has_only_default_variant %}
<variant-selector data-url="{{ product.url }}" data-section="{{ section.id }}">
{% for option in product.options_with_values %}
<label for="option-{{ section.id }}-{{ forloop.index0 }}">{{ option.name }}</label>
<select name="options[{{ option.name | escape }}]" id="option-{{ section.id }}-{{ forloop.index0 }}">
{% for value in option.values %}
<option value="{{ value | escape }}" {% if option.selected_value == value %} selected="selected" {% endif %}>{{ value }}</option>
{% endfor %}
</select>
<script type="application/json">
{{ product.variants | json }}
</script>
{% endfor %}
</variant-selector>
{% endunless %}
And here is the javascript code:
class VariantSelector extends HTMLElement {
constructor() {
super();
this.addEventListener("change", this.onVariantChange);
}
onVariantChange() {
this.getSelectedOptions();
this.getSelectedVariant();
this.updateMedia(this.currentVariant);
if (this.currentVariant) {
this.updateURL();
this.updateFormID();
this.updatePrice();
this.updateMedia();
}
}
getSelectedOptions() {
this.options = Array.from(this.querySelectorAll('select'), (select) => select.value);
console.log(this.options);
}
getVariantJSON() {
this.variantData = this.variantData || JSON.parse(this.querySelector('[type="application/json"]').textContent);
return this.variantData;
}
getSelectedVariant() {
this.currentVariant = this.getVariantJSON().find(variant => {
const findings = !variant.options.map((option, index) => {
return this.options[index] === option;
}).includes(false);
if (findings) return variant;
});
console.log(this.currentVariant);
}
updateURL() {
if (!this.currentVariant) return;
window.history.replaceState({}, '', `${this.dataset.url}?variant=${this.currentVariant.id}`);
}
updateFormID() {
const form_input = document.querySelector("#product-form").querySelector('input[name="id"]');
form_input.value = this.currentVariant.id;
}
updatePrice() {
fetch(`${this.dataset.url}?variant=${this.currentVariant.id}&section_id=${this.dataset.section}`)
.then((response) => response.text())
.then((responseText) => {
const id = `price-${this.dataset.section}`;
const html = new DOMParser().parseFromString(responseText, 'text/html');
const oldPrice = document.getElementById(id);
const newPrice = html.getElementById(id);
if (oldPrice && newPrice) oldPrice.innerHTML = newPrice.innerHTML;
});
}
updateMedia() {
if(this.currentVariant.featured_image !=null && this.currentVariant.featured_image.alt != null) {
$('[thumbnail-color]').hide();
var selected_color = this.currentVariant.featured_image.alt;
var thumbnail_selector = '[thumbnail-color="' + selected_color + '"]';
$(thumbnail_selector).show();
} else {
$('[thumbnail-color]').hide();
}
}
}
customElements.define("variant-selector", VariantSelector);

how to get values from views.py and use it in Javascript tag

This is my views.py
def list_note(request):
note_info = Note.objects.filter(id_teacher__exact=request.user.id).select_related()
actual_date = date.today()
for notes in note_info:
note_date = notes.remind.date()
tmp = actual_date + timedelta(days=3)
note_expired_list = []
if tmp == note_date:
print()
else:
note_expired_list.append(notes)
print(note_expired_list)
note_data = {
"note_details": note_info,
"note_expired_list_details": note_expired_list,
}
return render_to_response('list_note.html', note_data, context_instance=RequestContext(request))
I want use value note_expired_list_details in <scrpit> tag to display this in alert. How do this?
I try use {{ note_expired_list_details}} but in <script> tag not work.
This is a part of my templates (I try finding HTML element by Id in JS)
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<div >
{% for details in note_expired_list_details %}
<p>{{ details }}</p>
{% endfor %}
<script>
var x = document.getElementsByTagName("p");
alert("Test\n" + x[1].childNodes.nodeValue + "\n");
</script>
</div>
{% endblock %}
Why not store value of {{ note_expired_list_details }} in a JS variable and then use it however you want?
<script>
var expiredList = '{{ note_expired_list_details }}';
alert(expiredList);
</script>

Using a Jquery variable inside of a .html() function [duplicate]

This question already has answers here:
jQuery .html() and a variable inside
(2 answers)
Closed 7 years ago.
So I have a Jquery if statement that displays different content inside a div using $(".library-content").html("Here is some content!") but I want a section of the content displayed to be dependent on a variable. So if the variable was set to "cats" the content might read "I like cats" and if the variable changes to "dogs" it would read "I like dogs". Is it possible?
here is my code, it is quite long so i tried to shorten it in my example,
var librarycat = 'none' ;
var librarytype = 'none' ;
$( document ).ready(function() {
$("#library-cat").change(function() {
librarycat = $('option:selected',this).val();
if(librarycat != 'none' && librarytype != 'none') {
$(".library-content").html("{% set topic_posts = blog_recent_topic_posts('2941362257', 'audio', 25 ) %}<ul class='test-list'>{% for post in topic_posts|unique('name') %}{% if 'audio' in post.topic_list|map(attribute='name') %}<li><a href='{{post.absolute_url}}'><img src='{{ post.post_list_summary_featured_image }}' class='hs-featured-image'>{{ post.name}}</a><br>{% for topic in post.topic_list %}<a class='topic-link' href='{{ group.absolute_url }}/topic/{{ topic.slug }}'>{{ topic.name }}</a>{% if not loop.last %} {% endif %}{% endfor %}</li>{% endif %}{% endfor %}</ul>");
}
else if(librarycat == 'none' && librarytype != 'none') {
$(".library-content").html("{% set topic_posts = blog_recent_topic_posts('2941362257', 'audio', 25 ) %}<ul class='test-list'>{% for post in topic_posts|unique('name') %}<li><a href='{{post.absolute_url}}'><img src='{{ post.post_list_summary_featured_image }}' class='hs-featured-image'>{{ post.name}}</a><br>{% for topic in post.topic_list %}<a class='topic-link' href='{{ group.absolute_url }}/topic/{{ topic.slug }}'>{{ topic.name }}</a>{% if not loop.last %} {% endif %}{% endfor %}</li>{% endfor %}</ul>")
}
else if(librarycat != 'none' && librarytype == 'none') {
$(".library-content").html("{% set topic_posts = blog_recent_topic_posts('2941362257', 'audio', 25 ) %}<ul class='test-list'>{% for post in topic_posts|unique('name') %}<li><a href='{{post.absolute_url}}'><img src='{{ post.post_list_summary_featured_image }}' class='hs-featured-image'>{{ post.name}}</a><br>{% for topic in post.topic_list %}<a class='topic-link' href='{{ group.absolute_url }}/topic/{{ topic.slug }}'>{{ topic.name }}</a>{% if not loop.last %} {% endif %}{% endfor %}</li>{% endfor %}</ul>")
}
else {
$(".library-content").html("{% set topic_posts = blog_recent_topic_posts('2941362257', 'audio', 25 ) %}<ul class='test-list'>{% for post in topic_posts|unique('name') %}{% if 'Insurance' in post.topic_list|map(attribute='name') %}<li><a href='{{post.absolute_url}}'><img src='{{ post.post_list_summary_featured_image }}' class='hs-featured-image'>{{ post.name}}</a><br>{% for topic in post.topic_list %}<a class='topic-link' href='{{ group.absolute_url }}/topic/{{ topic.slug }}'>{{ topic.name }}</a>{% if not loop.last %} {% endif %}{% endfor %}</li>{% endif %}{% endfor %}</ul>")
}
});
where you see the word 'audio' I would like this to be depended on a select element.
Since you're new in town I'll help you out. In the future, please have a look at the help pages and provide some of your code.
if (firstThing === firstThing) {
var myString = "Some words";
if (secondThing) {
myString = myString + "are pretty cool";
}
$(".library-content").html(myString);
}
Use an if statement and local variables to set your message. The input to the .html() function can be a variable or static text.
$().ready(function() {
var useCats = false;
var catsMessage = "I Like Cats";
var dogsMessage = "I Like Dogs";
if(useCats)
$(".library-content").html(catsMessage);
else
$(".library-content").html(dogsMessage);
});
$().ready(function() {
var useCats = false;
var catsMessage = "I Like Cats";
var dogsMessage = "I Like Dogs";
if(useCats)
$(".library-content").html(catsMessage);
else
$(".library-content").html(dogsMessage);
});
.library-content {
border: 1px solid red;
width: 200px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="library-content">Original Content</div>

Javascript innerhtml doesn't work with twig tags

I have a function in twig which selects some values from db and displays a selectbox. I am trying to change the content of the div. The problem is that with innerHTML {{ creates a new line without quote and this is shown like error. It doesnt get the select box because it doesn't have quotes.
$(document).ready(function() {
$type = $("select[name='dtl[USER_TYPE]']");
$type.change(function() {
if ($(this).val() == "AUTOR") {
var content = '{{ mm.select(holdersdata, data.USER_TYPE_OBJECT_KOD, 'dtl[USER_TYPE_OBJECT_KOD]') }}';
document.getElementById("kodi").innerHTML = '"'+ content + '"';
}
});
});
macros.twig
<select data-placeholder="{{ translate('ZGJIDH_NJE') }}" name="{{ name }}" class="form-control input-sm chosen-select">
<option {% if not options.allowNull %}disabled{% endif %} selected value>{{ translate('ZGJIDH_NJE') }}</option>
{% for f in dataset %}
<option value="{{ f[kodField] }}" {% if f[kodField] | trim == selectedVal %}selected{% endif %}>
{% if f[labelField] %}
{{ f[labelField] }} {% if f[kodField] %}— ({{ f[kodField] }}){% endif %}
{% else %}
{{ f[kodField] }}
{% endif %}
</option>
{% endfor %}
</select>
EDIT
this is shown in console. {{ creates a new line without quotes:
var content = "
<select data-placeholder="Zgjidh nje..." name="dtl[USER_TYPE_OBJECT_KOD]" class="form-control input-sm chosen-select">
<option disabled selected value>Zgjidh nje...</option>
</select>
The problem is that your twig syntax is breaking the javascript syntax. See below, just change the 'to "
if ($(this).val() == "AUTOR") {
var content = '{{ mm.select(holdersdata, data.USER_TYPE_OBJECT_KOD, 'dtl[USER_TYPE_OBJECT_KOD]') }}';
document.getElementById("kodi").innerHTML = '"'+ content + '"';
}
Correct code :
if ($(this).val() == "AUTOR") {
var content = "{{ mm.select(holdersdata, data.USER_TYPE_OBJECT_KOD, 'dtl[USER_TYPE_OBJECT_KOD]') }}";
document.getElementById("kodi").innerHTML = '"'+ content + '"';
}
Due to the contents of your output JS is breaking as well. U can solve this by extending twig :
$filter = new Twig_SimpleFilter('escape_for_js', function ($string) {
$needles= array(
"\n",
"\r",
'"',
);
$replaces = array(
'',
'',
'\"',
);
return str_replace($needles, $replaces, $string);
});
Add this filter into twig :
$twig = new Twig_Environment($loader);
$twig->addFilter($filter
Using this filter :
var content = "{{ mm.select(holdersdata, data.USER_TYPE_OBJECT_KOD, 'dtl[USER_TYPE_OBJECT_KOD]') | escape_for_js }}";
More about extending twig here
No need to extend Twig yourself. Just use json_encode:
var content = {{ mm.select(holdersdata, data.USER_TYPE_OBJECT_KOD, 'dtl[USER_TYPE_OBJECT_KOD]') | json_encode }};
Notice the lack of quotes. json_encode will add them for you.

Javascript not reading the keys and values of a dictionary in django template

I have a dictionary like:
dest = {2: [u'canada', u'A', 'Ottawa'], 5: [u'Malaysia', u'A', 'KualaLumpur'],...}
Then I tried to retrieve the keys and values from dest in django template using javascript:
function categorizeReports()
{
var a = [];
var b = [];
{% for i,v in dest %}
id = '{{i}}';
console.log('id', id)
values = '{{v}}';
console.log('values',values)
{% for name, type, cat in values %}
if(type=='A' && cat=='Ottawa')
{
a.push(id,name,type,cat)
}
if(type=='A' && cat=='KualaLumpur')
{
b.push(id,name,type,cat)
}
{% endfor %}
{% endfor %}
console.log(a)
console.log(b)
}
But both the Arrays are shown as 'an empty string' as well as id and values are too shown as 'an empty string', Please help!
Missing .items
Change
{% for i,v in dest %}
to
{% for i,v in dest.items %}

Categories