Html / jquery multiple forms submit - javascript

I am working on Django File Sharing Project and in file view on click on file preview div it will pop-up modal with description of file . I have problems in IDing multiple forms
FileView.html
<div class="parent">
<div class="child" onclick="fo()">
<form class="form" method="post" action="django-script.py">
<h5 > File.jpg</h5>
<input type="hidden" name="file" value="file.jpg">
<h6 class="title">Image</h6>
<img class="image" src="/images/icons/file.png" >
</form>
</div>
<div class="child" onclick="fo()">
<form class="form" method="post" action="django-script.py">
<h5 > File.pdf</h5>
<input type="hidden" name="file" value="file.pdf">
<h6 class="title">PDF</h6>
<img class="image" src="/images/icons/pdf.png" >
</form>
</div>
<div class="child" onclick="fo()">
<form class="form" method="post" action="django-script.py">
<h5 > File.csv</h5>
<input type="hidden" name="file" value="File.csv">
<h6 class="title">CSV FILE</h6>
<img class="image" src="/images/icons/file.png" >
</form>
</div>
</div>
script
function fo()
{
document.querySelectorAll(".child")].forEach(child => {
const forms= child.querySelector(".form")
forms.submit();
})
}
It works well only for 1 div I dont know how to make it for all div elements
Original Django Code
ViewFile.html
<div class="parent">
{% for f in file %}
<div class="child" onclick="fo();">
<form class="form" method="post" action="{% url 'fileview' %}">
{% csrf_token %}
<h5 >{{f.title}}</h5>
<input type="hidden" name="file" value="{{f.filename}}">
<h6 class="title">{{f.filename}}</h6>
<img class="image" src="{% static '/images/icons/file.png' %}" >
</form>
</div>
{% endfor %}
</div>
Views.py
def fileview(request):
global loginFlag,loginUser
if request.method == 'POST':
fil=request.POST['file']
about=Transaction.objects.filter(filename=fil)
emp=about[0].userid
aname=Employee.objects.filter(emp_id=emp)[0].name
print(about)
files=Transaction.objects.all()
name=loginName
context={'files':files,'name':name,'about':about,'aname':aname}
return render(request,'detailedview.html',context)
else:
file=Transaction.objects.all()
name=loginName
context={'file':file,'name':name}
return render(request, 'viewfile.html',context)
I think the issue is in HTML multiple form class. Any solutions will be of great help
Thanks inadvance

