I'm trying to use js to save values in selected options. It works if js put it in my HTML template. Like this:
{% load static %}
{% include "header.html" %}
{% block content %}
<script src="{% static 'ReportingTool/js/sort_text.js' %}"></script>
<script src="{% static 'ReportingTool/js/sort_number.js' %}"></script>
...
<form method="GET" action=".">
<div class="row">
<div class="border border-2 p-2 g-2">
<label for="periodMin">Start date</label>
<input type="date" class="myselect form-select form-select-sm" id="periodMin"
name="period_min">
<label for="periodMax">End date</label>
<input type="date" class="myselect form-select form-select-sm" id="periodMax"
name="period_max">
</div>
<div class="border border-2 p-2 g-2">
<label for="structDivisions">Structural divisions</label>
<select id="structDivisions" class="myselect form-select form-select-sm"
name="struct_division">
<option selected>Choose...</option>
{% for SD in struct_divisions %}
<option id="{{ SD.id }}" value="{{ SD }}"> {{ SD }}</option>
{% endfor %}
</select>
<label for="workers">Worker</label>
<select id="workers" class="myselect form-select form-select-sm" name="worker">
<option selected>Choose...</option>
{% for worker in workers %}
<option value="{{ worker }}">{{ worker }}</option>
{% endfor %}
</select>
</div>
<div class="border border-2 p-2 g-2">
<label for="workDone">Work done</label>
<select class="myselect form-select form-select-sm" id="workDone" name="work_done">
<option selected>Choose...</option>
{% for work in workstype %}
<option value="{{ work }}">{{ work }}</option>
{% endfor %}
</select>
<label for="scope_min">Scope min</label>
<input type="number" min=0 class="myselect form-control form-control-sm" id="scope_min"
name="work_scope_min">
<label for="scope_max">Scope max</label>
<input type="number" min=0 class="myselect form-control form-control-sm" id="scope_max"
name="work_scope_max">
<label for="notes">Notes contains</label>
<input type="text" class="myselect form-control form-control-sm" id="notes"
name="work_notes_contains">
</div>
<div class="row border border-2 p-2 g-2">
<button type="submit"
value="sumbit"
name="button_search"
class="btn btn-outline-secondary w-100"
title="Search">
🔍
</button>
<button
name="button_export"
class="btn btn-outline-secondary w-100"
onclick=" location.href='{% url 'export_report' %}'"
title="Export csv">
💾
</button>
</div>
</div>
</form>
...
<script>
let selItems = JSON.parse(sessionStorage.getItem("SelItem")) || [];
$(function() {
if (selItems) {
selItems.forEach(obj => {
const [k, v] = Object.entries(obj)[0]
$("#" + k).val(v)
})
}
$('.myselect').on("change", function() {
selItems = $('.myselect').map(function() {
return { [this.id]: this.value }
}).get();
sessionStorage.setItem("SelItem", JSON.stringify(selItems))
});
});
</script>
{% endblock content %}
{% include "footer.html" %}
But if I put the script in a separate file:
{% load static %}
{% include "header.html" %}
{% block content %}
<script src="{% static 'ReportingTool/js/sort_text.js' %}"></script>
<script src="{% static 'ReportingTool/js/sort_number.js' %}"></script>
<script src="{% static 'ReportingTool/js/select.js' %}"></script>
select.js:
let selItems = JSON.parse(sessionStorage.getItem("SelItem")) || [];
$(function() {
if (selItems) {
selItems.forEach(obj => {
const [k, v] = Object.entries(obj)[0]
$("#" + k).val(v)
})
}
$('.myselect').on("change", function() {
selItems = $('.myselect').map(function() {
return { [this.id]: this.value }
}).get();
sessionStorage.setItem("SelItem", JSON.stringify(selItems))
});
});
it doesn't work. He doesn't understand what event he reacts to? I tried to add the name of the function and call click on the event. Nothing helps
What am I doing wrong?
change this:
<script src="{% static 'ReportingTool/js/select.js' %}"></script>
To
<script src="{% static '/ReportingTool/js/select.js' %}"></script> #You forgot to add forward slash(/) before ReportingTool.
Try and see if this is works
Related
I am using jquery to clone elements in a form and send all the data to a fastapi app. The problem I am finding is fastapi is not picking up the extra elements in the form.
Here is the code:
<button id="{{x.employee_id}}" class="btn btn-success eventBtn">Add Subject</button>
<form action="/cxc?id={{x.employee_id}}" method="POST">
<div id="cxc_form{{x.employee_id}}">
<div id="add_form{{x.employee_id}}">
<div class="row">
<div class="col">
<label class="form-label" for="area">Area of study:</label><br>
<select class="form-control" name="area0" id="area0">
{% for area in areas %}
<option value="{{area.qualification_area_id}}">{{area}}</option>
{% endfor %}
</select>
</div>
<div class="col">
<label class="form-label" for="deg">Grades:</label><br>
<select class="form-control" name="deg0" id="deg0">
{% for weight in weight %}
<option value="{{weight.weight_id}}">{{weight}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="row">
<div class="col">
<label class="form-label" for="country">Country:</label><br>
<select class="form-control" name="country0" id="country0">
{% for country in countries %}
{% if country.country_id == 186 %}
<option value="{{country.country_id}}" selected>{{country.name}}</option>
{% else %}
<option value="{{country.country_id}}">{{country.name}}</option>
{% endif %}
{% endfor %}
</select>
</div>
<div class="col">
<label class="form-label" for="yr">Year obtained:</label><br>
<input class="form-control" type="date" id="yr0" name="yr0" placeholder="Year received">
</div>
</div>
<hr>
</div>
</div>
<input class="btn btn-primary" type="submit" value="Add">
</form>
And the jquery:
let i = 1
$(document).ready(function() {
$(".eventBtn").click(function(e){
let id = e.target.id;
let f = "#add_form" + id
let c = "#cxc_form" + id
let old = $(f).clone()
old.find("select").each(function() {
this.name = this.name.replace('0', i)
this.id = this.id.replace('0', i)
})
old.find("input").each(function() {
this.name = this.name.replace('0', i)
this.id = this.id.replace('0', i)
})
$(old).appendTo(c);
i = i+1
});
});
And fastapi:
#app.post("/cxc")
async def add_cxc(id: int, request: Request, db: Session = Depends(get_db)):
form = await request.form()
print(form)
Does any one know why it is not giving me the data from the cloned elements. All I am getting in my request is
FormData([('area0', '1'), ('deg0', '1'), ('country0', '186'), ('yr0', '')])
My html file has a select, with three different options. If you select one it will display different inputs depending on what option you choose, but these inputs are required by default, and I can't send the form if I don't fill all the inputs.
function yesnoCheck(that) {
if (that.value == "1") {
document.getElementById("ifStudent").style.display = "block";
} else {
document.getElementById("ifStudent").style.display = "none";
}
if (that.value == "2") {
document.getElementById("ifAcademic").style.display = "block";
} else {
document.getElementById("ifAcademic").style.display = "none";
}
if (that.value == "3") {
document.getElementById("ifWorker").style.display = "block";
} else {
document.getElementById("ifWorker").style.display = "none";
}
}
<div class="select">
<select onchange="yesnoCheck(this);" name="school_role" required>
<option value="">--------</option>
<option value="1">Student</option>
<option value="2">Academic</option>
<option value="3">Employee</option>
</select>
</div>
<div id="ifStudent" style="display: none;">
<label class="label">Account number</label>
<input class="input" type="text" name="account_number" value="{{ studentform.account_number.value }}" placeholder="Account number">
<div class="help is-danger">
{% for error in studentForm.account_number.errors %}{{ error }}{% endfor %}
</div>
<div id="ifEmployee" style="display: none;">
<label class="label">Employee Number</label>
<input class="input" type="text" name="employee_number" value="{{ employeeForm.employee_number.value }}" placeholder="Employee number">
<div class="help is-danger">
{% for error in employeeForm.employee_number.errors %}{{ error }}{% endfor %}
</div>
<div id="ifAcademic" style="display: none;">
<label class="label">Academic number</label>
<input class="input" type="text" name="academic_number" value="{{ academicForm.academic_number.value }}" placeholder="Academic number">
<div class="help is-danger">
{% for error in academicForm.academic_number.errors %}{{ error }}{% endfor %}
</div>
Add required attribute to all inputs. I'm not confident in code style, but as a logical example:
<input ... name="account_number" required="{{school_role === 1}}" ... />
Add </div> to each section
Give each div a class of hide
Toggle the hide on change of the select
toggle the required
const ifs = [...document.querySelectorAll("[id^=if]")];
document.getElementById("school_role").addEventListener("change", function() {
const val = this.options[this.selectedIndex].textContent;
ifs.forEach(ifDiv => {
ifDiv.classList.toggle("hide", !ifDiv.id.includes(val))
const input = ifDiv.querySelector("input");
if (ifDiv.classList.contains("hide")) input.removeAttribute("required")
else input.setAttribute("required", true)
});
})
.hide {
display: none;
}
<div class="select">
<select name="school_role" id="school_role" required>
<option value="">--------</option>
<option value="1">Student</option>
<option value="2">Academic</option>
<option value="3">Employee</option>
</select>
</div>
<form>
<div id="ifStudent" class="hide">
<label class="label">Account number</label>
<input class="input" type="text" name="account_number" value="" placeholder="Account number">
<div class="help is-danger">
{% for error in studentForm.account_number.errors %}{{ error }}{% endfor %}
</div>
</div>
<div id="ifEmployee" class="hide">
<label class="label">Employee Number</label>
<input class="input" type="text" name="employee_number" value="" placeholder="Employee number">
<div class="help is-danger">
{% for error in employeeForm.employee_number.errors %}{{ error }}{% endfor %}
</div>
</div>
<div id="ifAcademic" class="hide">
<label class="label">Academic number</label>
<input class="input" type="text" name="academic_number" value="" placeholder="Academic number">
<div class="help is-danger">
{% for error in academicForm.academic_number.errors %}{{ error }}{% endfor %}
</div>
</div>
<input type="submit">
</form>
The mission is when I click on the plus button to add a new search input it has to add a new field with a plus button and removal button (it calls times-btn).
Everything works fine but when I click on the removal button the first one has created is removed only but when I click on any button else it doesn't work. so, How can I trigger the removal button that?
This screenshot explains the intended task.
search.html
<!-- Search formsets -->
<div class="search-field">
<h2 class="show"></h2>
<form method="get" id="main_search">
<div id="first_search_group" class="form-group row search_repeated search_group">
<div class="col-lg-2 d-inline p-2 word_repeated">
<label style="font-size: large; padding-top: 5px">Sentence or Word</label>
</div>
<!-- Filter -->
<div class="col-lg-2 d-inline p-2">
<select name="formsets_option" id="formsets_option" class="form-control">
{% if formsets_option == 'contains' %}
<option id="contains" value="contains" selected>contains</option>
{% else %}
<option id="contains" value="contains">contains</option>
{% endif %}
{% if formsets_option == 'start_with' %}
<option id="start_with" value="start_with" selected>start with</option>
{% else %}
<option id="start_with" value="start_with">start with</option>
{% endif %}
{% if formsets_option == 'is' %}
<option id="is" value="is" selected>is</option>
{% else %}
<option id="is" value="is">is</option>
{% endif %}
{% if formsets_option == 'end_with' %}
<option id="end_with" value="end_with" selected>end with</option>
{% else %}
<option id="end_with" value="end_with">end with</option>
{% endif %}
</select>
</div>
<div class="col-lg-4 d-inline p-2">
<input id="search_btn" type="text" class="form-control"
onkeyup="if (this.value != ''){document.getElementById('clear').hidden=false} else {document.getElementById('clear').hidden=true}"
placeholder="search" name="query" value="{{ request.GET.query }}">
</div>
<div class="col-lg-2 d-inline p-2">
<select name="verb_option" id="verb_option" class="form-control">
{% if verb_option == '' %}
<option value="" selected>Any POS</option>
{% else %}
<option value="">Any POS</option>
{% endif %}
{% if verb_option == 'Adj' %}
<option value="Adj" selected>Adjective</option>
{% else %}
<option value="Adj">Adjective</option>
{% endif %}
{% if verb_option == 'Adv' %}
<option value="Adv" selected>Adverb</option>
{% else %}
<option value="Adv">Adverb</option>
{% endif %}
{% if verb_option == 'Asp' %}
<option value="Asp" selected>Aspect Marker</option>
{% else %}
<option value="Asp">Aspect Marker</option>
{% endif %}
{% if verb_option == 'Cl' %}
<option value="Cl" selected>Classifier</option>
{% else %}
<option value="Cl">Classifier</option>
{% endif %}
{% if verb_option == 'Conj' %}
<option value="Conj" selected>Conjunction</option>
{% else %}
<option value="Conj">Conjunction</option>
{% endif %}
{% if verb_option == 'Det' %}
<option value="Det" selected>Determiner</option>
{% else %}
<option value="Det">Determiner</option>
{% endif %}
{% if verb_option == 'Idiom' %}
<option value="Idiom" selected>Idiom</option>
{% else %}
<option value="Idiom">Idiom</option>
{% endif %}
{% if verb_option == 'Intj' %}
<option value="Intj" selected>Interjection</option>
{% else %}
<option value="Intj">Interjection</option>
{% endif %}
{% if verb_option == 'Noun' %}
<option value="Noun" selected>Noun</option>
{% else %}
<option value="Noun">Noun</option>
{% endif %}
{% if verb_option == 'Num' %}
<option value="Num" selected>Number</option>
{% else %}
<option value="Num">Number</option>
{% endif %}
{% if verb_option == 'Ono' %}
<option value="Ono" selected>Onomatopoeia</option>
{% else %}
<option value="Ono">Onomatopoeia</option>
{% endif %}
{% if verb_option == 'Part' %}
<option value="Part" selected>Particle</option>
{% else %}
<option value="Part">Particle</option>
{% endif %}
{% if verb_option == 'Prep' %}
<option value="Prep" selected>Preposition</option>
{% else %}
<option value="Prep">Preposition</option>
{% endif %}
{% if verb_option == 'Pro' %}
<option value="Pro" selected>Pronoun</option>
{% else %}
<option value="Pro">Pronoun</option>
{% endif %}
{% if verb_option == 'Pu' %}
<option value="Pu" selected>Punctuation</option>
{% else %}
<option value="Pu">Punctuation</option>
{% endif %}
{% if verb_option == 'SFP' %}
<option value="SFP" selected>Sentence-Final Particle</option>
{% else %}
<option value="SFP">Sentence-Final Particle</option>
{% endif %}
{% if verb_option == 'Verb' %}
<option value="Verb" selected>Verb</option>
{% else %}
<option value="Verb">Verb</option>
{% endif %}
{% if verb_option == 'X' %}
<option value="X" selected>Unclassified</option>
{% else %}
<option value="X">Unclassified</option>
{% endif %}
</select>
</div>
<div style="align-self: center;font-size: 14px;color: #2f855a;" class="btn-plus col-lg-1 d-inline">
<div class="fa fa-plus d-inline"></div>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="submit" name="main_search" value="Search" class="btn btn-primary">
<a href="{% url 'search:search' %}" style="color: #c53030; margin-left: 10px;border: 0; background-color: transparent;cursor: pointer" id="clear" hidden>Clear Search</a>
</div>
</div>
</form>
</div>
search.html
<script type="text/javascript">
$(document).ready(function()
{
let btn_plus = $(".btn-plus");
let search_group = $(".search_group")
let search_form = $("#main_search")
let create_times_parent = document.createElement("div")
create_times_parent.classList.add("btn-times", "col-lg-1", "d-inline")
let create_times = document.createElement("div")
create_times.classList.add("fa", "fa-times", "d-inline")
create_times_parent.appendChild(create_times)
function add_inc()
{
btn_plus.click(function ()
{
$("div.search_group:first-of-type").after(search_group.clone(true, true));
search_group.addClass('created')
search_group.append(create_times_parent)
if ($(this).data('clicked', true)) {
create_times_parent.onclick = function ()
{
$(this).parent('.created').remove()
console.log("clicked")
}
}
});
}
add_inc()
});
</script>
Your divs are dynamically generated so just bind it with static elements which are already present inside your DOM.
Also , I have move whole remove event outside function and then have use $(document).on("click", ".remove", function() {.. this will trigger your remove button then use .closest(".created").remove() to remove whole div.
Demo Code :
$(document).ready(function() {
let search_group = $(".search_group")
let search_form = $("#main_search")
let create_times_parent = document.createElement("div")
create_times_parent.classList.add("btn-times", "col-lg-1", "d-inline")
let create_times = document.createElement("div")
//added on extra class here..
create_times.classList.add("fa", "fa-times", "d-inline", "remove")
create_times_parent.appendChild(create_times)
$(document).on('click', '.btn-plus', function() {
$("div.search_group:first-of-type").after(search_group.clone(true, true));
search_group.addClass('created')
search_group.append(create_times_parent)
});
//onclick of remove..
$(document).on("click", ".remove", function() {
$(this).closest('.created').remove() //get closest outer div
console.log("clicked")
})
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="search-field">
<h2 class="show"></h2>
<form method="get" id="main_search">
<div id="first_search_group" class="form-group row search_repeated search_group">
<div class="col-lg-2 d-inline p-2 word_repeated">
<label style="font-size: large; padding-top: 5px">Sentence or Word</label>
</div>
<!-- Filter -->
<div class="col-lg-2 d-inline p-2">
<select name="formsets_option" id="formsets_option" class="form-control">
<option id="contains" value="contains" selected>contains</option>
<option id="start_with" value="start_with" selected>start with</option>
<option id="is" value="is" selected>is</option>
<option id="end_with" value="end_with" selected>end with</option>
</select>
</div>
<div class="col-lg-4 d-inline p-2">
<input id="search_btn" type="text" class="form-control" onkeyup="if (this.value != ''){document.getElementById('clear').hidden=false} else {document.getElementById('clear').hidden=true}" placeholder="search" name="query" value="{{ request.GET.query }}">
</div>
<div class="col-lg-2 d-inline p-2">
<select name="verb_option" id="verb_option" class="form-control">
<option value="" selected>Any POS</option>
</select>
</div>
<div style="align-self: center;font-size: 14px;color: #2f855a;" class="btn-plus col-lg-1 d-inline">
<div class="fa fa-plus d-inline"></div>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="submit" name="main_search" value="Search" class="btn btn-primary">
<a href="{% url 'search:search' %}" style="color: #c53030; margin-left: 10px;border: 0; background-color: transparent;cursor: pointer" id="clear" hidden>Clear Search</a>
</div>
</div>
</form>
</div>
I have two drop down list inputs ,both of them comes from datalist , i want that base on the input that the user choose, to filter the other input to show only relevant results .
I am rendering the data from python back to HTML page
The data contains company name and bank account number,
So i want base on the company that user choose to show only the relevant account to the selected company
<form id="the_form" method="POST">
{% csrf_token %}
From:
<input name="start_date" class="datepicker" type="date" value={{start_date}}/>
To:
<input name="end_date" class="datepicker" type="date" value={{end_date}}/>
<input type="text" list='List_of_Companies' data-search-in="Company" id="Input1" name="Companyname" placeholder="Choose a Company" value="{{ Company}}"/>
<input type="text" list='List_of_Accounts' data-search-in="Account" id="Input2" name="Accountname" placeholder="Choose an Account ID" value="{{ Account_Id}}"/>
<br> <br>
<button name="action" type="submit" id="showccounts" value="show">Show</button>
<button name="action" type="submit" value="download">Download</button>
<datalist id="List_of_Companies">
<select id="filenamelist" size="5" class="select">
{% for Company in info_list %}
<option value="{{ Company.3 }}">{{ Company.3 }}</option>
{% endfor %}
</select>
</datalist>
<datalist id="List_of_Accounts">
<select id="filenamelist" size="5" class="select">
{% for Company in info_list %}
<option value="{{ Company.0 }}">{{ Company.3 }}</option>
{% endfor %}
</select>
</datalist>
</form>
{% load staticfiles %}
<div id="loading" style="width:300px;height:300px;display:table-cell; vertical-align:middle; text-align:center">
<img src="{% static "app/images/Loading_icon.gif" %}" style="margin:auto">
</div>
<table id="theTable" hidden>
<thead>
<tr>
{% for c in columns %}
<th>{{ c }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for r in rows %}
<tr>
{% for c in r %}
<td>{{ c }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
{% block scripts %}
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
I have a following code in jQuery:
$(".edit-trigger").on("click", function () {
url = $(this).data('url');
$.get(url, function(data) {
$("#modal .modal-content").html(data);
});
});
and it is loading following code (data) into modal window:
<form id="personal_info_form" class="modal-form">
<input type="hidden" value="{{ csrf_token }}" name="csrfmiddlewaretoken">
<div class="modal-content">
{% for field in form %}
<div class="row">
<div class="input-field col s12">
{{ field }}
<label for="{{ field.id }}" data-error="wrong">{{ field.label }}</label>
</div>
</div>
{% endfor %}
</div>
<div class="modal-footer">
<button class="modal-action modal-close">Anuluj</button>
<button type="submit">Akceptuj</button>
</div>
</form>
<script>
M.updateTextFields();
</script>
The issue is that script in loaded code is not always executed. Is it possible to ensure execution of that script?