Get which button is clicked at server when u submit via onclick - javascript

I have a form with two submit buttons, I am validating the form with jquery validate and submitting it. I want to know at server which button was clicked.
Form
<form class="dp-blog-form" action="{% url 'price_assessment_section_1' component.id %}" method="post"> {% csrf_token %}
{{ form.as_p }}
<!-- FORM SUBMIT BUTTONS-->
<button type="submit" > Save&Home</button>
<button type="submit" > Save&Next</button>
</form> <!-- end form-->
JS
$('.dp-blog-form button[type="submit"]').on('click', function (e) {
e.preventDefault();
if ($('.dp-blog-form').valid()) {
unbindPageLeaveEvent();
disableButton($(this));
$('.dp-blog-form').submit();
}
});
How to get the button information at the sever?

You can add a hidden field in the form, in the line just above the submit, which will be sent along:
$('.dp-blog-form').append('<input type="hidden" name="theButton" value="'+ this.textContent +'"/>');

set value and name for button, you can access it from server.
<form class="dp-blog-form" action="{% url 'price_assessment_section_1' component.id %}" method="post"> {% csrf_token %}
{{ form.as_p }}
<!-- FORM SUBMIT BUTTONS-->
<button type="submit" name='action' value='save_home'> Save&Home</button>
<button type="submit" name='action' value='save_next' > Save&Next</button>
</form> <!-- end form-->

we can add hidden field in a form:
<form class="dp-blog-form" action="{% url 'price_assessment_section_1' component.id %}" method="post"> {% csrf_token %}
{{ form.as_p }}
<!-- FORM SUBMIT BUTTONS-->
<input type="hidden" name="button_clicked" />
<button type="submit" name='action' value='save_home'> Save&Home</button>
<button type="submit" name='action' value='save_next' > Save&Next</button>
</form> <!-- end form-->
and in JS please set the value of clicked button into hidden field. then you will able to get the value of clicked button on server ...

Related

Datepicker allow blank date submission

I'm using datepicker with Django:
<form method="POST" action="{% url 'approval_date_action_modal' cpname=full_id %}"> {% csrf_token %}
<div class="input-group date" id='grm_date' data-provide="datepicker" data-date-format="yyyy-mm-dd" data-date-title="Approval Date" data-date-autoclose="true" data-date-end-date="0d" data-date-start-date="2018-11-14">
{{ approval_form.approval_date }}
<div class="input-group-addon">
<span class="material-icons md-12">date_range</span>
</div>
</div>
<br/>
<input class="btn btn-primary" type="submit" value="Confirm" />
</form>
when users clear the date and try to submit a blank date which corresponds to null in database, a warning "Please fill out this field" will pop up and cancel the submission.
Is there a simple way we can allow submission of a blank date in addition to the normal date of the stated format?

If else statement in django template based on request.session data

I'm trying to prevent/allow the user from clicking a button depending on whether a key is present in the request.session data.
It works for blocking it, but once the key is added to the session, that isn't reflected on the webpage/template and the key remains blocked. I presume I'll have to do this in JS but I'm not sure how to approach it. Any ideas?
Thanks
{% if choices not in request.session %}
<form class="submit-form" action="{% url 'search' %}" method="post" onsubmit="return false;">
{% csrf_token %}
<input type="submit" class="show-more-button cunt" style="margin-left: 5px" name="mybtn"
value="Search" data-bs-toggle="popover"
data-bs-placement="right" data-bs-trigger="focus"
data-bs-content="Please select one or more ingredient">
</form>
{% else %}
<form action="{% url 'search' %}" method="post">
{% csrf_token %}
<input type="submit" class="show-more-button" style="margin-left: 5px" name="mybtn"
value="Search">
</form>
{% endif %}
if request.POST.get('button_color') == 'green':
selected_ingredients = request.session.get('choices', [])
selected_ingredients.insert(len(selected_ingredients), ingredients_name)
request.session['choices'] = selected_ingredients
request.session.modified = True

