I have the following Django form:
class EmailForm(forms.Form):
name = forms.CharField(...)
email = forms.CharField(...)
message = forms.CharField(...)
Which I then render in my HTML like so:
<div class="controls">
{% csrf_token %}
<div class="form-group">
{{ form.name }}
</div>
<div class="form-group">
{{ form.email }}
</div>
<div class="form-group">
{{ form.message }}
</div>
<input type="submit" value="Say hello" onclick="sendEmail(this);">
</div>
I'm trying to disable the submit button after it's pressed. Here's my javascript function:
<script>
function sendEmail(this1)
{
var name = document.getElementById("form_name").value;
var email = document.getElementById("form_email").value;
var message = document.getElementById("form_message").value;
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var result = re.test(String(email).toLowerCase());
if (name != "" && result && message != "") {
this1.disabled=true;
}
}
</script>
When I override the onclick field in the <input> tag, the button becomes disabled as a result of the Javascript function, but the form does not submit (the page is not reloaded, Django doesn't process the POST). How do I continue the default action for the submit button after disabling it?
Your template does not have the <form></form> tags, without those there is no form to submit.
You should write:
<form id="MyForm">
<div class="controls">
...
<input type="submit" value="Say hello" onclick="sendEmail(this);">
</div>
</form>
That should do it, but in case it doesn't (I realy think it will), you can add this to your sendEmail function:
document.getElementById("myForm").submit();
how about onclick="this.submit()"
Related
I've made a tag list that takes user input and binds it to another input field as a list of tags. However, after weeks messing around with Javascript and JQuery the only way (and importantly an elegant way) I've been able to do it is using Brython. Unfortunately, that seems to be disabling the jinja2 template in some way so nothing is submitted to the database. So, after all that, my question is, can such a seemingly simple task be done natively in Flask?
Here is the essence of how the Brython script works https://jsfiddle.net/5nt39deo/2/ but the code that the question is about is below:
<form action="" id="homeForm" class="centered" role="form" method="post">
{{ form1.hidden_tag() }}
{{ form1.toppings(type="text",id="homeInput",autocomplete="off",list="topps",placeholder="Toppings...") }}
<datalist id="topps">{% for top in topps %}<option value="{{ sym }}">{% endfor %}</datalist>
<button action="" type="submit" id="homeAddTags" class="button">Add</button><br><br>
{{ form1.tags(id="tagList") }}<br>
{{ form1.agree(id="homeAgreement") }}
{{ form1.agree.label() }}<br><br>
<button type="reset" id="homeResetTags" class="button">Reset</button>
{{ form1.sendtags(type="submit",class_="button",id="homeSubmit") }}<br><br>
</form>
<script type="text/python" id="script1">
from browser import document, html, window, console, alert
storage = []
def addTag(e):
item = document['homeInput'].value
if item not in storage and item != '':
storage.append(item)
document['homeInput'].value = ''
document['tagList'].textContent = storage
else:
alert('Tag already added.')
document['homeInput'].value = ''
def resetTags(e):
storage = []
document['homeInput'].value = ''
document['tagList'].textContent = storage
document['homeAddTags'].bind('click', addTag)
document['homeResetTags'].bind('click', resetTags)
</script>
Check out this native javascript solution
...
<input type="text" id="text" placeholder="Enter something" oninput="outputUpdate();">
...
<script type="text/javascript" id="script2">
function outputUpdate(e){
let currentText=document.getElementById('text').value;
document.getElementById('output').innerHTML = currentText;
</script>
https://jsfiddle.net/kalovelo/z5ngxp31/
You can try something like that which I have explained below.
<input type="text">
<div id="output"></div>
Here is the Javascript: Instead of calling a javascript function explicitly, You can simply attach a keyup event to your input box. You can check this out here Fiddle
<script type="text/javascript">
var $onKeyUpEvent = document.getElementsByTagName('input')[0];
$onKeyUpEvent.addEventListener('keyup', (v) => {
document.getElementById('output').innerHTML = v.target.value;
})
</script>
I'd like to add a form field to the template when the user clicks on a button via javascript. I don't want to hide it and just make it appear, I need to insert it because it can be loaded into multiple parts. This is what I've tried but no luck.
document.getElementById("div_id").value = '{{ my_form.field|as_crispy_field }}';
Here is an example:
// update element innerHTML with input field
function addField2(e) {
e.preventDefault();
var container = document.getElementById("field_2_container");
var input = `
<div class="some_class">
<input type="text" name="field_2" id="id_field_2">
</div>
`;
// append input field to the element
container.innerHTML += input;
}
<form id="form">
<div id="field_1_container">
<input type="text" name="field_1" id="id_field_1">
</div>
<div id="field_2_container"></div>
<div id="field_3_container"></div>
<button onclick="addField2(event)">Add field 2</button>
</form>
EDIT: Changed the HTML form statement to work like so:
<form action="." class="form-horizontal" id="groupinfoForm" onsubmit="SubmitToServer()" method="post">
Question: Do i still also need the method="post">
Also changed the javascript to work with the onsubmit:
function SubmitToServer() {
event.preventDefault();
//some ajaxy goodness here... still working on this.
$.ajax({
data: $("#groupinfoForm").serialize(),
success: function(resp){
alert ("resp: "+resp.name);
}
})
//I thinK i have to change all this to work inside the .ajax call?
formData = $('form').serializeArray()
$('#group_info option:first').prop('selected',true);
gid = $('#group_info option:selected').val()
//test alert
alert("Submitting data for provider: " + $("#provider_id").val() + " and " + gid + " and " + formData[0]['date_joined']);
$("#groupinfo-dialog").modal('hide');
}
I have a form, that is standard django. Fill it out send it off goes to a different page upon success..shows errors if you don't fill out portions.
Now I have a modal form that will pop up to fill out some extra data. I have decided to try to my hand at ajax for this. I have some of it working:
Inside the class that is an UpdateView:
def post(self, request, *args, **kwargs):
if self.request.POST.has_key('group_info_submit') and request.is_ajax():
print("YOU SURE DID SUBMIT")
return HttpResponse("hi ya!")
The problem is it always redirects to a different page, and fails validation anyway because the form the modal pops over is not complete and trying to be submitted.
I saw this post here:
Ajax Form Submit to Partial View
This seems overly complicated, I just have a small div in my form that is a modal div that I would like to submit sort of separately from the rest... The java script I have in the code:
$.ajax({
data: $("#groupinfoForm").serialize(),
success: function(resp){
alert ("resp: "+resp.name);
}
})
Then the little modal html snippet is:
<div class="container">
<div id="groupinfo-dialog" class="modal" title="Group Information" style="display:none">
<div class="modal-dialog">
<h1> Group Information </h1>
<div class="modal-content">
<div class="modal-body">
<form action="." class="form-horizontal" id="groupinfoForm" method="post">
{% csrf_token %}
{{ group_information_form.non_field_errors }}
<div class="col-md-12">
{{ group_information_form.date_joined_group.errors }}
{{ group_information_form.date_joined_group.label_tag }}
{{ group_information_form.date_joined_group }}
</div>
<div class="col-md-12">
{{ group_information_form.provider_contact.errors }}
{{ group_information_form.provider_contact.label_tag }}
{{ group_information_form.provider_contact }}
</div>
<div class="col-md-12">
{{ group_information_form.credentialing_contact.errors }}
{{ group_information_form.credentialing_contact.label_tag }}
{{ group_information_form.credentialing_contact }}
</div>
<div class="col-md-12">
<div class="col-md-3">
</div>
<div class="col-md-8 form-actions">
<input type='button' class='btn' onclick="CancelDialog()" value='Cancel'/>
<input type='submit' class='btn btn-success' onclick="SubmitToServer()" value='Save' name='group_info_submit'/>
</div>
<div class="col-md-1">
</div>
</div>
<input type="hidden" id="provider_id" name="provider_id" value="{{ provider_id }}" />
<input type="hidden" id="group_id" name="group_id" value="{{ group_id }}" />
</form>
</div>
</div>
</div>
</div>
</div> <!-- end modal Group Info Dialog -->
I do have a model form on the backend in the forms.py here. Also note there was a SubmitToServer() call, that is where I thought I could toss all the ajax stuff over the fence to the server, but I guess I need that $.ajax? I am still learning the deeper parts of jquery. I want to do a lot of preprocessing before i submit the data. My attempt at the submittoserver javascript was here:
Wasn't sure how to get all the form data (just the three fields I care about from the modal) to send it over...my attempt here:
function SubmitToServer() {
formData = $('form').serializeArray()
$('#group_info option:first').prop('selected',true);
gid = $('#group_info option:selected').val()
alert("Submitting data for provider: " + $("#provider_id").val() + " and " + gid + " and " + formData[0]['date_joined']);
$("#groupinfo-dialog").modal('hide');
}
So can I bypass the main form validation and just send the three fields over somehow? and not have it redirect but stay on the page?
You have to intercept the submit event. add onsubmit="someFunction()" to the form. In the someFunction ajax the data you want to validate before submitting, and if all is ok return true, else false.
https://jsfiddle.net/am5f14oc/
<html>
<body>
<form onsubmit="validateFunc()" action="." method="post">
<input id="name" type="text" name="name">
<input type="submit"/>
</form>
</body>
</html>
and the javascript
function validateFunc() {
formData = $('form').serializeArray();
// do ajax or whatever and return true if everything is ok
return false;
}
i am creating login web app using ajax and PHP and i use javascript an php to validate the input and it works for the login form,but i added a link under the form if not signed up before the link under form
and the HTML for it is :
don't have account on tobe?
and the signUpForm() function contain
function signUpForm(){
$(".logInForm").load("SignUpForm.html");
}
and it works the content change
but when i use JS to validate input using code (just like the login code witch is working) :
HTML(the input in the SignUpForm.html calls the signUp() function)
<input type="button" value="Sign Up" onclick="signUp()">
function signUp(){
if($("input[class='user']").val()==""|| $("input[class='pass']").val()==""){
$(".error-message").fadeIn();
document.getElementById("error-message").innerHTML="Please fill all fields";
} else{
//action(2) including the php file loading
}
}
what happen is javascript ignores the new input fields and consider that the are deleted and always go to action(2) how can i make js see the new form html?
Assuming I understand your problem correctly, I think this code should help you get on the right footing (http://codepen.io/trevorhreed/pen/bppxRG?editors=1010).
In this example, I'm using $(...).html(...) instead of $(...).load(...) since I don't have a server hosting HTML files, but it should work fine to swap .html(...) out for .load(...).
console.clear();
$(function(){
var placeholder = $('#placeholder'),
signInTpl = $('#signin').html(),
signUpTpl = $('#signup').html();
function goToSignIn(){
placeholder.html(signInTpl);
// or placeholder.load('signin.html');
var btnSignIn = $('#btnSignIn'),
signInUsername = $('#signinUsername'),
signInPassword = $('#signinPassword');
btnSignIn.on('click', function(){
if(signInUsername.val() == '' || signInPassword.val() == ''){
alert('Sign In form is NOT valid');
}else{
alert('Sign In form is valid');
}
})
}
function goToSignUp(){
placeholder.html(signUpTpl);
// or placeholder.load('signup.html');
var btnSignUp = $('#btnSignUp'),
signUpUsername = $('#signupUsername'),
signUpPassword = $('#signupPassword');
btnSignUp.on('click', function(){
if(signUpUsername.val() == '' || signUpPassword.val() == ''){
alert('Sign Up form is NOT valid');
}else{
alert('Sign Up form is valid');
}
})
}
goToSignIn();
$('#btnGoToSignUp').on('click', function(){
goToSignUp();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="placeholder"></div>
<template id="signin">
<h2>Sign In</h2>
<form method="post">
<label>
Username
<input id="signinUsername" />
</label>
<label>
Password
<input id="signinPassword" />
</label>
Sign Up
<button type="button" id="btnSignIn">Sign In</button>
</form>
</template>
<template id="signup">
<h2>Sign Up</h2>
<form method="post">
<label>
Username
<input id="signupUsername" />
</label>
<label>
Password
<input id="signupPassword" />
</label>
<button type="button" id="btnSignUp">Sign In</button>
</form>
</template>
I have an hta file that writes to a text file using a form and some javascript.
The form's text field has id of keyword_id which is used by the JS, and directory is the value of the hidden field.
How do I change the JS to only create TEST.txt when user clicks submit?
The code also opens a new C: window everytime I click submit, what's with that?
Here is the html form & javascript code:
HTML:
<div class="tab-content">
<div id="signup">
<h1>Type any keyword(s):</h1>
<form action="/" method="post">
<div class="top-row">
<div class="field-wrap">
<label>
<span class="req"></span>
</label>
<input type="text" required autocomplete="off" id="keyword_id" />
<input type="hidden" name="write" value="C:\Users\ME\Desktop\TEST.txt" id="write_id"/>
<button type="submit" onclick="Writedata()" class="myButton"/>Auto Search</button>
</div>
</div>
Javascript
<script language="javascript">
function Writedata() {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var write_id;
write_id = document.getElementById('write_id').value ;
var s = fso.CreateTextFile(write_id, true);
s.WriteLine(document.getElementById('keyword_id').value);
s.Close();
}
</script>
You've <form action="/" method="post"> and the opened C folder is a response to the form submission.
Most likely you actually don't need the form to be submitted, hence you can omit the attributes in the form tag, and prevent the submission by changing the button type to "button". It's also possible to prevent the default action of button type="submit" by doing this:
function Writedata () {
:
window.event.returnValue = false;
window.event.cancelBubble = true;
}