Django, JS/JQuery validate inputs and disable submit button - javascript

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');
}

Related

Regarding enabling and disabling fields for registration form?

I have to create a registration form with fields as first name,last name,address,contact no,email.initially only first name shouid be visible as i enter name it should enable last name as i enter last name it should enable address
you could do somthing like this
<form>
<input id='firstname' >
<input id='lastname' disabled>
</form>
<script>
const firsname = document.getElementById('firstname')
const lastname = document.getElementById('lastname')
firstname.oninput = function(){
if(firstname.value.length>0) lastname.disabled = false
else lastname.disabled = true
}
</script>
I have totally different take on this. There is nothing wrong with this approach. In-fact there are many cool UIs design with same terminology. typeform.com is great example for this.
This is very bad practice at SO, whats a point in down rating a new user.
If you cant give a proper suggestion, then you have no right to down rate someone only because you failed to understand his view point.
To answer this :
It will be very bad idea if its just implemented this in wrong way, and user might get annoyed with this.
Its better to use combination of CSS and JS (jquery) to achieve this for great looking, user friendly UI.
Find this small snippet i've created using jQuery might help you.
with little css it can be made to look great!
Press enter after entering detail into text box.
jQuery.extend(jQuery.expr[':'], {
focusable: function(el, index, selector) {
return $(el).is('a, button, :input,[tabindex]');
}
}); // extention to jquery
$("#res").hide();
$("#email").hide();
$("#mobile").hide();
//Focuse Next on Enter press
$(document).on('keypress', 'input,select', function(e) {
if (e.which == 13) {
e.preventDefault();
var $focusable = $(':focusable');
var index = $focusable.index(document.activeElement) + 1;
if (index >= $focusable.length) index = 0;
$focusable.eq(index - 1).hide();
$focusable.eq(index).show();
$focusable.eq(index).focus();
}
});
function subscribeRelease() {
$("#res").show(200);
$(".btn").hide(200);
}
body,
html {
height: 100%;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="container-fluid h-100 justify-content-center">
<div class="row justify-content-center align-middle h-100">
<div class="col-10 text-center align-self-center">
<h1 style="font-size:40pt;">Register</h1>
<form id="register" class="form-inline justify-content-center">
<input type="text" class="form-control" id="name" placeholder="Name" /><br>
<input type="text" class="form-control" id="email" placeholder="Email" /><br>
<input type="text" class="form-control" id="mobile" placeholder="Mobile" /><br>
<br><br><br>
<button class="btn btn-info" onclick="subscribeRelease(); return false;">Submit!</button>
<span id="res"><h3 class="text-success">Registration Completed!</h3></span>
</form>
</div>
</div>
</div>

Each time I click button page refreshes

Title virtually says it all. Each time I click calculate button the page just refreshes. I added the stopPropagation and preventDefault which worked on my other button on a different page, however in this situation they don't seem to work. Any thoughts?
JS:
/******** Loan Balance Constructor *********/
function LoanBalance(mLoanAmt, mIntRate, nMonths, mMonthlyPmt){
//Declarations
this.loanAmount = mLoanAmt;
this.interestRate = mIntRate;
this.numbOfMonths = nMonths;
this.monthlyPayment = mMonthlyPmt;
//Calculates Remaining Balance
this.calculateRemaining = function(){
console.log(this.loanAmount);
console.log(this.interestRate);
console.log(this.numbOfMonths);
console.log(this.monthlyPayment);
//COME BACK TO FIX THE FORMULA
var remainingBalance = this.loanAmount*(Math.pow(1+this.interestRate, this.numbOfMonths) -
(this.monthlyPayment*(Math.pow(1 + this.interestRate, this.numbOfMonths) - 1) / this.interestRate));
return remainingBalance;
}
return this.calculateRemaining()
}
function newBalanceObject(e){
e.stopPropagation();
e.preventDefault();
var balanceObject = new LoanBalance(document.getElementById("loanAmount").value, document.getElementById("interestRate").value,
document.getElementById("numMonthsPaid").value, document.getElementById("sliderDuration").value);
var result = balanceObject.calculateRemaining();
document.getElementById("remainingBalanceTag").innerHTML = "Your remaining balance is: " + "$" + result.toFixed(2);
}
HTML:
<div id="remainingBalance">
<h1 class="text-center">Loan Balance Calculator</h1>
<form>
<div class="form-group">
<label for="loanAmount">Loan Amount:</label>
<input class="form-control" id="loanAmount">
</div>
<div class="form-group">
<label for="interestRate">Interest Rate:</label>
<input class="form-control" id="interestRate" placeholder="Please enter number as a decimal">
</div>
<div class="form-group">
<label for="numMonthsPaid">Number of Months Paid: </label>
<input id="numMonthsPaid" type="text" data-slider-min="0" data-slider-max="600" data-slider-step="1" data-slider-value="300">
<div class="form-group">
<label for="sliderDuration">Loan Duration: </label>
<input id="sliderDuration" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="600" data-slider-step="1" data-slider-value="300"/>
</div>
<button id="calcButton" class="btn btn-default">Calculate</button>
</form>
<h1 class="text-center" id="remainingBalanceTag"></h1>
</div>
The form is getting submitted by default. You need to intercept the submission event and stop the default's browser action.
Since you haven't specified the action on the form element, it's simply refreshing the page, because it doesn't know where to send the data to.
Here's a sample code which shows how to intercept and stop all forms fom being submitted by the browser. Adjust it according to your setup so you only prevent submission of the forms that you want prevented.
Array.from(document.forms).forEach(form => {
form.addEventListener('submit', e => e.preventDefault())
}

Required Field without Submit button after Ajax

I am trying to have my all my text/email input forms have a required attribute before you can "Submit" The email
But since I am using some Ajax to keep the page from refreshing after pressing the button the required attribute will not work.
This is why I am asking for an alternative for required with Javascript or jQuery (trying to prevent email form spam).
HTML (FORM)
<form id="contact">
<div class="form-group">
<label for="name">Voornaam*</label>
<input name="fn" type="text" class="form-control" id="fn" required>
</div>
<div class="form-group">
<label for="name">Achternaam*</label>
<input name="ln" type="text" class="form-control" id="ln" required>
</div>
<div class="form-group">
<label for="email">Email-address*</label>
<input name="email" type="email" class="form-control" id="email" required>
</div>
<div class="form-group">
<label for="message">Bericht*</label>
<textarea name="message" required class="form-control" id="message" rows="6"></textarea>
</div>
<button type="button" onClick="doIets(); this.form.reset();"
name="submit" id="submit" class="btn btn-primary">Verstuur <span id="result"></span></button>
<div id="result2"></div>
</form>
Ajax script
<script type="text/javascript">
function doIets()
{
console.log("doe iets");
var data = {
ck: (new Date()).getTime(),
fn: $("#fn").val(),
ln: $("#ln").val(),
email: $("#email").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "sendmail.php",/*php file path*/
data: data,
beforeSend: function(){
$('#result').html('<img src="loader" style="height:10px;"/>')
},
success: function(data){
$('#result').hide();
$('#result2').html(data);
}
});
}
</script>
You will need to use e.preventDefault() when they click on the submit button and then validate the form and after that submit it using the ajax call you created above.
since you already read out the data, you can check whether your message is long enough for you via
data.message.length
if it is 0 (or lower than a threshold you defined), you can skip the ajax call and return some info to the user.
You might also want to trim the message first in order to be sure there aren't only whitespace in there.
Here is part from my code, where I bind the submit event to my form and check by looping if any required field is empty or if I want to do any such thing.
This way may help you--
$('.form .contact-form').submit(function(e) {
e.preventDefault();
$('.form .message').eq(0).html("<i>Sending... Please Wait...</i>");
var form = $(this);
var validated = true;
$('input[type="text"]',this).each(function(){
if($(this).val().length < 1){
$(this).addClass('error').focus();
validated = false;
return false;
}
});
if(validated === true){
$.post(__asyn.ajaxurl, $('.form form').eq(0).serialize(), function(data, textStatus, xhr) {
console.log(data);
});
}
});
Just pass the event object to your handler onClick="doIets(event);
and then add
function doIets(event) {
event.preventDefault();
...
}

disable upload page after submit

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

Validation messages not removed after resetting the form

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.

Categories

Resources