I'm trying to implement predictive search into the search bar on the store, however I'm having abit of trouble making sense of the docs.
Here's what I've got so far, hopefully someone can point me in the right direction with what it is I am missing:
%- if settings.predictive_search_enabled -%}
<predictive-search data-loading-text="{{ 'accessibility.loading' | t }}">
{%- endif -%}
<form action="{{ routes.search_url }}" method="get" role="search">
<ul>
<li>
<input
type="search"
name="q"
placeholder="Amp Hours (aH)"
class="amp-input"
value="{{ search.terms | escape }}"
{%- if settings.predictive_search_enabled -%}
role="combobox"
aria-expanded="false"
aria-owns="predictive-search-results-list"
aria-controls="predictive-search-results-list"
aria-haspopup="listbox"
aria-autocomplete="list"
autocorrect="off"
autocomplete="off"
autocapitalize="off"
spellcheck="false"
{%- endif -%}>
{%- if predictive_search.performed -%}
<ul class="amp-dropdown-container">
{%- if predictive_search.resources.products.size > 0 -%}
<h5 class="volt-options-title">Top Searches</h5>
{%- endif -%}
{%- for product in predictive_search.resources.products -%}
<li>
{{ product.title }}
</li>
{%- endfor -%}
</ul>
{%- endif -%}
</li>
</ul>
</form>
{%- if settings.predictive_search_enabled -%}
</predictive-search>
{%- endif -%}
A predictive search box shows up but its not the way I need it to be. (only want it displaying products, not pages collections etc aswell).
I've also seen the javascript below in other tutorials but dont know how to use it for what I need. Any suggestions?
<script>
var q = 'goki'
var b = '&resources[type]=product'
$.ajax('/search/suggest.json?q=' + q + b,{
type: 'GET',
dataType: 'json', // added data type
success: function(response) {
console.log(response);
var productSuggestions = response.resources.results.products;
if (productSuggestions.length > 0) {
var firstProductSuggestion = productSuggestions[0];
alert(firstProductSuggestion.body);
}
}
});
</script>
Related
I'd like to show all grades from one user on Button Click. Now I wanted to integrate an expandable Button from Bootstrap. The GET Request works perfectly, but the JavaScript for the expandable Button gets triggered on Button Click and then the Page gets reloaded. That means the Button now is back at the original state. Do you guys maybe have a way to fix that?
noten.html
{% if subject_list %}
<form name="subject-list" method="GET">
<ul>
{% for subject in subject_list %}
<p>
<button class="btn btn-primary" type="submit" data-bs-toggle="collapse" data-bs-target="#{{ subject }}" aria-expanded="false" aria-controls="collapseExample" value="{{ subject }}" id="{{ subject }}" name="subject">
{{ subject }}
</button>
</p>
<div class="collapse" id="{{ subject }}">
<div class="card card-body">
{% if grades %}
{% for grade in grades %}
<li>{{ grade }}</li>
{% endfor %}
{% else %}
<p>Du hast keine Noten in diesem Fach!</p>
{% endif %}
</div>
</div>
{% endfor %}
</ul>
</form>
{% endif %}
views.py
def noten(request):
if request.user.is_authenticated: # if user is logged in
object_list = Subject.objects.order_by('name')
subject_list = []
for subject in object_list:
subject_list.append(subject.name)
if request.method == 'GET':
subject = request.GET.get('subject', '')
if subject != '':
print(f"GET {subject}")
grades = Test.get_grades(student=request.user.id, subject=subject, self=Test)
return render(request, 'noten.html', {'subject_list': subject_list, 'grades': grades})
else:
return render(request, 'noten.html', {'subject_list': subject_list})
else:
return render(request, 'noten.html', {'subject_list': subject_list})
else: # else redirect to login page
return redirect('loginForm:login')
I have a Django template (html), and a javascript in it that I want to loop for various pair values. It doesn't loop.
Here is the code in the template rsmgui.html:
{% for field in elements %}
<input type="hidden" id="theFieldLabelID" name="theFieldLabel" value="{{ field.label }}">
<input type="hidden" id="theFieldID" name="theField" value="{{ field }}">
<script src="{{ STATIC_URL }}js/loadStorage.js"></script>
{% endfor %}
The javascript loadStorage.js looks like this:
var myFieldLabel=document.getElementById("theFieldLabelID").value.replace(/ /g,"")
var myField = document.getElementById("theFieldID")
alert("Label = " + myFieldLabel);
localStorage.setItem(myFieldLabel, JSON.stringify(myField));
But it doesn't loop, it gets the first pair and then repeats it for the number of pairs. Any ideas how to "flush" the javascript so it reloads each time?
it gets the first pair and then repeats it for the number of pairs
That is because getElementById only returns first element. Element ID should be unique across the page. Without changing your logic, there are two solutions below.
First one is to add loop counter suffix:
{% for field in elements %}
<input type="hidden" id="theFieldLabel{{ forloop.counter }}" name="theFieldLabel" value="{{ field.label }}">
<input type="hidden" id="theField{{ forloop.counter }}" name="theField" value="{{ field }}">
<script>var id_suffix = "{{ forloop.counter }}"</script>
<script src="{{ STATIC_URL }}js/loadStorage.js"></script>
{% endfor %}
var myFieldLabel=document.getElementById("theFieldLabel" + id_suffix).value.replace(/ /g,"")
var myField = document.getElementById("theField" + id_suffix)
alert("Label = " + myFieldLabel);
localStorage.setItem(myFieldLabel, JSON.stringify(myField));
Second one is to use getElementsByName:
{% for field in elements %}
<input type="hidden" id="theFieldLabelID" name="theFieldLabel" value="{{ field.label }}">
<input type="hidden" id="theFieldID" name="theField" value="{{ field }}">
<script>var index = {{ forloop.counter0 }}</script>
<script src="{{ STATIC_URL }}js/loadStorage.js"></script>
{% endfor %}
var myFieldLabel=document.getElementsByName("theFieldLabel")[index].value.replace(/ /g,"")
var myField = document.getElementsByName("theField")[index]
alert("Label = " + myFieldLabel);
localStorage.setItem(myFieldLabel, JSON.stringify(myField));
Considering #sytech comment, you can wrap your code into function with a parameter is the index/id_suffix. Then call it with necessary value.
<script src="{{ STATIC_URL }}js/loadStorage.js"></script>
{% for field in elements %}
<input type="hidden" id="theFieldLabel{{ forloop.counter }}" name="theFieldLabel" value="{{ field.label }}">
<input type="hidden" id="theField{{ forloop.counter }}" name="theField" value="{{ field }}">
<script>loadStorage("{{ forloop.counter }}");</script>
{% endfor %}
function loadStorage(id_suffix)
{
var myFieldLabel=document.getElementById("theFieldLabel" + id_suffix).value.replace(/ /g,"")
var myField = document.getElementById("theField" + id_suffix)
alert("Label = " + myFieldLabel);
localStorage.setItem(myFieldLabel, JSON.stringify(myField));
}
I an using django-crispy forms and using that in a jquery dialog box to show a form wizard. the problem that I am facing is that when used in the dialog box the wizard never moves to the next screen.
So, my wizard is defined as follows:
class ContactWizard(SessionWizardView):
def get_template_names(self):
return "reviewdialog.html"
def done(self, form_list, **kwargs):
return HttpResponseRedirect('index')
And the template is defined as:
{% load crispy_forms_tags %}
{% load i18n %}
{% block content %}
<form action="." method="post">
{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{% crispy form %}
{% endfor %}
{% else %}
{% crispy wizard.form %}
{% endif %}
{% if wizard.steps.prev %}
<button name="wizard_goto_step" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
<button name="wizard_goto_step" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
{% endif %}
</table>
<input type="submit" class="btn btn-success" value = "NEXT">
</form>
{% endblock %}
Now, I show this in a jquery dialog where I have overridden the submit method to ensure that the dialog does not close on clicking the 'NEXT' button
<script>
function EditDialog(pk) {
$.ajax({
url: "{% url 'populatereviewform' %}",
method: 'GET',
data: {
pk: pk
},
success: function(formHtml){
//place the populated form HTML in the modal body
$('.modal-body').html(formHtml);
$( "#dialog" ).modal({width: 500, height: 500});
},
dataType: 'html'
});
$('#dialog').submit( function(e) {
return false;
});
return false;
}
</script>
The AJAX part just populates the form with some data and the dialog object is a standard jquery modal dialog. The form is shown at the first screen and is populated with the correct value but when I press NEXT nothing happens in the sense that the wizard does not transition.
The urls.py is configured as:
url(r'^review/(?P<pk>\d+)/$', views.ContactWizard.as_view([DummyForm, OtherForm]), name='review'),
Som, the form starts with the DummyForm (which is a ModalForm) but does not progress to the next wizard screen. I have a feeling it could be something to do with my javascript but could bit get to the bottom of this.
EDIT
So, based on #udi's answer, I tried the following:
$("#dialog").submit(function(e)
{
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$('.modal-body').html(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown)
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
return false;
}
However, the data that is returned here is not the next screen of the wizard but the underlying page on which the dialog is shown. So, perhaps it is the formURL or postdata variables that are not initialized properly?
The template for the wizard screen is:
{% load crispy_forms_tags %}
{% load i18n %}
{% block head %}
{{ wizard.form.media }}
{% endblock %}
{% block content %}
<form id="review-form" action="." method="post">
{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{% crispy form %}
{% endfor %}
{% else %}
{% crispy wizard.form %}
{% endif %}
{% if wizard.steps.prev %}
<button name="wizard_goto_step" class="btn btn-success" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
<button name="wizard_goto_step" class="btn btn-success" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
{% endif %}
</table>
<input type="submit" class="btn btn-success" value = "Hello">
</form>
{% endblock %}
You will need to get the html of the next form via jQuery and update it in the dialog.
Here is my html for the one-time price
<label for="autodeliver_off_radio_{{product.id}}" id="auto_deliver_label">
<input type="radio" name="autodeliver_{{product.id}}" class="autodeliver {{product.id}}" value="onetime" {% if subscription_only == 'false' %} checked="" {% endif %} id="autodeliver_off_radio_{{product.id}}"> <span class="label_background"></span>
<span style="color:black;">ONE-TIME PURCHASE </span> <span id="one-time-price_{{product.id}}"></span>
<br>
<span class="one_time_product_price"> {{ product.price | money }}</span>
</label>
here is my code for the subscription price
<label for="autodeliver_on_radio_{{product.id}}" id="auto_deliver_label" style="font-weight:bold;">
<hr style="margin-top:-5px;border-top: 1px solid #000;">
<input type="radio" name="autodeliver_{{product.id}}" class="autodeliver {{product.id}}" value="autodeliver" {% if subscription_only == 'true' %} checked="" {% endif %} id="autodeliver_on_radio_{{product.id}}"><span class="label_background"></span>
<span style="color:black;"> SUBSCRIBE
{% if discount_percentage != 0 %}
AND SAVE</span>
<span>{{discount_percentage}}%</span> <span id='recurring-time-price_{{product.id}}'></span><br><span class="subscribe_product_price">{{product.price | divided_by: new_num_2 | money }}</span> {% endif %}
</label>
and here is where is need the price to update
<div class="add-to-cart__wrapper">
<button type="submit" name="add" id="AddToCart" class="btn btn--large btn--full btn--clear uppercase">
<span id="AddToCartText">{{ 'products.product.add_to_cart' | t }} </span>
<span class="unicode">•</span>
<span class="add-to-cart__price money"><span id="ButtonPrice">{{ product.price | money }}</span></span>
</button>
</div>
I was hoping there was an easy jquery solution for this but i cant seem to get it. Been trying to extract html value from beside the checkboxes and update the add to cart button but no luck. Really stumped and thanks in advance! I added a visual in case this was confusing
Give this jQuery code a try:
$(function(){
var buttonPrice = $('span#ButtonPrice');
$('input[type="radio"].autodeliver').click(function(){
_this = $(this);
if ( _this.attr('value') === 'onetime' ) {
buttonPrice.html( $('span.one_time_product_price').html() );
} else if ( _this.attr('value') === 'autodeliver' ) {
buttonPrice.html( $('span.subscribe_product_price').html() );
};
});
});
I have a html code like this:
{% for i, j, k in full_name %}
{{ i }} {{ j }}
<input type="text" name="follow_id" value="{{ k }}" />
<input type="submit" value="Follow"><br /> <br />
{% endfor %}
The output looks like this:
user1 user_id_of_user1 follow_button
user2 user_id_of_user2 follow_button
user3 user_id_of_user3 follow_button
If I press the follow button of user3 I want to send the id of user3 only so that I can access it in server like this:
followed_user = request.POST['follow_id']
# Process
But, no matter which follow_button I press, I get the user id of only user1. How to fix this?
This is not a Django issue, but a HTML issue. Here is the work around: 1 form for each user:
{% for i, j, k in full_name %}
<form action="mydomain.com/mysubmiturl/" method="POST"><!-- Leave action empty to submit to this very same html -->
{% csrf_token %} <!-- Django server only accept POST requests with a CSRF token -->
{{ i }} {{ j }}
<input type="text" name="follow_id" value="{{ k }}" />
<input type="submit" value="Follow"><br /> <br />
</form>
{% endfor %}
Note that all the forms submit to the same URL, and thus the same view function !
Just my 2 cents, I would use some jQuery for this job.
In your template:
{% for i, j, k in full_name %}
{{ i }} {{ j }}
Follow
{% endfor %}
Then submit the data using AJAX:
$('.follow-button').click(function (e) {
e.preventDefault();
var this_id = $(this).attr('id').replace('js-follow-', '');
$.ajax({
type: 'POST',
url: 'path/to/view',
data: {'follow_id': this_id},
success: function (resp) {
// do something with response here?
}
});
});