Clearing multiple text input boxes with one name - javascript

Hi I have several text input boxes, and i have a clear button, they all share the same name and i wish to clear them all using one function, and this be done without ID's as that takes up too much space
my code thus far looks like this:
var Id;
var Name;
function Check(id, name) {
Id = document.getElementById(id);
Name = document.getElementById(name);
if (Id.value == id) {
Name.checked = true;
alert('correct');
return;
} else {
Name.checked = false;
alert('incorrect');
}
}
function ClearP() {
document.getElementsByName("input").innerHTML = '';
}
my html looks like this
<div class="content">
<div class="main_story" style="margin-bottom:20px;">
<p class="sentence">the word to go here -></p>
<input id="here" name="input" class="sentence" type="text" size="7">
<p class="sentence">is here</p>
<button style="float:right" id="correct" onClick="Check('here', 'aShow');">Correct?</button>
<input style="float:right" name="aShow" id="aShow" type="checkbox" value="">
</div>
<div class="main_story" style="margin-bottom:20px;">
<p class="sentence">the word to go here -></p>
<input id="you" name="input" class="sentence" type="text" size="7">
<p class="sentence">is you</p>
<button style="float:right" id="correct" onClick="Check('you', 'bShow');">Correct?</button>
<input style="float:right" name="bShow" id="bShow" type="checkbox" value="">
</div>
<button onClick="ClearP();">Clear</button>
</div>
all help is much appreciated :) thank you :)

function ClearP(){
var inputs = document.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
inputs[i].value = '';
}

Give all of them another class (something like "clearable", perhaps?), then find and clear all items with that class.

How about using jQuery, and something like this:
$('[name="input"]').val("");

Related

Add Class on Scroll Issue with Vanilla JS

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

Forward GET parameter to next URL

I am building a form with HTML consisting of multiple pages, one per question (due to layout reasons). I use the 'GET' method to pass the parameters of the form input to next page, like this:
<form action="example.html" method="GET">
<input type="number" step="0.1" name="Machine" id="Machine" placeholder="Machine">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>
This works fine and leads me to the URL
/example1.html?Machine=Input
On the next page, I use the same code as mentioned above (only different name and id for the input), but when I submit that page the parameters from the first page won't be redirected (of course). So the URL looks somewhat like this:
/example2.html?Amount=Input
I would need to have the parameters of the first page, too though. Basically looking like this
/example2.html?Machine=Input&Amount=Input
Is there a simple way for doing this with little Javascript or even without it? Thanks for your help
You could try adding hidden input elements to your form dynamically with javascript, created with name and value pairs from the GET parameters in document.location.search.
Click Run code snippet below to see a working example.
Instead of passing your results and going to the next step, you can just hide and reveal portions (steps) of the form using JavaScript.
A framework like AngularJS would make this extremely simple to do using declarative directive. But a plain old JavaScript will suffice.
The other advantage to this approach is that you can then POST your form to the web server.
function goTo(step) {
var steps = document.querySelectorAll('[step]'),
formStep,
formStepNo,
i;
for (i = 0; i < steps.length; i++) {
formStep = steps[i];
formStepNo = formStep.getAttribute('step');
if (step == formStepNo) {
formStep.style.display = 'block';
} else {
formStep.style.display = 'none';
}
}
}
var step = 1;
goTo(step);
function nextStep() {
step++;
goTo(step);
}
function backStep() {
step--;
goTo(step);
}
<form action="example.html" method="POST">
<div step="1">
<p>Step 1</p>
<input type="number" name="Machine" id="Machine" placeholder="Machine" />
<button onclick="nextStep()" type="button">Forward</button>
</div>
<div step="2">
<p>Step 2</p>
<input type="string" name="foo" placeholder="foo"/>
<button type="button" onclick="backStep()">Back</button>
<button type="button" onclick="nextStep()">Forward</button>
</div>
<div step="3">
<p>Step 3</p>
<input type="string" name="bar" placeholder="bar"/>
<button type="button" onclick="backStep()">Back</button>
<button type="submit">Submit</button>
</div>
</form>
Use this bit to get the parameters
How can I get query string values in JavaScript?
then this bit to add in the hidden form fields to the the form to pass along on the next submit
Create a hidden field in JavaScript
so something like this
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var Amount= getParameterByName('Amount');
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "Amount");
input.setAttribute("value", Amount);
document.getElementById("example2").appendChild(input);
<form action="example1.html" method="GET" id="example1">
<input type="number" step="0.1" name="Amount" id="Amount" placeholder="Amount">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>
<form action="example2.html" method="GET" id="example2">
<input type="number" step="0.1" name="Machine" id="Machine" placeholder="Machine">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>

How to update multiple divs while typing (javascript onkeyUp)?

