I have created two html pages; main info, and Entrance page. the Entrance page is supposed to act similar to a password so that under aged users do not enter the page. problem is my submit button is not doing anything. I would highly appreciate if somebody could help me get it to work since I need to finish it today.
Here is the code I have so far:
<html>
<head>
<!-- this is how you add a code comment-->
<title> Entrance Page </title>
</head>
<body bgcolor="#CEF6F5">
<form>
<h2 align=center><u> Please fill out the following information to proceed to the festival: </u></h2>
<br><br>First Name:<input type="text" name="First Name" id="first"> Last Name:<input type="text"
name="Last Name" id="last">
<br><br> age:<select name="age" id="age">
<option value="1"> below 10 </option>
<option value="2"> 10 </option>
<option value="3"> 11 </option>
<option value="4"> 12 </option>
<option value="5"> 13 </option>
<option value="6"> 14 </option>
<option value="7"> 15 </option>
<option value="8"> 16 </option>
<option value="9"> 17 </option>
<option value="10"> 18 </option>
<option value="11"> 19 </option>
<option value="12"> 20 </option>
<option value="13"> above 20 </option>
</select>
</form>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p align="center"> <button type="submit" onclick="run()"> Submit </button> </p>
<p><p id="p1"> </p>
<script>
var firstName = document.getElementById("first").value
var lastName = document.getElementById("last").value
var age = document.getElementById("age").value
var isNum = " ";
isNum = isNum + isNaN(firstName)
function run() {
var firstName = document.getElementById("first").value
var lastName = document.getElementById("last").value
if (age < 10 ) {
window.alert("your too young to enter in this event!")//go back to Entrance page
} else if (age > 10) {
window.alert("welcome to the Oktoberfest website!");
window.location.replace("Cost%20of%20an%20Event.html");//go to main website
} else if (age == 10) {
window.alert("lucky! you are just barely old enough to join!")
window.location.replace("Cost%20of%20an%20Event.html");//go to main website
}
}
if (isNum == true) {
window.alert("your name cannot be a number");
}//go back to Entrance page
while (firstName.length ==0) {
window.alert ("you didn't enter a first name ")
document.getElementById("block").value//go back to Entrance page
while (lastNamet.length ==0) {
window.alert ("you didn't enter a last name ")
document.getElementById("block").value//go back to Entrance page
</script>
</body>
</html>
Because your submit button is outside of your form element. This is allowed, but you'd need to add form="id of form here" to associate it with the form.
Even if you fix this issue, all that will happen is that your page will refresh because you also need to specify an action and a method for your form so that it knows how and where to submit the form data.
Learn about the form element here.
You've also got several other problems:
You don't have closing brackets at the end of each of your while
blocks. Your while loops run immediately (before the user has had a
chance to input anything into the form) and so they immediately cause
alert() messages and get you into an infinite loop. You should
probably stay away from while and just check the input in the
submit event of the form and if the input isn't right, display
your error - - no need for a loop.
And your use of HTML is incorrect in several places:
The bgcolor and align attributes are deprecated. All formatting
should be done with CSS, not HTML.
The heading elements (h1, h2, etc.) are for defining sections of
the document. They should not be used because of the formatting
applied to the text within them. As such, you shouldn't have an h2
if you aren't creating a sub-section of an h1, which you are not.
The <br> element should not be used to create artificial vertical
white space. Again, CSS is for layout and styling. br is meant to
force a line break between content, not for introducing blank lines.
Related
I recently came across a situation where I was working on a huge form with atleast 60 fields and I wanted that form to only submit if all fields were filled and if not, I wanted to show a custom message (Sweetalert) for every field not filled.
For example, If first name was left empty, show the message "Please enter your first name", If country of residence was not selected, show them the message that "Please select your country of residence" so on and so forth.
While I was writing tons of if and else statements to match every field using document.getElementById(), this thought of not doing things right came into my mind. I tried searching the web for this but was unable to find a suitable way of doing such things. Can anyone suggest me a better way rather then writing if else statements of 100 lines ?
By adding a specific class to your form controls you'd be able to retrieve them and iterate through them in order to check which ones are not filled.
Let's say this is your form:
<form id="myForm" name="myForm" novalidate>
<div>
<label for="control_1">Label_1:</label>
<input type="text" id="control_1" name="control_1" class="control" />
</div>
<div>
<label for="control_2">Label_2:</label>
<input type="text" id="control_2" name="control_2" class="control" />
</div>
<div>
<label for="control_3">Label_3:</label>
<input type="text" id="control_3" name="control_3" class="control" />
</div>
<div>
<label for="control_4">Label_4:</label>
<select id="control_4" name="control_4" class="control">
<option value="option_1">Option 1</option>
<option value="option_2">Option 2</option>
<option value="option_3">Option 3</option>
</select>
</div>
<div>
<input type="submit" value="Submit!" />
</div>
</form>
Then you can use the .control class to retrieve all controls and check them:
function onSubmit(e) {
e.preventDefault();
const controls = document
.getElementById("myForm")
.querySelectorAll(".control");
controls.forEach(control => {
if (!isControlFilled(control)) {
console.log(control.id);
// Do whatever you want with control's id
}
});
}
// This is just for illustrative purposes
// Should be adapted to cover all control types
function isControlFilled(control) {
return control.value ? true : false;
}
My form includes a search that takes about 10 seconds. The submit button is titled SEARCH and upon clicking I have set this up to change to SEARCHING. This is the code:
<input type=submit class=button
value= Search
onclick="javascript:formSubmit();this.value='Searching...'">
But now I need to validate that an email field and another field are completed so that the button text changes to SEARCHING only if validated.
I tried this, but it does not work:
<input type=submit class=button
value= Search
onclick="myFunction();javascript:formSubmit();this.value='Searching...'">
<script>
function myFunction() {
if ( document.getElementsByName('numberadults')[0].value == '0' )
alert('The number of adults must be more than zero!');
document.getElementById("myEmail").required = true;
document.getElementById("demo").innerHTML = "The required property was set. The email field must now be filled out before submitting the form.";
}
</script>
Here is the html of the two fields being validated:
<select name=numberadults class=cboStyleZ>
<option value=0 selected>
0
</option>
<option value=1>
1
</option>
<option value=2>
2
</option>
<option value=3>
3
</option>
<option value=4>
4
</option>
<option value=5>
5
</option>
<option value=6>
6
</option>
<option value=--->
---
</option>
</select>
<input type="email" id="myEmail" class=cboStyleZ1 name="eaddr"
placeholder="Your email is all we need">
<script>
function myFunction() {
//other statements if required
document.getElementById("search").value = "searching";
}
</script>
<input type=submit class=button id="search"
value="search";
onclick="myFunction()">
I think this code can help you
The following click handler:
onclick="myFunction();javascript:formSubmit();this.value='Searching...'"
doesn't indicate how the validation in myFunction would affect the form submission and the text change.
There are several ways to skin a cat here, but in general, you could rely on control structures like if or using short-circuit operators to change the execution flow based on the value of an expression that interests you (e.g.: the return value of myFunction())
HTML
onclick="if(myFunction()) { javascript:formSubmit();this.value='Searching...'} "
JS
function myFunction() {
if ( document.getElementsByName('numberadults')[0].value == '0' ) {
// ...
// Display what is wrong with the form to the user
// ...
return false;
}
return true;
}
Im helping a friend building a basic site. My javascript skills leaves much to be desired so I am learning I started with Javascript instead of Jquery library (sidenote: should I just go with Jquery from the start...?)
So I have the following:
Form with 3 radio buttons value low(1), medium(2), high(3)
Slider with amount
Select with duration.
The formula is calculated by user selecting risk (radio btns) amount (slider) duration (dropdowm)
When the user changes risk, or amount, or duration the total should get updated, and a button displayed.
So I came up with the following javascript:
JAVASCRIPT:
function getReturn(){
var risk = document.forms[0];
var years = document.getElementById("investmentDuration").value;
var slideAmount = document.getElementById("slideAmount").value;
var txt;
var returns;
var i;
for(i = 0; i < risk.length; i++){
if(risk[i].checked){
txt = risk[i].value;
//for
if(txt == 1){
returns = (slideAmount * 0.06)*years;
returns = Math.ceil(returns); // NO decimals
}
if(txt == 2){
returns = slideAmount * 0.11;
returns = Math.ceil(returns)*years; // NO decimals
}
if(txt == 3){
returns = slideAmount *0.17;
returns = Math.ceil(returns)*years; // NO decimals
}
}//if
}//for
I then added the getReturn() function to each element in the form...
I get the following when I try and run it, here is my JS FIDDLE
ERROR: getReturn() is not defined
HTML (note the on click function on each element)
<h2>SELECT INVESTMENT RISK LEVEL</h2>
<section>
<div>
<input type="radio" id="control_01" onclick="getReturn()" name="risk" value="1" checked>
<label for="control_01">
<h2>LOW RISK</h2>
<p>Slow & Steady. An Product Focused On Low Risk But Long term Gains</p>
</label>
</div>
<div>
<input type="radio" id="control_02" name="risk" onclick="getReturn()" value="2">
<label for="control_02">
<h2>MEDIUM</h2>
<p>Prepare For Glory. Medium To High Returns, Over A Medium To Long Period.</p>
</label>
</div>
<div>
<input type="radio" id="control_03" name="risk" onclick="getReturn()" value="3">
<label for="control_03">
<h2>High Risk</h2>
<p>Hardcore Investor. Tailored Based Package Focused on High Returns Over Short Periods</p>
</label>
</div>
</section>
<h4 style="color: black;">INVESTMENT AMOUNT:</h4>
<input type="range" id="slideAmount" name="slideAmount" onchange="getReturn()" value="6500" step="25" min="1000" max="10000">
<p>Number Of Years</p>
<select name="investmentDuration" id="investmentDuration" onclick="getReturn()">
<option value="1" selected>1 Year</option>
<option value="2">2 Years</option>
<option value="3">3 Years</option>
<option value="4">4 Years</option>
<option value="5">5 Years</option>
</select>
UPDATE
I got it to work however I feel
Having a onclick() / onchange = function() on each element seems inefficient.
I feel the code is prone to bugs if the page should get larger and expanded on.
Any constructive criticism and / or advice appreciated on how I can work and improve on this. Many Thanks
You get the
getReturn() is not defined
error because your code is inside an onLoad event (that is the default in jsfiddle)
You need to change this setting as shown in the image so that your function is in the global scope and thus callable from the DOM.
Then you also need to add the #returns element in your html.
A final improvement might be to use the oninput event on the range element so that is updates while you slide
All fixes: https://jsfiddle.net/gaby/o1zmvmL9/2/
I am building a reminder application with Phonegap using JS, HTML and CSS, the screen currently have a "Taken" button, when user clicks it, it will display a list of the medications the user is taking in a checkbox format, so user can choose which medication they have taken. Here's the JS code:
function show(){
document.getElementById("zero").style.display = "inline-block";
document.getElementById("aa").style.display = "inline-block";
}
function hide() {
document.getElementById("zero").style.display = "none";
document.getElementById("aa").style.display = "none";
}
function validate() {
var msg = [];
[].forEach.call(document.querySelectorAll('input[type="checkbox"]:not(:checked)'), function(elem, index) {
msg.push(elem.name);
});
alert(msg.length ? 'Why didnt you take ' + msg.join(' and ') : 'Well done you have taken all medications!');
}
function showDiv(){
document.getElementById('welcomeDiv').style.display = "block";
}
And here's the HTML:
<div class="inner" id=text><button onClick="show()">Taken</button>
</div>
<div id=aa style="display:none">
<form>
<input type="checkbox" name="Medication One" value="one">Supplement One<br>
<input type="checkbox" name="Medication Two" value="two">Supplement Two<br>
<input type="checkbox" name="Medication Three" value="three">Supplement Three<br>
<div id="welcomeDiv" style="display:none;" class="dropdown" title="Basic dialog">
<select>
<option value="" disabled="disabled" selected="selected">Please choose one</option>
<option value="forget">Forget to take</option>
<option value="notfeeling">Not feeling like taking it</option>
<option value="sideeffect">Worried about side-effects</option>
<option value="sideeffect">Run out of supplements</option>
<option value="others">Others</option>
</select>
<input type="submit" onClick="hide()" value="Submit">
</div>
<input id=xbutton type="button" onClick="this.style.display='none';validate();showDiv()" value="Submit">
</form>
</div>
So now when the user selects the reason as to why they didn't take at least one of their medication, an alert will display saying "Why didn't you take (medication name) /and (medication name)?" and a drop down box will display allowing user to choose the reason. However what I want to do is that if the user checked all checkboxes (meaning they have taken all medications), then the dropdown box will not appear, just an alert displaying "Well done you have taken all medications".
And I am not sure how to integrate that into my code, any help will be appreciated.
With some of the same code you wrote you can tell if all the inputs are checked:
if(document.querySelectorAll('input[type="checkbox"]:not(:checked)').length==0) {
alert("well done");
}
I have a small form.
Two select box elements and a submit button.
The select box elements collectively when selections are chosen, fire off an ajax request.
What I want to do is, disable the submit button UNTIL user has made selections from the select drop downs.
They must make a selection from BOTH select drop downs, before the Submit button is enabled.
I dont mind if the submit button is hidden until selections made.
Brief Code:
<form id="ad_form" method="post" action="">
<p>
<select id="ad_type" name="ad_type">
<option value="" selected="selected">Select premium ad type</option>
<option value="<?php echo TYPE_USER;?>">Featured Agent</option>
<option value="<?php echo TYPE_LISTING;?>">Featured Listing</option>
</select>
<label for="ad_type" class="labelStrong">Advertising Type</label>
</p>
<p>
<select id="ad_duration" name="ad_duration">
<option value="" selected="selected">Select premium ad duration</option>
<option value="weekly">Weekly</option>
<option value="fortnightly">Fortnightly</option>
<option value="monthly">Monthy</option>
</select>
<label for="ad_duration" class="labelStrong">Advertising Duration</label>
</p>
<p>
<div id="calender">
</div>
</p>
<p>
<input type="submit" name="submit" value="Submit" id="submitorder" />
</p>
</form>
Here's a demo that seems to do what you want:
http://jsfiddle.net/Yr59d/
That javascript code would go in a $(document).ready() block
$(function() {
$("#submitorder").css("visibility", "hidden");
$("#ad_form select").bind("change", function() {
if ($("#ad_type").val().length > 0 && $("#ad_duration").val().length > 0) {
$("#submitorder").css("visibility", "visible");
} else {
$("#submitorder").css("visibility", "hidden");
}
});
});
If you give all your selects a common class name (like 'required') , you can do something like this:
$('select.required').change(function() {
var total = $('select.required').length;
var selected = $('select.required option:selected').length;
$('#submitorder').attr('disabled', (selected == total));
});
This is not tested code. This documentation might help. This jquery discussion might help too.
Gah, I'll have to agree with Kon on this one - fix-now-worry-about-it-later answers have their place but an elegant solution that is simple at the same time has to be the way to go.
My solution: (with credit from a thread at: JQuery Enable / Disable Submit Button in IE7)
$('select.required').change(function() {
var total = = $('select.required').length;
var selected = $('#ad_form').find("select.required option[value!='':selected").length;
$('#submitorder').prop('disabled', (selected != total));
});
Incidentally, thanks ctcherry for demoing the code on the JSFiddle site - I've not seen that before and will make use of it in the future!
Use listeners on both select buttons for change and check whether the other is also set. If set, enable the submit button.