I've got an HTML form, and when it is submitted, I want a JavaScript function I have defined to run. However, no matter what, the function I've written is not recognised. Here is the HTML form:
<form id="compose-form">
<div class="form-group">
From: <input disabled class="form-control" value="{{ request.user.email }}">
</div>
<div class="form-group">
To: <input id="compose-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="compose-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
<input type="submit" class="btn btn-primary"/>
</form>
And then here is my JavaScript code:
document.addEventListener('DOMContentLoaded', function() {
// #compose is the id of the div the form #compose-form is in
document.querySelector('#compose').addEventListener('click', compose_email);
document.querySelector('#compose-form').addEventListener('submit', () => send_email(event));
});
function send_email(event) {
event.preventDefault();
// Note this isn't the actual content of my function, but even this simple code doesn't work
alert('Hello');
return false;
}
function compose_email() {
document.querySelector('#emails-view').style.display = 'none';
document.querySelector('#compose-view').style.display = 'block';
// Note: this function does work completely.
document.querySelector('#compose-recipients').value = '';
document.querySelector('#compose-subject').value = '';
document.querySelector('#compose-body').value = '';
}
WHAT I'VE TRIED:
I've moved the functions above the event listener in my JavaScript
I've alternately removed both the event.preventDefault(); and the return false;, removed both, kept both.
I've tried defining the function separately, as I have it here, and doing the code as an anonymous function
I've tried both document.querySelector('#compose-form').addEventListener('submit', etc.) and document.querySelector('#compose.form').onsubmit = send_email(event).
I know the form doesn't have an action=; it isn't relevant. In all the searching I have done, this code should prevent the form from submitting, and perform the function, but for whatever reason it doesn't. When I click the submit button only a ? is added to the URL, which I recognise as wanting queries, and that's handled elsewhere with my actual send_email function. I just want to know why my function appears to not be recognised and/or run.
It looks it has issue with document.querySelector('#compose').addEventListener('click', compose_email); Where is the element with id compose? It's not finding it.
I commented out that and it's firing the alert. Please check below
document.addEventListener('DOMContentLoaded', function() {
// #compose is the id of the div the form #compose-form is in
//document.querySelector('#compose').addEventListener('click', compose_email);
document.querySelector('#compose-form').addEventListener('submit', () => send_email(event));
});
function send_email(event) {
event.preventDefault();
// Note this isn't the actual content of my function, but even this simple code doesn't work
alert('Hello');
return false;
}
function compose_email() {
document.querySelector('#emails-view').style.display = 'none';
document.querySelector('#compose-view').style.display = 'block';
// Note: this function does work completely.
document.querySelector('#compose-recipients').value = '';
document.querySelector('#compose-subject').value = '';
document.querySelector('#compose-body').value = '';
}
<form id="compose-form">
<div class="form-group">
From: <input disabled class="form-control" value="{{ request.user.email }}">
</div>
<div class="form-group">
To: <input id="compose-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="compose-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
<input type="submit" class="btn btn-primary"/>
</form>
Related
The thing that I'd like to happen is that when the value of the status field is Paid the input field fines should be read-only.
How to achieve this?
This is my form:
This is my code:
<div class="form-group">
<label for="status" class="col-sm-3 control-label">Status</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="status" value = "Paid" name="status" readonly>
</div>
</div>
<div class="form-group">
<label for="fines" class="col-sm-3 control-label">Fines</label>
<div class="col-sm-9">
<input type="text"
class="form-control" id="fines" name="fines" required>
</div>
</div>
Javascript line of code:
<script type = "text/javascript">
$(document).ready (function(){
$('input[type=text][name=status]').change(function() {
if (this.value == "Paid") {
$("#fines").prop("readonly",true);
}
else{
$("#fines").prop("readonly",false);
}
});
});
</script>
Seeing as you're status field is set to readonly on load, I'd imagine you want to trigger a change event instantly.
$(document).ready (function(){
// setup a variable for multi-use
var $statusField = $('input[type=text][name=status]');
// watch for changes to the statusField
$statusField.change(function() {
// simpler check for paid status
$('#fines').prop('readonly', this.value === 'Paid');
});
// trigger a change on ready
$statusField.change();
});
This way you have access to trigger the change programatically but also have the ability to watch the status field. I've also cleaned up your code a little bit!
try like this
if ($(this).val() == "Paid") {
$("#fines").attr("readonly",true);
}
else{
$("#fines").attr("readonly",false);
}
I have a simple input params that are required. I want to disable my submit button until all the required fields are satisfied. Granted I am new to django, and the particular code I am working on is very old. As a result, post like this or this are not helping.
Current code that I am trying from one of the posts linked and including my own template
<script type="text/javascript">
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
$('#submit').on('click', function() {
var zip = $('#zip').val();
var email = $('#email').val();
var name = $('#name').val();
//if inputs are valid, take inputs and do something
});
<form class="form-horizontal" action="" method="get" id="dataform">
<div class="form-group">
<div class="container">
<div class="row">
<div class="col-md-offset-2 col-md-3">
<input class="col-md-12" id="zip" type="text" placeholder="Enter zip code" aria-required="true">
</div>
<div class="col-md-3">
<input class="col-md-12" id="name" type="text" placeholder="Enter last name" aria-required="true">
</div>
<div class="col-md-3">
<input class="col-md-12" id="email" type="email" placeholder="Enter email address" aria-required="true">
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="btn btn-primary" id="submit" type="submit">Submit</div>
</div>
</div>
</form>
any help on disabling my submit button until input fields are not validated/filled is much appreciated. Again, new to django and I am unable to use existing threads on said topic
From your current code, looks like your selector for the submit input is not actually getting the submit "button". Currently, your template defines the submit as a div and not an input, thus your selectors should be $("div[type=submit]") not $("input[type=submit]")
Better yet, just select by div id $('#submit')
Instead of targeting attributes, I was targeting props. Below is the fix for my particular issue.
if (inputsWithValues === 3) {
$("div[type=submit]").attr("disabled", false);
} else {
$("div[type=submit]").attr("disabled", 'disabled');
}
I'm trying to create a form where, if the user selects 'yes' from a dropdown, two extra fields appear. Both of these fields are required, and one of them needs to be validated according to an array of 'codes' - the user must input one of the codes in the array for the form to submit correctly. However, if the user selects 'no' from the dropdown, these fields do not appear and are not required, and the array validation does not occur and the form can be submitted.
I have some code for this, however I can't get the fields to appear. An earlier issue I encountered with this (minus the array validation - including that broke the code and stopped the extra fields appearing) was that if the user selected 'yes', and then went back to change their mind and selected 'no', then the form would not submit, clearly still requiring the fields to be filled in/correct array value inputted.
If anyone could help me in making this work I would greatly appreciate it.
HTML:
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select onclick='checkIfYes()' class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_code_input" name="auth_by" required disabled>
</div>
<hr>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>
JavaScript:
$(document).ready(function() {
checkIfYes = function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
// show extra fields & make them required
document.getElementById('extra').style.display = '';
document.getElementById('auth_code_input').disabled = false;
document.getElementById('desc').disabled = false;
// show user if their input is one of the codes in the array when leaving field
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
e.preventDefault();
}
});
// prevent form submission if input is not one of the codes in the array
$('#auth_form').on('submit', function(e) {
if (!ValidateInput()) {
e.preventDefault();
}
});
function ValidateInput() {
var codes = ['Foo', 'Bar']; // user must enter one of these
var IsValid = false;
var input = $('#auth_code_input').val()
if (codes.indexOf(input) > -1) { // if input equals one of the codes in the array
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
return IsValid;
}
} else { // hide and disable extra fields so form can submit
document.getElementById('extra').style.display = 'none';
document.getElementById('auth_code_input').disabled = true;
document.getElementById('desc').disabled = true;
}
}
});
JSFiddle
It's a glitch in the way you define the function -- by calling checkIfYes() it's looking for it on the global (window's) scope. By changing the line:
function checkIfYes() {...
to this:
checkIfYes = function() {...
then you've got it on the global scope. Which is, by the way, bad practice. You'd be better to create a click handler in your script itself, than to hard- code the function call in your HTML. But that's just me.
A few changes made, some pretty significant -- first, I removed the hard-coded reference to checkIfYes and simply put the event in your javascript. Second (and pretty darn significant), I moved the event handlers to the root of your javascript, rather than defining them in your checkIfYes function. This way, they don't depend on that being called each time. Try it, it works.
$(document).ready(function() {
/**
* Define some custom events to handle...
**/
$("#defect").on("change", checkIfYes );
// show user if their input is one of the codes in the array when leaving field
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
console.log("Input is wrong!");
}
});
// prevent form submission if input is not one of the codes in the array
$('#auth_form').on('submit', function(e) {
e.preventDefault();
console.log("This is where I would be checking...");
if (ValidateInput()) {
$("#auth_form").submit();
}
});
// Utility Functions.
function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
// show extra fields & make them required
document.getElementById('extra').style.display = '';
document.getElementById('auth_code_input').disabled = false;
document.getElementById('desc').disabled = false;
} else { // hide and disable extra fields so form can submit
document.getElementById('extra').style.display = 'none';
document.getElementById('auth_code_input').disabled = true;
document.getElementById('desc').disabled = true;
}
}
function ValidateInput() {
var codes = ['Foo', 'Bar']; // user must enter one of these
var IsValid = false;
var input = $('#auth_code_input').val()
if (codes.indexOf(input) > -1) { // if input equals one of the codes in the array
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
return IsValid;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_code_input" name="auth_by" required disabled>
</div>
<hr>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>
I have button(in future many), and form. What i want, that after submit of the page that call form became not available.
But after submit page is upload. How to avoid this?
<script type="text/javascript">
$(function() {
var btn = $('#btn1');
var form = $('#myform');
var formbtn = $('#submit');
btn.on ('mouseup', function(){
form.toggle(200);
});
formbtn.on('mouseup', function(){
btn.html('bought!');
btn.attr('disable', true);
return false;
});
});
<div id = "myform">
<form id = "my">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Phone</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<button id="submit" class="btn btn-default">Submit</button>
</form>
</div>
And how in future choice button to disable from the plurality of buttons, it will be some array?
To answer the first part of your question, you will want to change
btn.attr('disable', true);
to
btn.attr('disabled', 'disabled');
For the second part of your question, if I understand correctly, you could use a class or element selector for multiple buttons
$('button')
$('.buttonClass')
To add, depending on the version of jQuery, you may want to use .prop instead of .attr for 1.6+.
See this answer for more information - https://stackoverflow.com/a/6048113/1927071
I have a html form and I am using angular JS for validation. Here, after submitting the form I am calling the reset method which will reset the form input fields to default.
But, when I submit and call reset method, the validation messages appears in the input field. I have used the below code. I don't want to see the validation messages after submitting the form.
HTML
<form name="createvalidation" role="form" class="col-lg-12" novalidate>
<div class="form-group">
</div>
<div class="form-group">
<input type="text" placeholder="Challenge name" class="form-control input-sm" name="name" ng-model="challenge.challengename" required>
<span ng-show="(createvalidation.name.$dirty || submitted) && createvalidation.name.$error.required">Name is reqiured</span>
</div>
<div class="form-group">
<textarea class="form-control input-sm" rows="2" placeholder="Write more about this challenge..." name="description" ng-model="challenge.challengedescription" required></textarea>
<span ng-show="(createvalidation.description.$dirty || submitted) && challengecreatevalidation.description.$error.required">Description is reqiured</span>
</div>
</form>
<div>
<button type="button" ng-click="createChallenge()">Create</button>
</div>
JS CODE
$scope.createChallenge = function() {
//get the field and store in db
$scope.resetForm();
}
$scope.master = {};
$scope.resetForm = function() {
$scope.challenge = angular.copy($scope.master);
$scope.createvalidation.$setPristine();
}
$scope.createChallenge = function() {
//get the field and store in db
$scope.resetForm();
}
$scope.master = {};
$scope.resetForm = function() {
$scope.submitted = false; //Try adding this
$scope.challenge = angular.copy($scope.master);
$scope.createvalidation.$setPristine();
}
You appear to be copying the pristine state of the form from within the resetForm function. This means that it will only have the version of the form when resetForm is called. Instead perhaps you should be doing that copy whenever the form is setup and pristine.