I did a website and made a form ,and I have done the most of the validation but I am stuck at one. what I am trying to achieve here is when the the submit button of the form is clicked, a alert message show appear on screen saying thanks'customer name' for feed back and you chose 'radiobutton' and your comment was 'textincommentfield'.for one or another reason validation is not working. Any help would be great and thanks in advance , btw I am new to this.
Code: http://jsfiddle.net/92tSw/
HTML:
<title> Contact</title>
<body>
<div class="container">
<div id="wrap">
<div id="logo">
<img class="p" src="images/logo.png" align="left">
</div>
<img class="d" src="images/title.gif" align="middle">
<div id="menu">
<div id="menu2">
<ul>
<li><a href="homepage.html" ><span>Home</span></a></li>
<li><a href="about.html" ><span>About Us</span></a></li>
<li><a href="clubs.html" ><span>Clubs</span></a></li>
<li><a href="shop.html" ><span>Shop</span></a></li>
<li><a href="contact.html" ><span>Contact Us</span></a></li>
</ul>
</div>
</div>
<form>
<fieldset>
<legend style="font-size:20px; padding-top:20px;">Fill in the form Below to contact Us:</legend>
<p><label for="full name">Full Name:</label>
<input id="full name" type="text" size="40" name="customername" placeholder="Type first and last name" autofocus/></p>
<p><label for="Address">Address:</label>
<input type="text" name="address1" placeholder="Address Line 1" size="42%">
<input type="text" name="address2" placeholder="Address Line 2" size="42%">
<p><label for="Address"> </label>
<input type="text" name="city" placeholder="City/Town" size="20%">
<input type="text" name="postcode" placeholder="Post Code" size="20%"></p>
<p><label for="Telephone No.">Telephone Number:</label>
<input type="text" name="Telephone No." maxlenght="12"placeholder=" Enter Telephone No." size="42%"></p>
<p><label for="email">Email:</label>
<input name="email" type="email" size="25" placeholder="youremail#you.com" /></p>
<legend style="font-size:20px;" >Comments</legend>
<p><label for="quantity"> How great is the website?Choose one<em>*</em> :</label>
<input type="radio" name="myRadio" value="VG" >Very Great
<input type="radio" name="myRadio" value="G" >Great
<input type="radio" name="myRadio" value="NVG">Not Very Great
<input type="radio" name="myRadio" value="U" >Useless
<BR>
<BR>
<BR>
<BR>
<p><label for="comment">Your Message:</label>
<textarea cols="35" rows="5" name="comments" Placeholder="eg. please knock on the dooor, ring the bell etc." >
</textarea></p>
</fieldset>
<fieldset>
<input type="checkbox" name="Terms and Condition"value="Terms and Condition" required> Accept Terms and Condition<br>
<input id="bor" type="reset" value="Reset">
<input id="chor" type="submit" name="button" value="Submit" onclick="getMyForm(this.form)" >
</fieldset>
</div>
</div>
CSS:
form{ padding-top:100px; color:White;}
fieldset { background-color:#980000 ; margin: 1%;}
label { float:left; width:20%; text-align:right;}
legend{font-weight:bold;}
.foot {
padding-top:.75pt;
padding-bottom:.75pt;
padding-right:auto;
padding-left:auto;
width:100%;
}
JS:
function getMyForm(frm)
{
var myinfo = getRadioValue(frm.myRadio);
var customername = document.getElementById("customer").value;
var comment = document.getElementById("comment").value;
alert("Dear"+ customername + ",Thank you very much for your feedback.You have rated our site as" + myinfo +"your comment was Very informative website."+ comment +".");
}
function getRadioValue(radioArray){
var i;
for (i = 0; i < radioArray.length; i++){
if (radioArray[i].checked) return radioArray[i].value;}
return "";
}
It may be better to have the event on the form
<form id="form1" onsubmit="return getMyForm(this)">
To prevent the form from actually submitting, you have to return false; from the javascript method.
To submit the form programmatically in JS
frm.submit();
Or
document.getElementById("form1").submit();
Then return true; from the function under the right conditions to allow the submit to complete.
(I noticed you didn't include the action and method attributes on the form. I assumed this was just for the example.)
http://jsfiddle.net/92tSw/2/
Use JQuery if you are new to javascript.. its much more comfortable:
$(document).ready(function() {
$("#yourmockform").submit(function(e) {
var customername = $(this).find('#fullname').val();
var comment = $(this).find('#comment').val();
var myinfo = $(this).find('[name="myRadio"]:checked').attr('value');
alert("Dear"+ customername + ",Thank you very much for your feedback.You have rated our site as" + myinfo +"your comment was Very informative website."+ comment +".");
return false;
});
});
Related
Error codesI created the signup form page and If I skip entering the information, I want to make an alert box with javascript. But in JavaScript, it's showing the errors and doesn't show any alert if I skip. Is there any way to fix it? I will provide error codes with screenshot. Also, I want to do that If I click submit, I want to show Your request is successful box.
function validateForm() {
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var birthday = document.forms["myForm"]["birthday"].value;
var interest = document.forms["myForm"]["shopping"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
if (email == "") {
alert("Email must be filled out");
return false;
}
if (birthday == "") {
alert("Fill your birthday please");
return false;
}
if (shopping == "1") {
alert("Select your interested thing to do");
return false;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Busy Bee Florist</title>
<meta charset="utf-8">
<link rel="stylesheet" a href="css/style.css">
</head>
<body>
<div id="containers">
<header>
<img src="images/logo.png">
</header>
<nav>
<div class="navbar">
Sign Up For Special Deals!"
Contact
Account
Cart
Gallery
<div class="dropdown">
<button class="dropbtn">Colors
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
White
Red
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Occasions
</button>
<div class="dropdown-content">
Congratulations
Generic
</div>
</div>
</div>
</nav>
<form></form>
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post"></form>
<div class="container">
<h1>Busy Bee Florist</h1>
<h4> Please Fill Up In the Form</h4>
<form>
<fieldset>
<legend>Personal Information:</legend>
Full Name: <input type="text" style="margin-left: 18px;" name="name" placeholder="Your Name"><br><br>
Email: <input type="email" style="margin-left: 51px;" placeholder="example#gmail.com" name="email"><br><br>
Date of birth: <input type="date" name="birthday">
</fieldset>
<br>
Which special offers you interest most?<br><br>
<input type="checkbox" name="shopping" value="Shopping"> Lemon Meringue Pie <br><br>
<input type="checkbox" name="shopping" value="Dining"> Respberry Cake <br><br>
<input type="checkbox" name="shopping" value="Dancing"> Bluebarry Muffins<br><br>
<input type="checkbox" name="shopping" value="caramelslice"> Caramel Slice <br><br>
<input type="checkbox" name="shopping" value="cheeryripeslice">Cheery Ripe Slice <br><br>
<input type="checkbox" name="shopping" value="chocolatechip">Chocolate Chip Muffin<br><br>
<div class="test3"><b>Terms and Condition</b><font color="red"></font></div>
<div class="test3"> <input type="radio" name="TC" value="agree" >I Agree</div>
<div class="test3"> <input type="radio" name="TC" value="disagree">I Disagree</div>
<br><br>
<div class="w">
<p>Please provide any additional feedbacks:- </p>
<br><br>
<textarea name="message" rows="5" cols="45" placeholder="Please Type Here...."></textarea>
<br><br>
</div>
<br><br>
<div id="q">
<button class="btn-submit" value="Submit Reservation" type="submit"> Submit </button>
<button class="btn-reset" value="Clear Input" type="reset"> Clear Input</button>
</div>
</form>
</div>
</form>
</body>
</html>
Let's perform some clean up to your HTML code first.
You have this in your form declaration
<form></form>
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post"></form>
Let's remove the empty form declaration and remove the close form tag immediately after your declaration. Change those 2 lines to the following:
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post">
It should function a lot more appropriately after those changes.
You had a few issues, as I detailed out in my comment.
Targeting the wrong form, myForm element was empty. So I changed this accordingly.
In your JS, you had interest declared but you tried to use variable shopping which you did not declare. So I changed that shopping to interest.
After amending all those mistakes, the code worked.
function validateForm(event) {
event.preventDefault(); //Pause form from submitting.
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var birthday = document.forms["myForm"]["birthday"].value;
var interest = document.forms["myForm"]["shopping"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
if (email == "") {
alert("Email must be filled out");
return false;
}
if (birthday == "") {
alert("Fill your birthday please");
return false;
}
if (interest == "1") {
alert("Select your interested thing to do");
return false;
}
else event.target.submit(); //submit, all checks were completed
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Busy Bee Florist</title>
<meta charset="utf-8">
<link rel="stylesheet" a href="css/style.css">
</head>
<body>
<div id="containers">
<header>
<img src="images/logo.png">
</header>
<nav>
<div class="navbar">
Sign Up For Special Deals!"
Contact
Account
Cart
Gallery
<div class="dropdown">
<button class="dropbtn">Colors
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
White
Red
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Occasions
</button>
<div class="dropdown-content">
Congratulations
Generic
</div>
</div>
</div>
</nav>
<div class="container">
<h1>Busy Bee Florist</h1>
<h4> Please Fill Up In the Form</h4>
<form name="myForm" action="action_page.php" onsubmit="validateForm(event)" method="post">
<fieldset>
<legend>Personal Information:</legend>
Full Name: <input type="text" style="margin-left: 18px;" name="name" placeholder="Your Name"><br><br>
Email: <input type="email" style="margin-left: 51px;" placeholder="example#gmail.com" name="email"><br><br>
Date of birth: <input type="date" name="birthday">
</fieldset>
<br>
Which special offers you interest most?<br><br>
<input type="checkbox" name="shopping" value="Shopping"> Lemon Meringue Pie <br><br>
<input type="checkbox" name="shopping" value="Dining"> Respberry Cake <br><br>
<input type="checkbox" name="shopping" value="Dancing"> Bluebarry Muffins<br><br>
<input type="checkbox" name="shopping" value="caramelslice"> Caramel Slice <br><br>
<input type="checkbox" name="shopping" value="cheeryripeslice">Cheery Ripe Slice <br><br>
<input type="checkbox" name="shopping" value="chocolatechip">Chocolate Chip Muffin<br><br>
<div class="test3"><b>Terms and Condition</b><font color="red"></font></div>
<div class="test3"> <input type="radio" name="TC" value="agree" >I Agree</div>
<div class="test3"> <input type="radio" name="TC" value="disagree">I Disagree</div>
<br><br>
<div class="w">
<p>Please provide any additional feedbacks:- </p>
<br><br>
<textarea name="message" rows="5" cols="45" placeholder="Please Type Here...."></textarea>
<br><br>
</div>
<br><br>
<div id="q">
<button class="btn-submit" value="Submit Reservation" type="submit"> Submit </button>
<button class="btn-reset" value="Clear Input" type="reset"> Clear Input</button>
</div>
</form>
</div>
</form>
</body>
</html>
I have a single page website that has three buttons (styled with jQuery Mobile) as a menu which, when clicked, show different content that is contained on hidden "div". However, on the main page I have a form connected to mysql which lets users join in, but when you fill the form and click the button "submit", the page "kind of reloads" and the header buttons don't work anymore. So, when form is submitted on main div, menu stops to work (it doesn't display and hide content anymore) Is there any solution to this?
(I've included a snippet but here the problem is not seen as I can't connect it to mysql).
function updateContent(hash) {
var newClass = hash.substring(1);
var newContent = $("." + newClass).html();
$("#content").html(newContent);
$("#content").css("display", "none");
}
if (window.location.hash) {
updateContent(window.location.hash);
}
$(".contentUpdate").click(function() {
updateContent($(this).attr("id"));
$("#content").fadeIn();
$(".contentUpdate").removeClass("ui-btn-active");
});
.hiddenContent {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<div id="menu">
<div data-role="navbar">
<ul>
<li><a class="contentUpdate" id="#swim">Swim</a></li>
<li><a class="contentUpdate" id="#cycle">Cycle</a></li>
<li><a class="contentUpdate" id="#run">Run</a></li>
</ul>
</div>
<!-- /navbar -->
</div>
<div id="content">
FORM
<div id="joinForm">
<form method="post">
<label for="name">Name and Surname(s)</label>
<input type="text" id="name" placeholder="Adam Smith" value="" name="name" />
<label for="email">Email</label>
<input type="text" id="email" placeholder="example#esade.edu" value="" name="email" />
<label for="phone">Phone</label>
<input type="text" id="phone" placeholder="+34 671 542 893" value="" name="phone" />
<fieldset data-role="controlgroup">
<p>Choose the sports you're interested in:</p>
<input type="checkbox" id="swimming" name="swimming" value="" />
<label for="swimming">Swimming</label>
<input type="checkbox" id="cycling" name="cycling" value="" />
<label for="cycling">Cycling</label>
<input type="checkbox" id="running" name="running" value="" /> <label for="running">Running</label>
</fieldset>
<div align="right">
<button type="submit" class="ui-shadow ui-btn ui-corner-all ui-btn-inline" name="submit" id="submit" value="submit">Submit</button>
</div>
</form>
</div>
</div>
<div class="hiddenContent swim">
swim
</div>
<div class="hiddenContent cycle">
cycle
</div>
<div class="hiddenContent run">
run
</div>
Thank you!
I need help putting multiple if statements into my function. I need it to check to make sure their is an input in input1 (first name) input2 (lastname) input6 (email) and input8(message box). I need it to then pop up an alert if one field is empty and state what field that is. I coded it up earlier with seperate functions and then called the functions on submit but then it pops up all the alerts pending that the field is empty. I would rather have it pop up only one alert then return false to exit the script so it doesnt spam you with 4 alerts and then cancel the script. Thanks!
Update: I have it working for the first three fields i need (First/Lastname and email) I just need to add an alert for the message box, but it seems .length is not working for the message box... any ideas? I tried doing the same as the others, but it breaks the code and does nothing.
<!DOCTYPE html>
<html>
<head>
<title>Contact Us</title>
<link rel="stylesheet" type="text/css" href="view.css" media="all">
<script type="text/javascript" src="view.js"></script>
</head>
<body id="main_body" >
<div id="form_container">
<form id="form_1121982" class="appnitro" enctype="multipart/form-data" method="post" action="">
<div class="form_description">
<p></p>
</div>
<h1 align="center">Contact Us</h1>
<ul >
<li id="li_1" >
<label class="description" for="element_1">Name </label>
<span>
<input id="input1" name= "input1" class="element text" maxlength="255" size="8" value=""/>
<label>First</label>
</span>
<span>
<input id="input2" name= "input2" class="element text" maxlength="255" size="14" value=""/>
<label>Last</label>
</span>
</li> <li id="li_2" >
<label class="description" for="element_2">Phone </label>
<span>
<input id="input3" name="input3" class="element text" size="3" maxlength="3" value="" type="text"> -
<label for="input3">(###)</label>
</span>
<span>
<input id="input4" name="input4" class="element text" size="3" maxlength="3" value="" type="text"> -
<label for="input4">###</label>
</span>
<span>
<input id="input5" name="input5" class="element text" size="4" maxlength="4" value="" type="text">
<label for="input5">####</label>
</span>
</li> <li id="li_3" >
<label class="description" for="input6">Email </label>
<div>
<input id="input6" name="input6" class="element text medium" type="text" maxlength="255" value=""/>
</div>
</li> <li id="li_4" >
<label class="description" for="input7">Upload a File </label>
<div>
<input id="input7" name="input7" class="element file" type="file"/>
</div>
</li> <li id="li_5" >
<label class="description" for="input8">Paragraph </label>
<div>
<textarea id="input9" name="input8" class="element textarea medium"></textarea>
</div>
</li>
<li class="buttons">
<input type="hidden" name="form_id" value="1121982" />
<input id="saveForm" class="button_text" type="button" name="submit" value="Submit" onclick="myFunction1();" />
<input type="reset" value="Reset">
</li>
</ul>
</form>
<div id="footer">
</div>
</div>
</body>
</html>
function myFunction1()
{
var field1 = document.getElementById("input1").value.trim(); //checks length of first name
var field2 = document.getElementById("input2").value.trim(); //checks length of first name
var field6 = document.getElementById("input6").value.trim(); //checks length of first name
if ( field1.length == 0 )
{
alert("Please Fill In Your First Name");
return false;
}
else if ( field2.length == 0 )
{
alert("Please Fill In Your Last Name");
return false;
}
else if( field6.length == 0 )
{
alert("Please Fill in Your Email");
return false;
}
}
Place the return within your if statements.
if (field1.length == 0) {
alert("Please Fill In Your First Name");
return false;
}
To answer the second part of your question, though you haven't supplied the javascript on how you're trying to get the textarea.
Firstly, your naming convention isn't great. You should use something that is meaningful so you don't make mistakes which I think you have done here.
<textarea id="input9" name="input8" class="element textarea medium"></textarea>
Your textarea has id=input9 with name=input8. Going by how you were doing this originally, it should be id=input8?
For your fields, use the naming of your labels. Eg id=Firstname, id=Email etc.
I need to get the label of each element and apply it to the input as a placeholder attribute, I get about half way though but cannot seem to get just the text of the element in order to add a attribute
Please note that i am not able to use jQuery in any regard
JS:
var elements = document.querySelectorAll('p.form-field');
Array.prototype.forEach.call(elements, function(el, i){
var chel = el.querySelectorAll('.field-label');
console.log(chel.textContent);
});
HTML:
<form accept-charset="UTF-8" method="post" action="nottelling" class="form" id="pardot-form">
<p class="form-field first_name pd-text required ">
<label class="field-label" for="25492_61334pi_25492_61334">First Name</label>
<input type="text" name="25492_61334pi_25492_61334" id="25492_61334pi_25492_61334" value="" class="text" size="30" maxlength="32" onchange="" />
</p>
<div id="error_for_25492_61334pi_25492_61334" style="display:none"></div>
<p class="form-field last_name pd-text required ">
<label class="field-label" for="25492_61336pi_25492_61336">Last Name</label>
<input type="text" name="25492_61336pi_25492_61336" id="25492_61336pi_25492_61336" value="" class="text" size="30" maxlength="32" onchange="" />
</p>
<div id="error_for_25492_61336pi_25492_61336" style="display:none"></div>
<p class="form-field email pd-text required ">
<label class="field-label" for="25492_61338pi_25492_61338">Email</label>
<input type="text" name="25492_61338pi_25492_61338" id="25492_61338pi_25492_61338" value="" class="text" size="30" maxlength="255" onchange="piAjax.auditEmailField(this, 25492, 61338, 12545572);" />
</p>
<div id="error_for_25492_61338pi_25492_61338" style="display:none"></div>
<p class="form-field company pd-text required ">
<label class="field-label" for="25492_61340pi_25492_61340">Company</label>
<input type="text" name="25492_61340pi_25492_61340" id="25492_61340pi_25492_61340" value="" class="text" size="30" maxlength="100" onchange="" />
</p>
<div id="error_for_25492_61340pi_25492_61340" style="display:none"></div>
<p style="position:absolute; width:190px; left:-9999px; top: -9999px;visibility:hidden;">
<label for="pi_extra_field">Comments</label>
<input type="text" name="pi_extra_field" id="pi_extra_field" />
</p>
<input name="_utf8" type="hidden" value="☃" />
<p class="submit">
<input type="submit" accesskey="s" value="Send Message" />
</p>
<input type="hidden" name="hiddenDependentFields" id="hiddenDependentFields" value="" />
</form>
var labels = document.querySelectorAll("label");
var i = labels.length;
while (i--) {
var label = labels.item(i);
var text = label.textContent;
label.parentNode.classList.contains("required") && (text += "*");
label.nextElementSibling.setAttribute("placeholder", text);
}
While the earlier answers work, I'd suggest a simpler approach, such as:
function placeholderLabels() {
// get <input> elements that are in a <p> and follow a <label>:
var inputs = document.querySelectorAll('p label + input');
// iterate over those <input> elements:
Array.prototype.forEach.call(inputs, function(input) {
// input is the current <input> from the NodeList over which we're
// iterating, here we set its placeholder property to either:
// the textContent of the first <label> associated with the <input>
// or to an empty string, if there's no associated <label>:
input.placeholder = input.labels.length ? input.labels[0].textContent.trim() : '';
});
}
placeholderLabels();
function placeholderLabels() {
var inputs = document.querySelectorAll('p label + input');
Array.prototype.forEach.call(inputs, function(input) {
input.placeholder = input.labels.length ? input.labels[0].textContent.trim() : '';
});
}
placeholderLabels();
label {
display: inline-block;
width: 7em;
}
p.required label::after {
content: '*';
}
<form accept-charset="UTF-8" method="post" action="nottelling" class="form" id="pardot-form">
<p class="form-field first_name pd-text required ">
<label class="field-label" for="25492_61334pi_25492_61334">First Name</label>
<input type="text" name="25492_61334pi_25492_61334" id="25492_61334pi_25492_61334" value="" class="text" size="30" maxlength="32" onchange="" />
</p>
<div id="error_for_25492_61334pi_25492_61334" style="display:none"></div>
<p class="form-field last_name pd-text required ">
<label class="field-label" for="25492_61336pi_25492_61336">Last Name</label>
<input type="text" name="25492_61336pi_25492_61336" id="25492_61336pi_25492_61336" value="" class="text" size="30" maxlength="32" onchange="" />
</p>
<div id="error_for_25492_61336pi_25492_61336" style="display:none"></div>
<p class="form-field email pd-text required ">
<label class="field-label" for="25492_61338pi_25492_61338">Email</label>
<input type="text" name="25492_61338pi_25492_61338" id="25492_61338pi_25492_61338" value="" class="text" size="30" maxlength="255" onchange="piAjax.auditEmailField(this, 25492, 61338, 12545572);" />
</p>
<div id="error_for_25492_61338pi_25492_61338" style="display:none"></div>
<p class="form-field company pd-text required ">
<label class="field-label" for="25492_61340pi_25492_61340">Company</label>
<input type="text" name="25492_61340pi_25492_61340" id="25492_61340pi_25492_61340" value="" class="text" size="30" maxlength="100" onchange="" />
</p>
<div id="error_for_25492_61340pi_25492_61340" style="display:none"></div>
<p style="position:absolute; width:190px; left:-9999px; top: -9999px;visibility:hidden;">
<label for="pi_extra_field">Comments</label>
<input type="text" name="pi_extra_field" id="pi_extra_field" />
</p>
<input name="_utf8" type="hidden" value="☃" />
<p class="submit">
<input type="submit" accesskey="s" value="Send Message" />
</p>
<input type="hidden" name="hiddenDependentFields" id="hiddenDependentFields" value="" />
</form>
It's worth reiterating at this point, however, that this is not a good user-interface; the placeholder should not replace the <label>, and if used should provide some guidance on what the <input> expects, such as the format or an expected value.
You’re close: the problem is just that you are trying to use the object returned by the second querySelectorAll as if it were an element. It returns a collection, even when there is just one matching element. If you know that only one element matches it, simply index it with a zero. The same way you can access the input element, if you know there is only one such element inside each p element. So the essential code can be as follows:
var elements = document.querySelectorAll('p.form-field');
Array.prototype.forEach.call(elements, function(el, i){
el.querySelectorAll('input')[0].placeholder =
el.querySelectorAll('.field-label')[0].textContent;
});
There are several possible approaches, depending on the assumptions you make about the source code.
Note: Duplicating label texts as placeholders is useless and disturbing. Replacing label text by placeholders is bad for accessibility and frowened upon in the HTML5 spec. But maybe the operation you are doing has some different purpose.
Is there a way to get a javascript calculator to calculate an answer as a user types instead of having to press a "calculate" button like in this example?
<form name="form" id="form">
<input type="Text" name="weight" size="4"> Weight (in Kilos)
<input type="Text" name="height" size="4"> Height (in Centimeters)<br>
<input type="Text" name="BodyMassIndex" id="BodyMassIndex" size="4"> BMI
<input type="button" style="font-size: 8pt" value="Calculate" onClick="calculateBMI()" name="button">
</form>
Using onblur is an improvement but you still have to click out of the text box to blur the input to get the answer. Like I say, I'd prefer the answer to update in real time. Any suggestions? Thanks!
If the user is typing, you can use the keyup event. So basically, everytime the user types a key, your event handler fires and can update the view/display.
Use onkeyup.
e.g.
<form name="form" id="form">
<input type="Text" name="weight" size="4" onkeyup="calculateBMI()"> Weight (in Kilos)
<input type="Text" name="height" size="4" onkeyup="calculateBMI()"> Height (in Centimeters)<br>
<input type="Text" name="BodyMassIndex" id="BodyMassIndex" size="4"> BMI
<input type="button" style="font-size: 8pt" value="Calculate" onClick="calculateBMI()" name="button">
</form>
jsFiddle example.
EDIT: Changed to onkeyup after finding onkeypress didn't work for me in Chrome.
HTML
<form name="form" id="form">
<input class="bmi_input" type="Text" name="weight" size="4"/> Weight (in Kilos)
<input class="bmi_input" type="Text" name="height" size="4"/> Height (in Centimeters)
<input class="bmi_input" type="Text" name="BodyMassIndex" id="BodyMassIndex" size="4"/> BMI
</form>
Javascript
function calculateBMI() {
console.log("I'm here");
}
var els = document.getElementsByClassName("bmi_input");
var sz = els.length;
for(var n = 0; n < sz; ++n) {
els[n].onkeyup = calculateBMI;
}
http://jsfiddle.net/dbrecht/94hxS/
You could handle the onChange event in each of the input text boxes, calling your calculate function:
<form name="form" id="form">
<input type="Text" name="weight" size="4" onChange="calculateBMI()"> Weight (in Kilos)
<input type="Text" name="height" size="4" onChange="calculateBMI()"> Height (in Centimeters)<br>
<input type="Text" name="BodyMassIndex" id="BodyMassIndex" size="4"> BMI
</form>
Here is a simple example of two user text inputs, which "instantly" calculate the answer based on the called JavaScript function (The functions are also included). In addition, this code provides the option to also use a button (it is currently commented out). Hope this helps!
HTML:
<body>
<div id="form-main">
<div id="form-div">
<form class="form" id="form1" method="post">
<p class="celcius"><h2 style="color:#FFF">Input:</h2>
<input name="celsius" type="text" class="feedback-input" placeholder="Temperature (Celsius)" onkeyup="Conversion()" id="celsius" />
</p>
<hr>
<h2 style="color:#FFF">Result:</h2>
<p class="fahrenheit">
<input name="fahrenheit" type="text" class="feedback-input" id="fahrenheit" onkeyup="Conversion2()" placeholder="Temperature (Fahrenheit)" />
</p>
<!--
<div class="submit">
<input type="button" value="CONVERT" id="button-blue" onClick="Conversion()"/>
<div class="ease"></div>
</div>
-->
</form>
</div>
</body>
JavaScript:
function Conversion() {
var tempCels = parseFloat(document.getElementById('celsius').value);
tempFarh =(tempCels)*(1.8)+(32);
document.getElementById('fahrenheit').value= tempFarh;
}
function Conversion2() {
var tempFarh = parseFloat(document.getElementById('fahrenheit').value);
tempCels =(tempFarh - 32)/(1.8);
document.getElementById('celsius').value= tempCels;
}