I have an html template that I use with my Django website code. In the template are a couple of forms. Two of the forms are datefields and I have a confirm popup that is activated on submission if the user fills them in. I wanted the popup to exit the form submission and return to the page if the user clicks 'cancel', and to continue submitting the form if the user clicks 'ok'.
The confirm popup shows up correctly but the form submission continues no matter what the user clicks. How do I change it so that the form submission exits if the user clicks 'cancel'?
Javascript looks like this:
<script type="text/javascript">
var checkFields = ["SPAN_START","SPAN_END"];
function checkForm( theForm ) {
for (i in checkFields ) {
var fieldName = checkFields[ i ];
var theField = theForm[ fieldName ];
if ( theField.value ) {
var retVal = confirm("Are you sure you want to specify a date?");
if (retVal == true){
theField.submit()
return true;
} else {
return false;
}
}
}
}
</script>
The html where it is used looks like this:
<form action="/InterfaceApp/Nominal_Request/" method="post" class="form" onsubmit="checkForm( this )">
{% csrf_token %}
<div class="panel-body text-center">
{% bootstrap_form form_span_start %}
{% bootstrap_form form_span_end %}
{% buttons %}
<button type="submit" class="btn btn-primary center-block" value="Submit" name="Range">
{% bootstrap_icon "fire" %} Generate Range of Requests
</button>
{% endbuttons %}
</div>
</form>
Can anyone tell me how to cancel the submission of the form if the user clicks 'cancel'??
Much appreciated.
You have to return the value of the function to the inline event handler
onsubmit="return checkForm( this )"
preferably you wouldn't use inline event handlers at all, but addEventListener instead.
Related
We have a Shopify website (Dawn theme) and we added some custom attribute fields on cart page which is associated with the product added to cart.
For showing the attribute fields, below is the code I'm using in the cart page file:
{% for variable in (1..item.quantity) %}
<div class="user_web_info">
<div class="cart-attribute__field">
<label for="website-name{{variable}}">Website Name*</label>
{% capture attributename %}Website Name{{variable}}{% endcapture %}
<input type="text" aria-required="true" required="required" class="required" data-name="Website Name{{variable}}" id="website-name{{variable}}" name="attributes[Website Name{{variable}}]" value="{{ cart.attributes[attributename] }}">
</div>
<div class="cart-attribute__field">
<label for="website-url{{variable}}">Website URL*</label>
{% capture attributeurl %}Website URL{{variable}}{% endcapture %}
<input type="text" aria-required="true" required="required" class="required" data-name="Website URL{{variable}}" id="website-url{{variable}}" name="attributes[Website URL{{variable}}]" value="{{ cart.attributes[attributeurl] }}">
</div>
</div>
{% endfor %}
I got the code for fields from this article:
https://community.shopify.com/c/online-store-2-0/dawn-theme-add-custom-fields-in-cart-page-and-show-results-in/td-p/1410437
I'm facing an issue with the validation of these fields when clicking checkout button on the cart page. Default HTML validation is showing in the field when clicking checkout without filling the fields, but the user is immediately redirecting to checkout page after that.
I tried to use simple jquery / javascript code as mentioned in these articles for preventing the form submission when validation happens. But it is not working:
https://community.shopify.com/c/technical-q-a/how-to-prevent-login-form-submit/td-p/1787161
https://community.shopify.com/c/shopify-apis-and-sdks/help-needed-validation-function-for-add-to-cart-form-submission/td-p/261161
I implemented the validation code in a separate js file and included it in theme.liquid file.
I searched a lot for finding a solution, but couldn't find it yet. I even used an App here: https://apps.shopify.com/customized-attribute
I need the validation for the checkbox also.
I figured out the issue here
I changed the checkout button from type="submit" to type="button" and changed the name attribute of checkout button to "checkout1". I'm not sure how these things affecting the form submission, but i had to do these.
Then I commented out these default form submission code in the cart page footer file:
document.querySelector('#checkout').addEventListener('click', function(event) {
document.querySelector('#cart').submit();
});
Also implemented the below validation code in custom js file:
document.querySelector('#checkout').addEventListener('click', function(event) {
event.preventDefault();
let errors = 0;
document.querySelectorAll('input.required').forEach((input) => {
let val = input.value;
console.info(val.length);
if(val.length == 0){
errors = errors + 1;
}
});
if(errors > 0){
alert("Please fill all the required fields.");
return false;
}
else if(!document.querySelector('#disclmr-chk').checked) {
alert("Please check the checkbox.");
return false;
}else{
document.querySelector('#checkout').setAttribute('name', 'checkout');
document.querySelector('form#cart').submit(); }});
With Django I generate a list of items, with the number of them.
To be more convenient, I would like to add a plus and a minus button.
I found a simple solution, but when I try to put this in my form with the POST method, if click the page refresh or POST ?
I don't want to refresh the page every time, I have a validate button and all the value will be treat in one time.
<form class"form-inline" action="{% url 'stock:stock' %}"method="post" >{% csrf_token %}
{% for stock in stocks %}
<div>
<button id="minusButton">-</button>
<input type="number" name="stock" id="stock" value="{{stock.stock}}" >
<button id="plusButton">+</button>
</div>
{% endfor %}
</form>
<script>
textInput = document.querySelector('#numberInput');
plusButton = document.querySelector('#plusButton');
minusButton = document.querySelector('#minusButton');
plusButton.onclick = () => textInput.value = parseInt(textInput.value) + 1;
minusButton.onclick = () => textInput.value = parseInt(textInput.value) - 1;
</script>
If anyone know how to manage?
every time I press submit button page gets reloaded.I have included preventdefault on submit.But it is not working.
Please help me.
This is part of html code .
Every time on submit I got redirected to another page.
I don't want page to reload. How to fix this.
<form id='form' method="POST">
{% csrf_token %}
{{form.as_p}}
<input type='hidden' id='myusername' value='{{user}}'>
<input type="submit" class='btn btn-primary'>
</form>
{% block script %}
<script src='https://cdnjs.cloudflare.com/ajax/libs/reconnecting-websocket/1.0.0/reconnecting-websocket.js'></script>
<script>
var loc=window.location
var wsStart='ws://'
var formData=$("#form")
var me=$("#myusername").val()
var Holder=$("#items")
var msgInput=$("#id_message")
if(loc.protocol=='https:'){
wsStart='wss://'
}
var endpoint=wsStart + loc.host + loc.pathname+'/'
var socket=new ReconnectingWebSocket(endpoint)
socket.onmessage=function(e){
console.log('message',e)
var Data=JSON.parse(e.data)
chatHolder.append('<li>'+Data.message+' via '+Data.username+'</li>')
}
socket.onopen=function(e){
console.log('open',e)
formData.submit(function(event){
event.preventDefault()
var msgText=msgInput.val()
var finalData={
'message':msgText
}
socket.send(JSON.stringify(finalData))
formData[0].reset()
})
}
socket.onerror=function(e){
console.log('error',e)
}
socket.onclose=function(e){
console.log('close',e)
}
</script>
{% endblock %}
store the content from your form in a context dict then pass it to the new page maybe?
I have a function that currently runs whenever the user clicks/tabs out of the employee_number field. I would like it to run whenever the length of the numbers entered is equal to 6, without having to leave the field, since when I try using the tab, it conflicts with loading the next field which is a drop-down that is part of the function ran.
I tried by running it using .change and putting the constraint within the function, but it did not work and I don't know what else to try.
enter_exit.html
{% extends "base.html" %}
{% load core_tags staticfiles %}
{% block main %}
<form id="warehouseForm" action="" method="POST" data-employee-activity-lookup-url="{% url 'operations:employee_activity_search' %}" novalidate >
{% csrf_token %}
<div>
<div>
<div id="employee-name" style="margin-bottom: 10px"> </div>
<label>Employee #</label>
{{ form.employee_number }}
</div>
<div=>
<label>Work Area</label>
{{ form.work_area }}
</div>
<div style="display: none" id="my-hidden-div">
<label>Station</label>
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button>Enter Area</button>
<button>Exit Area</button>
</div>
</div>
</form>
<script>
// Grab the employee name and their current active work log (if any)
$(document).on('blur', "#{{ form.employee_number.id_for_label }}", function(){
var url = $("#warehouseForm").attr('data-employee-activity-lookup-url');
var employeeId = $(this).val();
# ... more fields ...
if (employeeId !== "") {
# .. Rest of function ...
})
</script>
{% endblock main %}
I also tried using keydown/keyup, but it would not even produce a call to the function. This is how I modified the JS
$("#{{ form.employee_number.id_for_label }}").keydown(()=>{
var url = $("#warehouseForm").attr('data-employee-activity-lookup-url');
var employeeId = $(this).val();
console.log(1); //Not even this appears
if (employeeId === 6) {
...
}
})
Any ideas on how to make this work?
If your id selector ("#{{ form.employee_number.id_for_label }}") is being parsed into a valid reference ("#id-1234-abc", for example), your next issue will be your conditional:
if (employeeId === 6) {…
That tests whether the input value, $(this).val(), is 6 — not how many characters. For that, you would want something like:
if ( employeeId.length === 6) {…
I integrated a popup upon landing on our page http://www.showstye.lu (best seen in an incognito window due to cookie reset). In this popup you have a newsletter signup form which is a copy of the one available in the footer.
I had to duplicate css to adapt to the newsletter popup so that it styled correctly which is fine, I am using Colorbox for the popup itself.
Now, the form itself when I click on the submit button (S'Abonner) it doesn't trigger the submit correctly. I always get a false return telling me to resubmit a new e-mail address.
However, the newsletter form itself works completely fine in the footer and ALSO when I use the keyboard stroke "Enter" instead of clicking on the submit button.
I don't comprehend why one form works in the footer but the identical copy does not (only with Enter keystroke), I looked at the styling/JS/html of the form and it is identical across both.
Any ideas how to resolve this so that the submit button works successfully?
<div style='display:none'>
<div id='subscribe_popup'>
<div id="spop_left">
<div id="spop_top"></div>
<div id="spop_sign">
<div class="popbox">
{% if theme.setting_newsletter %}
<form id="formNewsletter" action="{{ 'account/newsletter' | url }}" method="post">
<input type="hidden" name="key" value="{{ page.key }}" />
<input type="email" name="email" id="formNewsletterEmail" value="" placeholder="{{ 'E-mail' | t }}"/>
<a class="btn glyphicon glyphicon-send" href="#" onclick="$('#formNewsletter').submit(); return false;" title="{{ 'Subscribe' | t }}" {% if shop.language == 'de' %}style="padding: 0px 10px;"{% endif %}><span>{{ 'Subscribe' | t }}</span></a>
</form>
</div> {% endif %}
</div>
</div>
<div id="spop_right"></div>
</div>
</div>
<!-- END subscribe popup-->
Here is the JS behind it:
<script> // popup script
$("document").ready(function (){
// load the overlay
if (document.cookie.indexOf('visited=true') == -1) {
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
$.colorbox({width:"553px", inline:true, href:"#subscribe_popup"});
}
$(".open_popup").colorbox({width:"553px", inline:true, href:"#subscribe_popup"});
});
</script>
Ok that was it, I was integrating a submit into the hyperlink instead of using a simple inputtype submit, keystroke was obviously working because of how the browser automatically identifies the keystroke enter as a submit!