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");
}
}
Related
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>
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');
}
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())
}
For a community site, I created an HTML form to add new users. If a new user wants to make a profile photo right away, this is possible with WebcamJS (using v1.0.2, already got this working).
However, when I want to add a new user and filled in all data (with or without a picture) and press Return, instead of submitting the form, a new webcam div is opened.
I tried a lot of different things, even disabling the default behavior of the return key, but still the problem persists.
Hope anyone can help!
Simplified HTML example:
Webcam.set({
width: 400,
height: 300,
//dest_width: 400,
//dest_height: 300,
image_format: 'jpeg',
jpeg_quality: 80
});
$("#maak_foto").hide();
$("#foto_maken").click(function() {
Webcam.attach('#my_camera');
$("#maak_foto").show();
$("#my_camera").show();
$("#foto_form").show();
});
$("input#foto_gebruiken").click(function() {
$("#my_camera").hide();
$("#pre_take_buttons").hide();
});
function preview_snapshot() {
Webcam.freeze();
// swap button sets
document.getElementById('pre_take_buttons').style.display = 'none';
document.getElementById('post_take_buttons').style.display = '';
}
function cancel_preview() {
Webcam.unfreeze();
// swap buttons back
document.getElementById('pre_take_buttons').style.display = '';
document.getElementById('post_take_buttons').style.display = 'none';
}
function save_photo() {
// actually snap photo (from preview freeze) and display it
Webcam.snap(function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'Jouw foto:<br>' +
'<img src="' + data_uri + '"/>';
// swap buttons back
document.getElementById('pre_take_buttons').style.display = '';
document.getElementById('post_take_buttons').style.display = 'none';
var raw_image_data = data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
document.getElementById('webcam').value = raw_image_data;
//document.getElementById('wijzigen').submit();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://intern.ifmsa.nl/leden/webcam/webcam.js"></script>
<form name="htmlform" method="post" enctype="multipart/form-data" action="<?php $_SERVER['PHP_SELF'] ?>">
<label>Voornaam</label>
<input type="text" name="voornaam">
<br>
<label>Email</label>
<input type="email" name="email">
<br>
<label>Photo</label>
<div>
<input name="foto" type="file">
<button id="foto_maken" onclick="return false" ;>Or make another one</button>
<input id="webcam" type="hidden" name="webcam" value="">
</div>
<br>
<div id="results"></div>
<div id="my_camera" style="display: none; clear: left;"></div>
<div id="pre_take_buttons">
<input type="button" id="maak_foto" value="Take photo" onClick="preview_snapshot(); return false;">
</div>
<div id="post_take_buttons" style="display:none;">
<input type="button" value="Another photo" onClick="cancel_preview(); return false;">
<input name="webcamdefi" id="foto_gebruiken" type="button" value="Use photo" onClick="save_photo(); return false;">
</div>
<label>Confirm password</label>
<input name="pass" type="password" required>
<input class="submit" type="submit" name="submit" value="Wijzigen">
</form>
Simple magic (the first tag button#foto_maken is interpreted as the submit button and fire when the enter press):
change this:
<button id="foto_maken" onclick="return false" ;>Or make another one</button>
to this:
<input type="button" id="foto_maken" value="Or make another one"/>
[ http://jsfiddle.net/2es2yf0y/ ]
More clear example: http://jsfiddle.net/stdob/tfss0sz2/2/
So I've been looking around at code and seeing what is possible through javascript. I have a code that currently checks if a form has empty elements and denies it to be submitted if any are empty. The thing is I tried to add an alert if the elements were empty and an alert if the elements were not empty but it did not work. I don't seem to know enough about java script to go about editing it.
Here is the form. Ignore the weird class and div names, they are set that way because the form submits to a google doc spreadsheet.
<form class="quickemailform" action="https://docs.google.com/spreadsheet/formResponse?formkey=dGp3YUxCTGtWd251ZXVfOEtwc1hhWVE6MQ&ifq" method="post" target="hidden_iframe" onsubmit="submitted=true;" id="ss-form" name="frm1" onsubmit="InputChecker()">
<br>
<div class="errorbox-good">
<div class="ss-item ss-item-required ss-text">
<div class="ss-form-entry">
<label class="ss-q-title" for="entry_0">
<font class="formtitles">FULL NAME:</font>
</br>
<label class="ss-q-help" for="entry_0"></label>
<input type="text" name="entry.0.single" value="" class="ss-q-short" id="entry_0" size="42">
</div>
</div>
</div>
<div class="errorbox-good">
<div class="ss-item ss-item-required ss-text">
<div class="ss-form-entry">
<label class="ss-q-title" for="entry_1">
<font class="formtitles" id="compnam">COMPANY NAME:</font>
</br>
<label class="ss-q-help" for="entry_1"></label>
<input type="text" name="entry.1.single" value="" class="ss-q-short" id="entry_1" size="42">
</div>
</div>
</div>
<div class="errorbox-good">
<div class="ss-item ss-item-required ss-text">
<div class="ss-form-entry">
<label class="ss-q-title" for="entry_2">
<font class="formtitles" id="emailadd">EMAIL ADDRESS:</font>
<br>
<label class="ss-q-help" for="entry_2"></label>
<input type="text" name="entry.2.single" value="" class="ss-q-short" id="entry_2" size="42">
</div>
</div>
</div>
<div class="errorbox-good">
<div class="ss-item ss-item-required ss-paragraph-text">
<div class="ss-form-entry">
<label class="ss-q-title" for="entry_3">
<font class="formtitles" id="request">Your Request:</font>
<font class="fineprint">( SUMMARIZE IMPORTANT DETAILS )</font>
<br>
</label>
<label class="ss-q-help" for="entry_3"></label>
<textarea name="entry.3.single" cols="32" rows="10" class="ss-q-long" id="entry_3"></textarea>
</div>
</div>
</div>
<input type="hidden" name="pageNumber" value="0">
<input type="hidden" name="backupCache" value="">
<div class="ss-item ss-navigate"><div class="ss-form-entry">
<input class="submitbuttons" type="submit" name="submit" value=" " src="" border="0" onclick="myFunction()" />
</div>
</div>
</form>
Here is the javascript that denies the form to be submitted if any fields are empty. I got this code online, I did not write it myself. It is tested and works but I want it to do more than just deny submission.
<script type="text/javascript">
(function() {
var divs = document.getElementById('ss-form').
getElementsByTagName('div');
var numDivs = divs.length;
for (var j = 0; j < numDivs; j++) {
if (divs[j].className == 'errorbox-bad') {
divs[j].lastChild.firstChild.lastChild.focus();
return;
}
}
for (var i = 0; i < numDivs; i++) {
var div = divs[i];
if (div.className == 'ss-form-entry' &&
div.firstChild &&
div.firstChild.className == 'ss-q-title') {
div.lastChild.focus();
return;
}
}
})();
</script>
If possible I want to know how I can add an alert for when the form is denied or accepted. Also if the form is denied I would like to have it so that I have something like
<font class="asterick" div="your_name_ast">*</font> or <font class="asterick" div="company_name_ast">*</font>
and have the asterick show up next to each empty element if the form is denied not submitted. Such as having the form check each element to be empty or not. If the script finds the element to be empty an alert would pop up saying "Form is not filled. Please look over all elements with a *." and then it would have the asterisk appear.
Thanks to anyone that has read this far.
EDIT: Doing some looking around more and it seems that alerts are considered bad practice. Is this true? Is there some other way I might go about letting users know if the elements are empty?
You could use jQuery Validate (or similar) like EdSF mention or you could just change the submit button into a regular button that when click it calls a function to validate your fields and if non are empty submit the form. I haven't tested the following code, but you get the idea.
function validateForm(){
var isValid = true;
var elements = document.getElementById('ss-form').getElementsByTagName('input');
for(var i=0; i < elements.length; i++){
if(elements[i].value.length < 1){
isValid = false;
}
}
if(isValid){
document.getElementById('ss-form').submit();
}
else {
alert('Please fill all required fields');
}
}
Using jQuery you could accomplish everything you want to do. jQuery is very easy to learn. Here is a sample of your code using jQuery:
This is a very minimal example of what you can do.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$('#entry_0').blur(function()
{
var Fullname = $(this).val();
$('#nameresult').css("display","none");
if(Fullname.length>0)
{
$('#nameresult').css("display","inline-block");
$('#nameresult').css("color","#00BB00");
$('#nameresult').html("Valid")
return true;
}
$('#nameresult').css("display","inline-block");
$('#nameresult').css("color","#ff0000");
$('#nameresult').html("Input Needed")
$(this).focus();
return;
});
$('#entry_1').blur(function()
{
var Companyname = $(this).val();
$('#companyresult').css("display","none");
if(Companyname.length>0)
{
$('#companyresult').css("display","inline-block");
$('#companyresult').css("color","#00BB00");
$('#companyresult').html("Valid")
return true;
}
$('#companyresult').css("display","inline-block");
$('#companyresult').css("color","#ff0000");
$('#companyresult').html("Input Needed")
$(this).focus();
return;
});
});
</script>
</head>
<body>
<form >
FULL NAME:<input type="text" name="entry.0.single" value="" class="ss-q-short" id="entry_0" size="42">
<div id="nameresult" style="display: none;"></div>
<br>
COMPANY NAME:<input type="text" name="entry.1.single" value="" class="ss-q-short" id="entry_1" size="42">
<div id="companyresult" style="display:none;"></div>
<br>
EMAIL ADDRESS:<input type="text" name="entry.2.single" value="" class="ss-q-short" id="entry_2" size="42"><br>
Your Request:<textarea name="entry.3.single" cols="32" rows="10" class="ss-q-long" id="entry_3"></textarea><br><br>
<input class="submitbuttons" type="submit" name="submit" value="SUBMIT" src="" border="0" />
</form>
</body>
</html>
Please forgive the code formatting, I typed it up very quickly.
Here is a link to jQuery
Here is a working model that I've used on an email encrypting site:
http://jsfiddle.net/2b6d5/46/
Feel free to add to it, change it... post any forks/updates here.
:)
/*
* validate an e-mail address by leveraging the HTML5
* input element with type "email"
*/
function validate() {
var input = document.createElement('input');
input.type='email';
input.value=document.getElementById('valid').value;
if (input.checkValidity()) {
document.getElementById('address').style.background = 'green';
} else {
document.getElementById('address').style.background = 'red';
}
return false;
}
function val2(){
var input = document.createElement('input');
input.type='email';
input.value=document.getElementById('valid').value;
if (input.checkValidity()) {
return true;
} else {
alert("Not a valid e-mail address");
return false;
}
}