disable upload page after submit - javascript

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

Related

Django, JS/JQuery validate inputs and disable submit button

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

Two button submit form issue

Hi successfully made a form where there are two submit buttons.
I needed two buttons because I need each button to take the form to a different place, while get/post the information in the first form.
This is how I did it
Javascript:
function submitForm(action) {
var form = document.getElementById('form1');
form.action = action;
form.submit();
}
<form id="form1" method="post" >
<div class="f-row">
<label for="pick">Pick-Up Address</label>
<input type="text" input name="pick" required value="<?php echo isset($_POST['pick']) ? $_POST['pick'] : ''; ?>"/>
</div>
<input type="button" onclick="submitForm('page2.php')" class="btn small color left" value="ADD ANOTHER STOP" />
<input type="button" onclick="submitForm('page3.php')" class="btn medium color right" value="Continue" />
</form>
It works, both buttons submits to the relevant pages.
But now there is one problem I can't seem to fix, previously if the form was not filled, and i clicked submit, it would ask me to fill up the required fields, now it does not anymore.
If required fields are not filled up, it still submits the form.
I need button 1 to not require required fields to be filled up, and button 2 to require it as button 2 submits the form, while button 1 brings it to a new form to fill up with other details before they submit from there.
Anyone know of a way I can sort this?
You can try this: <input type="text" name="pick" id="pick" required/> and in the javascript
function submitForm(action) {
var form = document.getElementById('form1');
form.action = action;
if (document.getElementById('pick').value) {
form.submit();
}}
else{
alert('Please fill the required field!');}
You just need to use jquery to validate the form when the first button is clicked and you can use formaction attribute on the button to specify where the button should go when it's clicked.
$('document').ready(function(){
$('#btn1').on('click',function(){
var pick = $('input[type="text"][name="pick"]').val();
if(pick == ""){
alert("enter pick");
return false;
}else{
$(this).submit();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post" >
<div class="f-row">
<label for="pick">Pick-Up Address</label>
<input type="text" name="pick" value="your value">
</div>
<button type="submit" formaction="page2.php" class="btn small color left" id="btn1">ADD ANOTHER STOP</button>
<button type="submit" formaction="page3.php" class="btn medium color right">Continue</button>
</form>
You could use jQuery for this.
if ($('#something').length)
This will check if there exist an element with the id 'something', but not if it is empty or which value it has.
To check this you can use:
if($('#something').val().length>0)
or
if($('#something').val() != "")
Do with it what ever is needed.
You could even add this check within your submitForm function just above the current code.
Try this:
<script>
function submitForm(action) {
var a = $("input[name=pick]").val();
if(a) {
var form = document.getElementById('form1');
form.action = action;
form.submit();
} else {
alert('please fill the required field');
return false;
}
}
</script>
Using this way(simple way):--
<form id="myForm" name="myForm" onSubmit="encriptar_rc4();return false;">
<input type="submit" name="submitOne" value="submitOne" class="submitButton" />
<input type="submit" name="submitTwo" value="submitTwo" class="submitButton" />
</form>
<script>
$(function(){
$(".submitButton").click(function(e){
alert($(this).attr("name"));
});
encriptar_rc4();{
alert('hola');
}
});
</script>

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();
...
}

jquery to disable buttons on submit/click in forms and links

In my rails app I have buttons that submit information to the server. Some buttons are part of a form and some are not. I'm looking for a way to apply my jquery, which disables the buttons after click, to both.
Here is my current jquery:
$('.btn-disabler').on('click', function() {
$(this).append("<i class='fa fa-spinner fa-pulse btn-loader'>").disable(true);
$(this).find('.btn-label').addClass('invisible');
});
This code adds an icon disables the button and makes the text invisible. I've extended the disable function to work on anchor tags as explained here https://stackoverflow.com/a/16788240/4584963
An example link:
<a class="btn btn-success btn-disabler" rel="nofollow" data-method="post" href="/approve?id=10">
<span class="btn-label">Approve</span>
</a>
An example form:
<form class="simple_form well" novalidate="novalidate" id="new_user" action="/" accept-charset="UTF-8" method="post">
<div class="form-group">
<input class="string optional form-control" placeholder="First name" type="text" name="user[first_name]" id="user_first_name">
</div>
<div class="form-group">
<input class="string optional form-control" placeholder="Last name" type="text" name="user[last_name]" id="user_last_name">
</div>
<div class="form-group">
<input class="string email optional form-control" placeholder="Email" type="email" name="user[email]" id="user_email">
</div>
<div class="form-group">
<input class="password optional form-control" placeholder="Password" type="password" name="user[password]" id="user_password">
</div>
<div class="form-groups">
<input class="password optional form-control" placeholder="Retype password" type="password" name="user[password_confirmation]" id="user_password_confirmation">
</div>
<button name="button" type="submit" class="btn btn btn-primary btn-disabler">
<span class="btn-label">Submit</span>
</button>
</form>
My jquery above does not work for the form. In the form on click, the button changes but there is no submission. To get the jquery to work for the form I need to change it to this:
$('.signup-form').on('submit', function() {
$(this).find('.btn-disabler').append("<i class='fa fa-spinner fa-pulse btn-loader'>").disable(true);
$(this).find('.btn-label').addClass('invisible');
});
How can I consolidate this to apply to both links and form submit buttons? Seems like my problem stems from links need the click event and the form needs the submit event.
You can use jQuery is() to check parent of current button object is form or not in order to submit the form:
$('.btn-disabler').on('click', function() {
$(this).append("<i class='fa fa-spinner fa-pulse btn-loader'>").disable(true);
$(this).find('.btn-label').addClass('invisible');
if ($(this).parent().is("form")) $(this).parent().submit();
});
do you try this using the id of the form like
$('#new_user').on('submit' ...
or with the form element
$('form').on('submit' ...
Think of the submit button as an extension of a form submit event. If you disable the form submit button, the form submit event is disabled. What you can do is add the class to the form, and then in your jQuery code you can assign specific rules. something like this..
So, using this HTML:
<form class="disabler">
<button type="submit"><span>Label</span></button>
</form>
<span>Label</span>
<button class="disabler"><span>Label</span></button>
Use this javascript:
$('.disabler').each(function(e){
if(this.nodeName == "A"){
// this is a hyperlink...
// apply css class
$(this).on('click', function(){
//some action
});
} else if (this.nodeName == "BUTTON") {
//this is a button outside of a form
// disable and add css class
$(this).on('click', function(){
//some action
});
} else if (this.nodeName == "FORM") {
$(this).on('submit', function(){
$(this).find('button[type="submit"]')
.append("<i>Loading</i>")
.disable();
});
}
});
You can probably refactor this down more, but i think you should pay attention to nodeName when you're trying to apply different rules to each of these components.
I hope this answers your question.

Categories

Resources