I have a short javascript code that updates the content of a div element (box1 in the example below). It replaces the default text ("hello") with the text typed in an input element.
I would like to modify this code so it'd update not only the box1 div, but box2 and box3 too. I tried to use getElementsByClassName, but I was unable to make it work. I would be very grateful if somebody'd help me. Thank you.
<div class="font1" id="box1">hello</div>
<div class="font2" id="box2">hello</div>
<div class="font3" id="box3">hello</div>
<input type='text' name='fname' class='chatinput' onkeyUp="document.getElementById('box1').innerHTML = this.value" />
This should work for you :)
document.querySelector('.chatinput').onkeydown = function(){
var box1 = document.querySelector('#box1'),
box2 = document.querySelector('#box2'),
box3 = document.querySelector('#box3');
box1.innerHTML = box2.innerHTML = box3.innerHTML = (this.value);
}
You basicly create a onkeydown event, and attach it to the input.chatinput. I advise you, not to use inline javascript in the HTML
Try this
<div class="font1" id="box1">hello</div>
<div class="font2" id="box2">hello</div>
<div class="font3" id="box3">hello</div>
<input type='text' name='fname' class='chatinput' onkeyUp="document.getElementById('box1').innerHTML = this.value; document.getElementById('box2').innerHTML = this.value; document.getElementById('box3').innerHTML = this.value; " />
Demo Here
document.getElementsByClassName('box') return list of element so you should do this in a for loop
function onKeyUp($this){
for(var i in document.getElementsByClassName('box'))
document.getElementsByClassName('box')[i].innerHTML = $this.value
}
<div id="box1" class="box">hello</div>
<div id="box2" class="box">hello</div>
<div id="box3" class="box">hello</div>
<input type='text' name='fname' class='chatinput' onkeyUp="onKeyUp(this)" />
jQuery:
jsfiddle
function foo(value){
$("div").each(function(){
this.innerHTML = value;
})
};
angular:
jsfiddle
<body ng-app>
<div class="font1" id="box1">Hello {{value}}</div>
<div class="font2" id="box2">hi {{value}}</div>
<div class="font3" id="box3">nihao {{value}}</div>
<input type='text' name='fname' class='chatinput' ng-model="value" />
</body>
You're on the right track. Just use the same command three times, either inline:
<input type="text" name="fname" class="chatinput" onkeyUp="
document.getElementById('box1').innerHTML = this.value;
document.getElementById('box2').innerHTML = this.value+'hello';
document.getElementById('box3').innerHTML = this.value+'world';" />
or use a JavaScript function:
<script>
function clickMe(s){
document.getElementById("box1").innerHTML = s;
document.getElementById("box2").innerHTML = s+"hello";
document.getElementById("box3").innerHTML = s+"world";
}
</script>
<input type="text" name="fname" class="chatinput" onkeyUp="clickMe(this.value)" />
(Side note: Use double quotes for HTML-attributes. Even though all browser will understand you if you use single quotes, the double quote is the standard and the only allowed way if you want to be XML/XHTML/HTML5-compatible)

Javascript to check for empty form elements, deny submit if empty, send alert message

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

Show/hide forms using buttons and JavaScript

I need to show a form using a button, and hide it when the user presses another button, because the other button shows another form. I did a similar thing with a select box, but I can't figure out how to do this.
Use the following code fragment to hide the form on button click.
document.getElementById("your form id").style.display="none";
And the following code to display it:
document.getElementById("your form id").style.display="block";
Or you can use the same function for both purposes:
function asd(a)
{
if(a==1)
document.getElementById("asd").style.display="none";
else
document.getElementById("asd").style.display="block";
}
And the HTML:
<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>
There's something I bet you already heard about this! It's called jQuery.
$("#button1").click(function() {
$("#form1").show();
};
It's really easy and you can use CSS-like selectors and you can add animations. It's really easy to learn.
If you have a container and two sub containers, you can do like this
jQuery
$("#previousbutton").click(function() {
$("#form_sub_container1").show();
$("#form_sub_container2").hide(); })
$("#nextbutton").click(function() {
$("#form_container").find(":hidden").show().next();
$("#form_sub_container1").hide();
})
HTML
<div id="form_container">
<div id="form_sub_container1" style="display: block;">
</div>
<div id="form_sub_container2" style="display: none;">
</div>
</div>
There's the global attribute called hidden. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?
var someCondition = true;
if (someCondition == true){
document.getElementById('hidden div').hidden = false;
}
<div id="hidden div" hidden>
stuff hidden by default
</div>
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden
Would you want the same form with different parts, showing each part accordingly with a button?
Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters « and » just print respectively « and » which might be interesting for the previous and next button characters.
shows_form_part(1)
/* this function shows form part [n] and hides the remaining form parts */
function shows_form_part(n){
var i = 1, p = document.getElementById("form_part"+1);
while (p !== null){
if (i === n){
p.style.display = "";
}
else{
p.style.display = "none";
}
i++;
p = document.getElementById("form_part"+i);
}
}
/* this is called at the last step using info filled during the previous steps*/
function calc_sum() {
var sum =
parseInt(document.getElementById("num1").value) +
parseInt(document.getElementById("num2").value) +
parseInt(document.getElementById("num3").value);
alert("The sum is: " + sum);
}
<div id="form_part1">
Part 1<br>
<input type="number" value="1" id="num1"><br>
<button type="button" onclick="shows_form_part(2)">»</button>
</div>
<div id="form_part2">
Part 2<br>
<input type="number" value="2" id="num2"><br>
<button type="button" onclick="shows_form_part(1)">«</button>
<button type="button" onclick="shows_form_part(3)">»</button>
</div>
<div id="form_part3">
Part 3<br>
<input type="number" value="3" id="num3"><br>
<button type="button" onclick="shows_form_part(2)">«</button>
<button type="button" onclick="calc_sum()">Sum</button>
</div>

Categories

Resources