Creating input fields inside a form using JavaScript

I'm working on a quiz app and want to generate a number of input fields representing the answers based on the value that the user types.
I'm using a button named "create" to do that Using JavaScript, but when clicking the button it submits the form.
Please Check the two images below.
Input
Output
HTML Code
{% load static %}
{% block body %}
<button class="btn btn-primary new">Add a question</button>
<form class="question" method="POST" style="display: none">
{% csrf_token %}
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" class="form-control" id="title" placeholder="Question title">
</div>
<div class="form-group" id="answers_num">
<label for="exampleInputPassword1">Number of answers</label>
<input type="number" class="form-control" id="ans_number">
<button class="create_answers">Create</button>
</div>
<div class="form-group">
{% comment %} Generated input fields {% endcomment %}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% block script %}
<script src="{% static 'mcq/index.js' %}"></script>
{% endblock %}
{% endblock %}```
JS code
document.querySelector(".new").addEventListener("click", ()=> {
document.querySelector(".question").style.display = 'block';
document.querySelector("#create_answers").addEventListener("click", ()=> {
answers = this.value;
console.log(answers);
// Create input fields
for (let i = 0; i < answers; i++) {
input = document.createElement("input");
input.classList.add('form-control');
answersDiv = document.querySelector("#answers").appendChild(input);
}
})
})```
You need to explicitly set the type of the button, like
<button class="create_answers" type="button">Create</button>
in order to avoid submitting the form upon click.

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" />

Modelformset with dynamic form addition saves only the first form

I have two forms on one page, each with its own submit button. With JS script I can dynamically add a new formset for each of the two form. I am faced with a situation where I can add as many new forms as I want for the form that is displayed first on the page and all are saved. For the second forms list, only the first form from the formset list is saved.
template.html
<form method="post" action="">{% csrf_token %}
{{ formset_planguage.management_form }}
<div id="form_set_lang">
{% for form in formset_planguage.forms %}
{{form.non_field_errors}}
{{form.errors}}
<table class='no_error'>
{{ form }}
</table>
{% endfor %}
</div>
<input type="button" value="Add More" id="add_more_lang">
<div id="empty_form_lang" style="display:none">
<table class='no_error'>
{{ formset_planguage.empty_form }}
</table>
</div>
<input class='btn btn-primary' type="submit" name="language" value="Submit"/>
</form>
<form method="post" action="">{% csrf_token %}
{{ formset_framework.management_form }}
<div id="form_set_framework">
{% for form in formset_framework.forms %}
{{form.non_field_errors}}
{{form.errors}}
<table class='no_error'>
{{ form }}
</table>
{% endfor %}
</div>
<input type="button" value="Add More" id="add_more_framework">
<div id="empty_form_framework" style="display:none">
<table class='no_error'>
{{ formset_framework.empty_form }}
</table>
</div>
<input class='btn btn-primary' type="submit" name="framework" value="Submit"/>
</form>
<script>
$('#add_more_framework').click(function() {
var form_idx = $('#id_form-TOTAL_FORMS').val();
$('#form_set_framework').append($('#empty_form_framework').html().replace(/__prefix__/g, form_idx));
$('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});
</script>
<script>
$('#add_more_lang').click(function() {
var form_idx = $('#id_form-TOTAL_FORMS').val();
$('#form_set_lang').append($('#empty_form_lang').html().replace(/__prefix__/g, form_idx));
$('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});
</script>
Your two forms are like <form method="post" action=""> so the destination is always the same page, so Django will handle both forms the same way. If in your page you handle in the POST the values of the first form, the second will be handled like it's the first form.
The best solution is to send one "big" form with all your fields named differently in the first "group" and the second "group", and read only either the first "group" or if it's empty, the second "group".
The other solution is to send the second form to a different url.

Categories