I'm building a search page that allows doing a search from 1-4 keywords that through the get method sends to the results page.(eg. for those keywords: one, two tree --> website.com/search/q=one+two+tree)
Right now when I add more keywords and press search it sends to the URL using just the keyword in the text input.
I tried to create a string joining the keywords with the "+" but sitll doesn't work. The following code is what I have tried.
This is a django webapp and in the form.py there is one charfield with an id tag named "add_keyword".
The function that doesn't work is send_keywords()
<body>
<link rel="stylesheet" href="style.css">
<script type="text/javascript">
var keywords_array = []
function getInputValue() {
if (keywords_array.length<4){
var ul = document.getElementById("keywords");
var li = document.createElement("li");
var inputVal = document.querySelector("#add_keyword").value;
li.appendChild(document.createTextNode(inputVal));
ul.appendChild(li);
keywords_array.push(inputVal);
}
if (keywords_array.length==4){
console.log("You've added the max number of keywords")
}
}
function send_keywords() {
query = keywords_array.join("+")
window.location.href= window.location.href+"/search/q="+query
return query
}
</script>
<h1>Dulcis in Fundo</h1>
<h2>Let's coock something, what do you have left?</h2>
{% block content %}
<form class="" action="/search/" method="GET">
<ul id="keywords">
</ul>
{{ form }}
<button type="button" onclick="getInputValue();" name="button">add</button>
<button type="submit" onclick="send_keywords()">Search</button>
</form>
{% endblock %}
</body>
Related
I have 2 buttons orders, and suppliers., and want to show data in a Django web app when the corresponding button is clicked. To do this my home.html looks like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".button_order").click(function(){
$(".myorders").show();
$(".mysupplier").hide();
});
$(".button_supplier").click(function(){
$(".myorders").hide();
$(".mysupplier").show();
});
});
</script>
syle.css looks like;
.myorders,
.mysupplier{
font-size: 25px;
display: none;
}
This works perfectly fine until I use normal data like;
<body>
{%block content %}
<button class="button_order" >ORDERS</button>
<button class="button_supplier" >SUPPLIER</button>
<p class="myorders" >
This is my order
</p>
<p class="mysupplier">
my supplier is cool
</p>
</body>
But when I try to use data into <p class="mysupplier"> or <p class="myorders" > from my databases, the hide property no longer works, like below part.
<p class="myorders">
{% for element in orders %}
{% for key,val in element.items %}
<ul><li>{{key}}:{{val}}</li></ul>
{% endfor %}
<hr class="new1">
{% endfor %}
</p>
I should get Order data from database only when ORDER button is clicked, but my server shows all data from before without even clicking the button. How to maintain hide and show the property of my data.
my views.py looks like
from django.shortcuts import render
client = MongoClient("mongodb://localhost:27017/")
db=client.inventory_data
def home(request):
collection_data_1 = db['orders']
orders = list(collection_data_1.find())
collection_data_2= db['suppliers']
suppliers = list(collection_data_2.find())
return render(request,'home.html',{'orders': orders,'suppliers':suppliers})
The loop in template is executed when rendering template. You pass all your data from view to template. if you just want to hide it from display add to your js:
<script>
$(document).ready(function(){
$(".mysupplier").hide();
$(".myorders").hide();
$(".button_order").click(function(){
$(".myorders").show();
$(".mysupplier").hide();
});
$(".button_supplier").click(function(){
$(".myorders").hide();
$(".mysupplier").show();
});
});
</script>
but if you would like to dynamicly fetch current data from db by pressing button i recommend use htmx (htmx.org)
I am trying to load a variable into a HTML page when pressing a button. The problem is that I already have a function to load the initial page, and the new data shall be loaded on the same page, without redirecting.
This is the code i have by now:
.py file:
#app.route('/')
def index():
return render_template('index.html')
def get_documents():
documents = {'asd': 'as', 'def':'de'}
return render_template('index.html', documents=json.dumps(documents))
index.html file
<div>
<button onclick="Start()" id="StartButton" >Start</button>
</div>
<div id = "feed" style="display: none;">
</div>
<script>
var d = JSON.parse('{{documents | tojson | safe}}');
document.getElementById('feed').innerHTML = d.asd;
</script>
.js file:
function Start()
{
var feed_div = document.getElementById("feed");
feed_div.style.display = "block";
}
I would like that when i press the Start button, the content in the documents structure would appear in the .feed section. How could i do this?
Also, documents will be a list, but here i used a json because i wanted to try some examples i've found.
You can create div element inside the feed element, this element will contain all of your document data and will be hidden
<div id="document" style="display: hidden">
{% for item in documents %}
<div>{{ item }}</div>
{% endfor %}
</div>
and then in javascript change the display of the document element:
function start() {
document.getElementById("document").style.display = "block";
}
I am experiencing some problems with my code. My data loader to python isn't working. Here is my HTML site (using Jinja syntax from a base.html):
{% extends 'base.html' %}
{% block head %}
<title>PPO Count</title>
{% endblock %}
{% block body %}
<!-- Header -->
<div class="header">
<h2 class='title'>Prototype 1: Pet Owner Viz</h2>
</div>
<!-- Button Panel-->
<!-- Vis Box -->
<div class='canvas'>
<div class="container">
<div class='button-box'>
<button id='Bx' type="button" onclick='toggleClickedBuz("Bx", "Bx")'>Bx</button>
<button id='By' type="button" onclick='toggleClickedBuz("By", "By")'>By</button>
<button id='Bz' type="button" onclick='toggleClickedBuz("Bz", "Bz")'>Bz</button>
<button id='loadData'>Load Data</button>
</div>
<div class='viz-box'>
</div>
</div>
</div>
<!-- Scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.js"></script>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="/static/js/main.js"></script>
{% endblock %}
Notice the buttons? What occurs is that onclick, it goes into an array using JS. In sum this function deletes duplicate entries and changes the colour of the buttons on screen to highlight their selection.
const vizBox = d3.select('.viz-box');
const svg = vizBox.append('svg');
// Create button click array
var clickedBusinesses = [];
function toggle(business) {
clickedBusinesses[business] = !clickedBusinesses[business];
};
function getClickedBusinesses() {
return Object.keys(clickedBusinesses).filter(key => clickedBusinesses[key]);
};
// Update array and change button colour to reflect selection
function toggleClickedBuz( bizStr , id ) {
if(clickedBusinesses.includes(bizStr)){
// removing duplicate element from that array, dependant on button pressed
clickedBusinesses = clickedBusinesses.filter( cb => cb !== bizStr );
document.getElementById( id ).style.backgroundColor='white';
}else{
// else push it to the array
clickedBusinesses.push(bizStr)
document.getElementById( id ).style.backgroundColor='red';
}
var json_string = JSON.stringify(clickedBusinesses)
console.log(json_string)
};
window.onload = function() {
d3.select('loadData').onclick = function() {
doWork()
};
}
function doWork() {
$.post('receiver', json_string, function() {
});
event.preventDefault();
}
button id='loadData' isn't working, I can't get my jsonified JS array into python. Any thoughts?
d3.select does not return a native DOM node, it returns a so called d3-selection that doesn't know anything about onclick. Instead, you should use the .on method of a d3-selection to register event listeners as described here: https://github.com/d3/d3-selection#handling-events
Alternatives:
Instead of using d3 to select elements, use the native .querySelector method: document.querySelector('#loadData').onclick = ....
Or use jQuery for it: $('#loadData').on('click', ...).
I have a webpage that generate <li> from a Json object passed from a flask app route. I have a set of checkboxes generated dynamically from the same Json object. What I wanted to do is highlight the words in the <li> text ... </li> if there is a match to any checked checkbox.
This what I have done so far.
Java script to capture checked checkboxes and find matches in <li>
$(".topic-check").change(function(){
var chkTopicIDs = checkTopics();
console.log(chkTopicIDs);
list_items = document.querySelectorAll(".sent");
for (item of list_items){
var text = item.textContent;
if (new RegExp(chkTopicIDs.join("|")).test(text)){
item.classList.add("highlight");
}
else {
item.classList.remove("highlight");
}
}
});
function checkTopics(){
$checkbox = $('.topic-check');
var chkArray = [];
chkArray = $.map($checkbox, function(el){
if(el.checked){return el.id}
});
return chkArray;
}
CSS to highlight
.highlight{
background: yellow;
}
HTML template with jinja tags
...
<ul>
{% for sent in turn['list_of_sentences'] %}
<li class="sent">{{sent['text']}}</li>
{% endfor %}
</ul>
...
<div class="card-body">
{% for topic in response['topics'] %}
<div>
<input type="checkbox" id="{{topic}}" class="topic-check" onclick="func1()" /> <label class="checkbox-inline" >{{ topic }}</label> <br/>
</div>
{% endfor %}
</div>
...
I did a sanity check to see whether I get the list of checked checkboxes. The console displays IDs, so that part worked. But I don't see the highlighting of text regardless of checkboxes are checked.
Side note: I also see the following error in JS console.
ReferenceError: func1 is not defined
1) You have a typo here: item.classList.add("highlist") - should be highlight correct?
2) onclick="func1()" this is causing your func1 is not defined, just remove it.
3) I don't know if that's the case, but $(".topic-check").change won't work on dynamically added HTML. You need something like $(".card-body").on("change", ".topic-check", function)
4) You should store new RegExp(chkTopicIDs.join("|")) as a variable outside the loop for increased performance
I know similar questions have been asked before but I am very new to django and js. I have tried many solutions but I am not able to make sense of many and able to run them. So I am writing my code and the solution that I have tried. Can someone please tell me what mistake am I doing.
In my views.py I am handling a file which produces some results. These results are in the form of a Dataframe(used pandas). From this dataframe I am calculating few integer values which are stored in variables: tot,p,lp,us. I am also getting 3 sub-dataframes namely: dfp,dflp,dfus. I need to display all these on the webpage so I am sending them to an html: uploaded.html as shown below.
dict_1 = {'Path':p, 'LPath':lp, 'USig':us}
json1 = json.dumps(dict_1)
return render(request, 'uploaded.html', locals(), {'js_json1': json1, 'TotVar': tot})
The above code just sends the variables and not the dataframe as I don't know how to do it. I have handled it in my uploaded.html in the following way:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Upload File-Hereditary Cancers</title>
<link rel="stylesheet" href="/static/css/style.css" type="text/css">
<script type="text/javascript">
function results()
{
var totalvariants = {{TotVar}};
document.getElementById("totvar").innerHTML = "Total number of variants are: "+totalvariants;
}
</script>
</head>
<body>
<div id="header">
<div>
<div class="logo">
Hereditary Cancers
</div>
<ul id="navigation">
<li>
Home
</li>
<li>
About
</li>
<li class="active">
Upload File
</li>
<li>
Team
</li>
<li>
Contact Us
</li>
</ul>
</div>
</div>
<div>
{% if saved %}
<strong>Your file was uploaded.</strong>
<button onclick = "results()">Results</button>
<p id = "totvar">This will change</p>
{% endif %}
{% if not saved %}
<strong>Your file was not uploaded.</strong>
{% endif %}
</div>
<div id="footer">
<div class="clearfix">
<div id="connect">
</div>
<p>
© 2023 Zerotype. All Rights Reserved.
</p>
</div>
</div>
</body>
</html>
I am creating a button in my html which activates the script on click. I haven't done much in my script because I don't know how to. I have just tried to display the tot variable which is also not getting displayed.Can anyone tell me the complete script on how I can handle dataframes and variables in my js function and display their results.
i don't know what are you do, but you send locals() as context. first, why you did this? you don't use them in template. second, you should send your context in third parameter in render() and if you so need locals in template context, write something like this:
ctx = locals()
ctx.update(
js_json1 = json1,
TotVar = tot,
)
return render(request, 'uploaded.html', ctx)
or
ctx = {
'locals': locals(),
'js_json1': json1,
'TotVar': tot,
}
return render(request, 'uploaded.html', ctx)
https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#render