All your form tags have the same ID (which isn't what you want) and your onclick was instructing JS to submit the first matching ID, hence it was submitting the first form only. Instead make it a relative association. Use a JS function and pass this which will refer to the container element. Then in the function find the form inside the element and submit that.
<div class="parent">
{% for f in file %}
<div class="child" onclick="showFile(this)">
<form method="post" action="{% url 'fileview' %}">
{% csrf_token %}
<h5 >{{f.title}}</h5>
<input type="hidden" name="file" value="{{f.filename}}">
<h6 class="title">{{f.filename}}</h6>
<img class="image" src="{% static '/images/icons/file.png' %}" >
</form>
</div>
{% endfor %}
<script>
showFile(div) {
div.querySelector('form').submit()
}
</script>

Related

jQuery form submit not triggering

I have 2 forms in one html file(Not nested). Each do their own thing and do not rely on each other. The problem i'm currently facing is that $(form).submit((event)=>{code}) only works on:
<form id="mainForm" action='' method="POST" enctype="multipart/form-data">
{% csrf_token %}
<!--Cover image-->
<ul class="error" id="coverImageLink_errors"></ul>
<div class="cover-img">
{{ mainForm.coverImageLink|add_class:'actual-img' }}
<img src="#" id="cover" alt="Your image" style="color: black;">
</div>
<!--Music data part-->
<div class="music-data">
<ul class="error" id="albumName_errors"></ul>
<label for="{ mainForm.albumName.id_for_label }">title</label><br>
{{ mainForm.albumName }} <br><br>
</div>
<input id='albumSubmit' type="submit" value="Next" class="main-form-upload">
</form>
<script>
$('#mainForm').submit((event)=>{
event.preventDefault();
console.log('AJAX CALLED FOR MAIN FORM');
});
</script>
But not on:
<form id="AdvancedForm" action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<ul class="last-step-error" id="advancedForm.non_field_errors"></ul>
<section id="main-section">
<!-- compresso page -->
<div id="compresso-page">
<div class="parent">
<div class="name">0. Hello world</div>
<ul class="pre-errors">
<li>Video file is not supported</li>
<li>+2 more</li>
</ul>
</div>
</div>
</section>
<div style="height: 20px;"></div> <!-- prevents collision with button -->
<input type="submit" value="Release" onclick="alert('Advanced form submit pressed')">
</form>
<script>
$('#AdvancedForm').submit((event)=>{
event.preventDefault();
console.log('AJAX CALLED FOR ADVANCED FORM')
const url = '{% url "validate-upload-collection" %}'
})
</script>
I see AJAX CALLED FOR MAIN FORM but not AJAX CALLED FOR ADVANCED FORM.
The advanced form is display='none' by default
console.log(document.getElementById('AdvancedForm')) returns here
If you are confused with {{ something }}, it's just some django(Web framework) variable syntax. Those variables will be filled in on the server side so that is not present in the html.
It might be that onclick="alert('Advanced form submit pressed')" interferes with your handler. Try to remove that from the submit button.
One other thing I see is that the second form has no real fields? That might be another thing. Try adding <input type="text" name="test" />

html onclick to load external javascript not working

I am trying to load an external javascript from a html input button. However when I click on the button I get no output or response. I do get a message in console that the script has been loaded though.
HTML:
<div class="split left">
<fieldset class="Receiver Commands">
<legend>Receiver Commands</legend>
<input type="button" value="click me" id="clickMe" onclick="serverStart()" />
<script type="text/javascript" src="{%static 'scripts/ServerResponse.js' %}">
</script>
<form method="post">
</form>
<div id="testtaskbox" class="testtaskbox">
{% csrf_token %}
</div>
</fieldset>
<fieldset class="receiverResponse">
<legend>Receiver Response</legend>
<div class="receiverText">
<textarea id ="response" class="textarea">Digdebugv2 1.11
{{responseContext}}
</textarea>
</div>
</fieldset>
</div>
Javascript:
serverStart()
function serverStart () {
document.getElementById('reponse').innerHTML = '123bob'
console.log('ServerResponse started')
}
Your document.getElementById('reponse').innerHTML = '123bob'
'response' was not correct spelled.
Replace your current code with this and it will work.
function serverStart () {
document.getElementById('response').innerHTML = '123bob'
console.log('ServerResponse started')
}
serverStart();
<div class="split left">
<fieldset class="Receiver Commands">
<legend>Receiver Commands</legend>
<input type="button" value="click me" id="clickMe" onclick="serverStart()" />
<script type="text/javascript" src="{%static 'scripts/ServerResponse.js' %}">
</script>
<form method="post">
</form>
<div id="testtaskbox" class="testtaskbox">
{% csrf_token %}
</div>
</fieldset>
<fieldset class="receiverResponse">
<legend>Receiver Response</legend>
<div class="receiverText">
<textarea id ="response" class="textarea">Digdebugv2 1.11
{{responseContext}}
</textarea>
</div>
</fieldset>
</div>

Is it possible that jquery .html() method loads code partialy?

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?

Django form is not displaying

I am new to django forms and while trying to design an HTML form, I notice that the django form blocks are not displaying. Below are the codes:
<body> tag of index.html:
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-login">
<div class="panel-heading">
<div class="row">
<div class="col-xs-6">
Login
</div>
<div class="col-xs-6">
Register
</div>
</div>
<hr>
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
{% block login_content %}
{% endblock %}
{% block register_content %}
{% endblock %}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
login.html which goes into the {% block login_content %}
{% extends 'index.html' %}
{% block login_content %}
<form id="login-form" action="{% url 'authentication:user_login' %}" role="form" style="display: block;" method="POST">
{% csrf_token %}
<label for="username">Username:</label>
<input id="username" type="text" name="username" placeholder="Enter Username" tabindex="1" class="form-control">
<label for="password">Password:</label>
<input id="password" type="password" name="password" tabindex="=2" class="form-control" placeholder="Password">
<button type="submit" class="btn btn-success">Login</button>
</form>
{% endblock %}
register.html that goes into the {% block register_content %}
{% extends 'index.html' %}
{% block register_content %}
<form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST">
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<input type="submit" name="" value="Register">
</form>
{% endblock %}
On my UI, the {{ user_form.as_p }} and the {{ profile_form.as_p }} does not appear at all.
When i inspect the console of my UI, the html does not even pick up the following line from the register.html:
<form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST">
Here is the login.js which is responsible for the UI interactivity:
$(function() {
$('#login-form-link').click(function(e) {
$("#login-form").delay(100).fadeIn(100);
$("#register-form").fadeOut(100);
$('#register-form-link').removeClass('active');
$(this).addClass('active');
e.preventDefault();
});
$('#register-form-link').click(function(e) {
$("#register-form").delay(100).fadeIn(100);
$("#login-form").fadeOut(100);
$('#login-form-link').removeClass('active');
$(this).addClass('active');
e.preventDefault();
});
});
EDIT:
Here is my views.py:
def user_login(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('homepage')) # main page if login is successful
else:
return HttpResponse("ACCOUNT NOT ACTIVE")
else:
print('Someone tried to log in and failed')
print('Username: {}, password, {}'.format(username, password))
return HttpResponse('Invalid login details supplied')
else:
return render(request, 'authentication/login.html', {})
def register(request):
registered = False
if request.method == "POST":
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print(user_form.errors, profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
return render(request, 'authentication/register.html',
{
'user_form': user_form,
'profile_form': profile_form,
'registered': registered
})
Okay, it seems like it is impossible to have a single page display both the templates. Is there anyway to get it done?
In your register.html,
<form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST">
You are setting style="display: none;", so obviously the form won't show up.
EDIT: I am not sure about the feasibility of showing two different forms in the same page.

Remove form from DOM using JavaScript

I have three radio buttons.. each radio buttons on click have an independent form that appears. I need to remove form from DOM when i click on a radio button. and there are a third one not ready yet. When i click on the first radio button only its form appears, the other two are removed from DOM. Same for other.
I don't have a good idea about JavaScript.
Html:
<div class="page-header">
<h1>Backtesting{% if form.instance.pk %}: {{form.instance.title}} {% endif %}</h1>
</div>
<div class="row">
<div class='col-md-9'>
<form action="{% url "backtest" %}" method='POST' role='form' id='form'>
{% csrf_token %}
<div id="tabs">
<input type="radio" name="tabs" value="first" id="toggle-tab1" checked="checked" />
<label for="toggle-tab1">Long</label>
<input type="radio" name="tabs" value="second" id="toggle-tab2" />
<label for="toggle-tab2">Short</label>
<input type="radio" name="tabs" value="third" id="toggle-tab3" />
<label for="toggle-tab3">Long and Short</label>
<div id="tab1" class="tab" >
{% include 'tags/parameters_form.html' %}
<br />
{% if user.is_authenticated %}
<input type='submit' id='run' value='Run' class='btn btn-default'>
{% if user.profile.is_active %}
Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'>
{% else %}
<p>
Expired account! you need to reactivate in order to save parameters.
</p>
{% endif %}
{% else %}
Please login in order to Run backtesting!
</br>
Our system needs your email in order to notify you once one or more of your simulations are done. This is a safer way for you to keep track of your previous simulations (/jobs).
{% endif %}
</div>
<div id="tab2" class="tab" >
{% include 'tags/parameters_backtest_form.html' %}
<br />
{% if user.is_authenticated %}
<input type='submit' id='run' value='Run' class='btn btn-default'>
{% if user.profile.is_active %}
Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'>
{% else %}
<p>
Expired account! you need to reactivate in order to save parameters.
</p>
{% endif %}
{% else %}
Please login in order to Run backtesting!
</br>
Our system needs your email in order to notify you once one or more of your simulations are done. This is a safer way for you to keep track of your previous simulations (/jobs).
{% endif %}
</div>
</div>
</form>
</div>
</div>
{% endblock %}
<form action="{% url "backtest" %}" method='POST' role='form' id='form'>
{% csrf_token %}
<div id="tabs">
<input type="radio" name="tabs" value="first" id="toggle-tab1" checked="checked" />
<label for="toggle-tab1">Long</label>
<input type="radio" name="tabs" value="second" id="toggle-tab2" />
<label for="toggle-tab2">Short</label>
<input type="radio" name="tabs" value="third" id="toggle-tab3" />
<label for="toggle-tab3">Long and Short</label>
<div id="tab1" class="tab" >
<!-- first form will show when page load -->
<fieldset id="first" class="toggle">
{% include 'tags/parameters_form.html' %}
</fieldset>
<fieldset disabled id="second" class="toggle">
{% include 'tags/parameters_form.html' %}
</fieldset>
<fieldset disabled id="third" class="toggle">
{% include 'tags/parameters_form.html' %}
</fieldset>
.....
Js
$('[name="tabs"]').click(function(){
$('.toggle').prop("disabled", true);
var val = $(this).val()
$('#'+val).prop('disabled', false);
});
When you add disabled attr in fieldset then fieldset inner input field data will not post in form that means field will not work in fieldset tag if it have disabled attribute. So you can show specific form in each condition and add attribute disable in fieldset tag that inner field data will not post.
Read about https://www.w3schools.com/tags/att_fieldset_disabled.asp
If you cannot change DOM elements and add a class there my answer would be to attach a event listener to each of the buttons:
'use strict';
var button1 = document.getElementById('toggle-tab1'),
button2 = document.getElementById('toggle-tab2'),
button3 = document.getElementById('toggle-tab3');
button1.addEventListener('click', function () {
// Code that takes it away (hide DOM elements or whatever you need)
});
On a side note a better approach would be to add a function to all of the radio inputs and then based on the ID or value of the input radio you can alter the behavior:
<input type="radio" name="tabs" onclick="handleClick(this)" value="first" id="toggle-tab1" checked="checked" />
Then you can have a function:
function handleClick (e) {
if (e.id == 'toggle-tab1') {
// Code that takes it away (hide DOM elements or whatever you need)
}
};
function onclick(e){
var tab = document.getElementById('toggle-tab1');
tab.style.visibility = "hidden";
}
button1.addEventListener('click', onclick(e))
This should do the trick!
Problem is resolved with :
<input type="radio" name="tabs" value="first" id="toggle-tab1" {% if strategy == 'l' %} checked="checked"{% endif %} />
<label for="toggle-tab1">Long</label>
<input type="radio" name="tabs" value="second" id="toggle-tab2" {% if strategy == 's' %} checked="checked" {% endif %} />
<label for="toggle-tab2">Short</label>
<div id="tab1" class="tab" >
<form action="{% url "backtest" %}" method='POST' role='form' id='form'>
{% csrf_token %}
<input type="hidden" name="tabs" value="first" id="toggle-tab1" checked="checked" />

Categories