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())
}
Related
I am coding a new site for a client and I want to add a class to a div element once the user reaches 100vh. I have given the body an id of "myBody" and the div element that I want to add the class to an id of "quoteForm" and a class of "quote-form" Here is the html of the page...
<body id="myBody">
<div id="quoteForm" class="quote-form">
<div id="quoteFormHead"></div>
<form action="<?php the_permalink(); ?>" method="post">
<div id="quoteFormBody">
<div class="formfullwrapper">
<input type="text" name="message_fname" placeholder="Enter your full name here...">
</div>
<div class="formfullwrapper">
<input type="email" name="message_email" placeholder="Enter your email address here...">
</div>
<div class="formfullwrapper">
<input type="number" name="message_phone" placeholder="Enter your phone number here...">
</div>
<div class="formfullwrapper">
<textarea name="message_msg" placeholder="Details, please! Audience? Word count? Type of document? Tone? Deadlines? Sensitive content?"></textarea>
</div>
</div>
<div id="quoteFormFooter">
<div class="formfullwrapper">
<input type="submit" id="submitform" value="Get my free quote">
</div>
</div>
</form>
</div>
</body>
as you can see its quite a simple form. Below if the javascript logic I have used to add the class name...
document.addEventListener("DOMContentLoaded", function(){
var scrollElement = document.getElementById('myBody');
var scrollElementPos = scrollElement.scrollTop;
var form = document.getElementById('quoteForm');
scrollElement.addEventListener('scroll', function(){
scrollElementPos = scrollElement.scrollTop;
if(scrollElementPos >= 10){
form.classList.add("form-fixed");
} else {
form.classList.remove("form-fixed");
}
console.log(scrollElementPos);
});
});
At present nothing is happening and the class name is not being added to the quote form. Any ideas? Many thanks,
Phillip Dews
Yep its the scroll "On" Window. This is what I came up with and it works a dream...
window.onscroll = function(){
var top = window.pageYOffset || document.documentElement.scrollTop;
var form = document.getElementById('quoteForm');
if (top > 1000) {
form.classList.add("form-fixed");
} else {
form.classList.remove("form-fixed");
}
}
I'm building a demo login form. For the demo, I'd like two things to happen:
When the user clicks the login button for the first time, an error message appears.
When the user clicks the login button for the second time, they are directed to another page.
Here's how my code looks so far:
function toggleError() {
var toggleError = document.querySelector('.message--error');
toggleError.classList.toggle('error-toggled');
}
.message {
display: none;
}
.error-toggled {
display: block;
}
<div class="message message--error">
<span class="message__text">The login details you entered are incorrect.</span>
</div>
<form onsubmit="toggleError(); return false;" action="/" method="get" class="login__form" autocomplete="off">
<label for="email" class="srt">Email</label>
<input type="email" name="email" id="email" required placeholder="Email" class="input input--border-right">
<label for="password" class="srt">Password</label>
<input type="password" name="password" id="password" required placeholder="Password" class="input">
<div class="login__actions">
<button type="submit" class="button">Log In</button>
Lost your password?
</div>
</form>
Using onsubmit="toggleError(); return false;" achieves my first objective of displaying an error message.
How would I extend this function so the user is directed to a page when they click the button for a second time? I'm guessing I would write some type of loop?
Based on first two comments here a possible way:
<script>
var clickCounter=0;
function toggleError() {
//Increase the value by one
clickCounter++;
if (clickCounter == 1) {
//what ever you want to do
return false;
} else if (clickCounter == 2) {
//You need to change the value again
...
var toggleError = document.querySelector('.message--error');
toggleError.classList.toggle('error-toggled');
return false;
}
}
</script>
I have some code that successfully inputs a variety of values into a form on a webpage and I can see that the data is put into the correct fields in the correct format. When I submit the form using the 'OK' button, or code, the process completes but the Date data carried through is the current date, despite the fact that I can see a different date displayed in the field. I can cut and paste data into the field from e.g., Notepad and it works fine.
Here is the html for the beginning of the form:
<form action="#" method="get">
<div class="columns group">
<div class="formColumn flex">
<div id="editConference_ownerField" style="display: none">
<div class="formRow">
<div class="labelBlock" id="editConference_ownerLbl">Owner</div>
<div class="fieldBlock fillspace">
<select id="editConference_owner"></select>
</div>
</div>
</div>
// The first input in this class loads find and is pulled through when the form is submitted using the OK button
<div class="formRow">
<label class="labelBlock" id="editConference_labelLbl" for="editConference_label">Title</label>
<div class="fieldBlock fillspace">
<input type="text" class="input" id="editConference_label" maxlength="256" value="">
</div>
</div>
<div id="editConference_timeFields" style="">
<div class="formRow">
<div class="labelBlock" id="editConference_startLbl">Start</div>
<div class="fieldBlock calendarBlock">
<input type="date" id="editConference_startNative" class="native_date has_native">
// The element id="editConference_start" is a date and does NOT pull through
<input type="text" id="editConference_start" class="sl_date has_native" placeholder="DD/MM/YYYY">
// The element id="editConference_startTime" is a time DOES pull through!
<input type="text" id="editConference_startTime" placeholder="Time" class="ui-timepicker-input" autocomplete="off">
<div id="start-date-picker"><div class="pika-single is-hidden is-bound" style="position: static; left: auto; top: auto;"></div></div>
<div id="start-time-picker"></div>
</div>
</div>
<div class="formRow">
<div class="labelBlock" id="editConference_endLbl">End</div>
<div class="fieldBlock calendarBlock">
<input type="date" id="editConference_endNative" class="native_date has_native">
<input type="text" id="editConference_end" class="sl_date has_native" placeholder="DD/MM/YYYY">
<input type="text" id="editConference_endTime" placeholder="Time" class="ui-timepicker-input" autocomplete="off">
<div id="end-date-picker"><div class="pika-single is-hidden is-bound" style="position: static; left: auto; top: auto;"></div></div>
<div id="end-time-picker"></div>
</div>
</div>
Here is the Javascript that I have been using. I have been testing it out using the Chrome F12 Console and working inside the iframe. All the inputs used appear to be of type="text". It automates the filling out of the form except the problem noted above and submits it:
\\Loading the data into the fields
var Title = "Coding syntax test again";
document.getElementById('editConference_label').value = Title;
var StDate = "06/05/2020";
document.getElementById('editConference_start').value = StDate;
var StTime = "16:20";
document.getElementById('editConference_startTime').value = StTime;
var EndDate = "06/05/2020";
document.getElementById('editConference_end').value = EndDate;
var EndTime = "17:50";
document.getElementById('editConference_endTime').value = EndTime;
var Desc = "The conference description stuff";
document.getElementById('editConference_description').value = Desc;
\\ Click 'OK'
document.getElementById("editConference_ok").click();
Things tried:
1) Using the code below to enter data via the id ="editConference_startNative" element. It does not seem to work but I am not sure if my code makes any sense or if this something worth pursing:
var StDate = document.querySelector('input[type="date"]');
StDate.value = '2020-05-05';
document.getElementById('editConference_startNative').value = StDate;
2) Creating a var with a date type for use with the Native version of the input
var StDate = new Date("05/05/2020");
document.getElementById('editConference_startNative').value = StDate;
I think the output is in the wrong form to be used but can't figure out how to shorten it in the right format. Perhaps this is not the right approach.
3) Removing the final click code then waiting for a few seconds and them adding the Click line in and executing but this did not work so I presume it is not a question of a delay. I also tried this code before the click code for a delay but I am not sure if it is valid:
setTimeout(function(){}, 3000);
document.getElementById("editConference_ok").click();
Thanks in advance for any suggestions.
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 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