I am having troubles with a script with JS, I am still learning but I am stuck for a while.
The solution should be,
IF a checkbox is checked and the value is "" <-- the msgbox should say an message that the textbox should be filled with a value, and so for each checked checkbox, if you uncheck the checkbox, it should dissapear.
Code of 2 checkboxes in html page
<label>
bangkirai
<input id="chk_bangkirai" type="checkbox" onchange="enableTextBox()" />
</label>
<input type="text" id="bangkirai" name="bangkirai" disabled onchange="enableTextBox()" />
<label>
beukenhout
<input id="chk_beukenhout" type="checkbox" />
</label>
<input type="text" id="beukenhout" name="beukenhout" disabled/>
and the JavaScript, I made for each checkbox an other function, but I need to combine the error message in the same msgbox.
function enableTextBox() {
divOutput = document.getElementById("msgbox2");
strValideer = "<ul>";
if (document.getElementById("chk_bangkirai").checked === true) {
document.getElementById("bangkirai").disabled = false;
}
else {
document.getElementById("bangkirai").disabled = true;
}
if (document.getElementById("bangkirai").value === "") {
strValideer += "<li><b>bangkirai: </b>verplicht veld</li>";
}
strValideer += "</ul>";
divOutput.innerHTML = strValideer;
}
function enableTextBox2() {
divOutput = document.getElementById("msgbox2");
strValideer = "<ul>";
if (document.getElementById("chk_beukenhout").checked === true) {
document.getElementById("beukenhout").disabled = false;
}
else {
document.getElementById("beukenhout").disabled = true;
}
if (document.getElementById("beukenhout").value === "") {
strValideer += "<li><b>beukenhout: </b>verplicht veld</li>";
}
strValideer += "</ul>";
divOutput.innerHTML = strValideer;
}
I should probably use an array or an for each itteration ... but I can only find examples with forms ...
I will keep looking for a solution myself, but I hope I can get some inspiration here by experienced coders.
Thanks in advance
You could simplify this a lot and make it more... Concise and less dependent on which checkbox you have. We will do this with an external script and no onClick attributes on our HTML. This will enable us to separate our logic code from our design code. I will also use a placeholder instead of value, as it will create issues when people need to start entering a value (aka, you need to only have the text there when theres no value etc...) It just makes it more complicated.
Since we are dealing with numbers ('stuks' or amounts), lets also only allow number values to be inserted. Lastly, I have not bothered to replicate your HTML as I think the simplified example will make it easier to understand. Update I have also added the required and disabled sattributes here, settings your input to required when the checkbox is checked and disabled when not.
Check the below snippet for comments on the steps taken to do this:
// First, let select all fieldsets like this:
var fieldsets = document.querySelectorAll( 'fieldset.checkbox-message' );
// Lets loop through them
for( let i = 0; i < fieldsets.length; i++ ){
// Lets create variables to store our fieldset, checkbox and input for later use.
let fieldset = fieldsets[ i ];
let checkbox = fieldset.querySelector( 'input[type="checkbox"]' );
let input = fieldset.querySelector( 'input[type="number"]' );
// Lets also store the message we put in placeholder
// We will also give it a default value,
// in case you forget to set the placeholder.
let message = input.placeholder || 'Please fill in the amount';
// Now lets define a function that will fill the placeholder
// based on the checked value of the checkbox
// We will be storing it in a variable because of the scope of a `for` block.
// If you would use function setState() it might be defined globally
// So multiply checkboxes would not work.
let setState = function(){
if( checkbox.checked ){
input.placeholder = message;
input.disabled = false;
input.required = true;
} else {
input.placeholder = '';
input.disabled = true;
input.required = false;
}
}
// Now lets listen for changes to the checkbox and call our setState
checkbox.addEventListener( 'change', setState );
// Lrts also call setState once to initialise the correct placeholder
// for our input element to get started. This will remove any placeholders
// if the checkboxes are unchecked.
setState();
}
<fieldset class="checkbox-message">
<label for="bangkirai">Bangkirai</label>
<input type="checkbox" id="bangkirai" />
<input type="number" placeholder="Tell us, how many 'bangkirai'?" />
<span>stuks</span>
</fieldset>
<fieldset class="checkbox-message">
<label for="beukenhout">Beukenhout</label>
<input type="checkbox" id="beukenhout" />
<input type="number" placeholder="How many 'beukenhout'?" />
<span>stuks</span>
</fieldset>
Good luck coding!
#somethinghere's answer is concise but if we modify your answer as it is you could check this
function enableTextBox() {
bangkirai_validation = document.getElementById("bangkirai_validation");
if (document.getElementById("chk_bangkirai").checked === true) {
document.getElementById("bangkirai").disabled = false;
}
else {
document.getElementById("bangkirai").disabled = true;
bangkirai_validation.style.display='none';
return;
}
if (document.getElementById("bangkirai").value =="") {
bangkirai_validation.style.display='block';
}else
{
bangkirai_validation.style.display='none';
}
}
function enableTextBox2() {
beukenhout_validation = document.getElementById("beukenhout_validation");
if (document.getElementById("chk_beukenhout").checked === true) {
document.getElementById("beukenhout").disabled = false;
}
else {
document.getElementById("beukenhout").disabled = true;
beukenhout_validation.style.display='none';
return;
}
if (document.getElementById("beukenhout").value == "") {
beukenhout_validation.style.display='block';
}else
{
beukenhout_validation.style.display='none';
}
}
<fieldset>
<legend>Bestel gegevens</legend>
<div class="container">
<div class="row">
<div class="span7 id=" houtsoorten"">
<div class="control-group">
<label class="control-label">
bangkirai
<input id="chk_bangkirai" type="checkbox"
onchange="enableTextBox()" >
</label>
<div class="controls">
<div class="input-append">
<input class="inpbox input-mini"
type="number" id="bangkirai" name="bangkirai" placeholder="aantal" disabled
onkeyup="enableTextBox()" onchange="enableTextBox()">
<span class="add-on">stuks</span>
<div style="display:none;" id="bangkirai_validation">Please enter a value</div>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">
beukenhout
<input id="chk_beukenhout" type="checkbox" onchange="enableTextBox2()" >
</label>
<div class="controls">
<div class="input-append">
<input class="inpbox input-mini"
type="number" id="beukenhout" name="beukenhout" placeholder="aantal"
disabled onkeyup="enableTextBox2()" onchange="enableTextBox2()" >
<span class="add-on">stuks</span>
<div style="display:none;" id="beukenhout_validation">Please enter a value</div>
</div>
</div>
</div>
Related
I've created a check function where the code checks if a user has changed a value. If it has then a modal should be displayed if a value hasn't changed go back to the previous screen. The problem is that on some screens values are already existing so using the id to check this doesn't work.
Here are examples of the inputs:
<div class="govuk-input__wrapper"> <input
aria-label="Enter the total percetage for January. Enter 0 if this does not apply"
class="input-suffix govuk-input govuk-input--width-5" id="input-4"
onblur="sumPercentage()" name="installmentPercentage" type="text value=" value="5"
aria-describedby="percent">
<div class="govuk-input__suffix" aria-hidden="true">%</div>
</div>
<div class="govuk-form-group right-align">
<div class="govuk-input__wrapper">
<div class="govuk-input__prefix right-align" aria-hidden="true">£</div>
<input aria-label="Enter the total amount for February. Enter 0 if this does not apply"
class="govuk-input input-prefix govuk-input--width-7" id="input-3"
onblur="sumTotal()" name="installmentValue" type="text" aria-describedby="currency"
autocomplete="off" value="320,000">
</div>
</div>
Every time this gets fired the input value for 'input4ValueChanged' and 'input3ValueChanged' is changed
document.getElementById("input-4").addEventListener("change", input4ValueChanged),
document.getElementById("input-3").addEventListener("change", input3ValueChanged),
Setting the input4WasChanged and input3WasChanged to false as we want to set it to true when the modal appears
function check() {
let input4WasChanged = false
let input3WasChanged = false
Starts the counter
let counter = 0
If the input change is true then it opens the 'notSaved' modal
if (input4WasChanged === true) {
document.getElementById('notSaved').style.display = 'block'
counter++
}
if (input3WasChanged === true) {
document.getElementById('notSaved').style.display = 'block'
counter++
}
if (counter === 0) {
history.back()
}
}
If a value has been changed then display the modal
function input4ValueChanged(){
if(document.getElementById("input-4").value != "")
{
input4WasChanged = true;
}
}
function input3ValueChanged(){
if(document.getElementById("input-4").value != "")
{
input3WasChanged = true;
}
}
I'm not entirely sure of what you're asking here, but it seems that you've made a mistake in your Js or in your Html file.
Since your ids differs:
your js: Boolean(document.getElementById(**"input-4"**).value),
your html: <input ... id="input-4 value=" ...>
I hope I could help a bit.
I would like my program to automatically select all checkboxes (Specifically "Side 1, Side 2, Side 3 and Side 4") if the wall_amount input is above 3. How would this be done?
I have tried this on javascript lines 10-12. Thanks
HTML
<label for="wall_amount">Number of Walls</label>
<input type="number" value="1" min="1" max="4" step="1" id="wall_amount" name="wall_amount"></input>
<div>
Please choose where you want the walls placed
<label for="wall_side1">Side 1</label>
<input type="checkbox" id="wall_side1" name="wall_side1"></input>
<div style="display: inlineblock;">
<label for="wall_side2">Side 2</label>
<input type="checkbox" id="wall_side2" name="wall_side2"></input>
<img class="img2" src="images/reference.png" alt="Bouncy Castle">
<label for="wall_side3">Side 3</label>
<input type="checkbox" id="wall_side3" name="wall_side3"></input>
</div>
<label for="wall_side4">Side 4</label>
<input type="checkbox" id="wall_side4" name="wall_side4"></input>
</div>
Javascript
var base_length = Number(document.getElementById("base_length").value);
var base_width = Number(document.getElementById("base_width").value);
var walltype = Number(document.getElementById("walltype").value);
var checkbox_side1 = document.getElementById("wall_side1");
var checkbox_side2 = document.getElementById("wall_side2");
var checkbox_side3 = document.getElementById("wall_side3");
var checkbox_side4 = document.getElementById("wall_side4");
var wall_amount = Number(document.getElementById("wall_amount").value);
$("input:checkbox").click(function() {
let max = $("#wall_amount").val();
var bol = $("input:checkbox:checked").length >= max;
$("input:checkbox").not(":checked").attr("disabled", bol);
});
$("wall_amount").on('keyup', function () {
$('checkbox_side1').prop('checked', +$(this).val() > 3);
});
You can use the function setAttribute to check checkboxes. For example, this code (based on your example) will check your element with the id wall_side1.
checkbox_side1.setAttribute("checked", true)
Anyway, try adding this to your code as a function. Then add a conditional statement that runs the function every time your variable exceeds a certain amount.
I am still relatively new at answering questions so I hope this helps!
const checkboxes = [
"wall_side1",
"wall_side2",
"wall_side3",
"wall_side4"
].map((id) => document.getElementById(id));
const amountInput = document.getElementById("wall_amount");
amountInput.addEventListener("change", (event) => {
const value = parseInt(event.target.value || 0);
if (value === 4) {
checkboxes.forEach(
checkbox => {
checkbox.disabled = true;
checkbox.checked = true;
}
);
} else {
checkboxes.forEach(
checkbox => {
checkbox.disabled = false;
}
);
}
});
I'm using vanilla js, and I'm stumped because there's very little code here, so I'm not sure where the problem lies. It may be a misunderstanding on my part on how the attribute works.
function changeState() {
const self = event.target
const parent = event.path[1]
if (self.type == "radio") {
console.log(self.id + " is " + self.checked)
}
}
<div id="usernames_buttons">
<input type="radio" name="usernames" id="usernames-bl" onclick="changeState()" checked>
<label for="usernames-bl">BL</label>
</input>
<input type="radio" name="usernames" id="usernames-wl" onclick="changeState()">
<label for="usernames-wl">WL</label>
</input>
<button data-toggle onclick="changeState()">OFF</button>
</div>
I paired everything down to just this code and ran it in a code pen to test, and the console.log will return true regardless of which option I am clicking. The expectation is that usernames-bl would return true and -wl would return false, but they return true whether the checked attribute is there or not.
You are invoking the changeState() on every click and i guess, as its a radio button, which will always give checked 'true' on click
I think you are doing it right minus the "Off" button should un-check both.. so I added this block:
if (self.type != "radio") {
document.getElementById("usernames-wl").checked = false;
document.getElementById("usernames-bl").checked = false;
}
function changeState() {
const self = event.target
const parent = event.path[1]
if (self.type != "radio") {
document.getElementById("usernames-wl").checked = false;
document.getElementById("usernames-bl").checked = false;
}
console.log("usernames-wl is " + document.getElementById("usernames-wl").checked)
console.log("usernames-bl is " + document.getElementById("usernames-bl").checked)
}
<div id="usernames_buttons">
<input type="radio" name="usernames" id="usernames-bl" onclick="changeState()" checked/>
<label for="usernames-bl">BL</label>
<input type="radio" name="usernames" id="usernames-wl" onclick="changeState()"/>
<label for="usernames-wl">WL</label>
<button data-toggle onclick="changeState()">OFF</button>
</div>
I've tried almost all the methods mentioned here and in other websites but still I'm stuck so that's why I'm asking it here.
I've created a form (with out <form></form> tags) in this form I'm creating 4 radios buttons using a while loop data is being pulled from a database.
To send data I'm using a JavaScript(Ajax) which is bound to a button click event.
Now I want to keep the submit button disabled until all the filed's are filled the last filed's are the radio buttons I'm tried to use many other ways to do this but nothing happened so any way below is code I'm using.
function checkUrole() {
var roles = document.getElementById("userRoles"),
btn = document.getElementById("submit"),
len = roles.length,
sel = null;
for(var i=0; i < len; i++){
if (roles.checked){
sel = roles[i].value;
}
}
if (sel === null){
document.getElementById("msgID").innerHTML = "9";
btn.disabled = true;
}else{
btn.disabled = false;
}
}
And this is my HTML
<label for="userRoles">User Role:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" id="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>" onmousedown="checkUrole()"><?php echo $row["userRole"]; }?>
<label id="msgID" hidden></label>
<div id="msg"></div>
Basically the HTML will create something like this,
<input type="radio" id="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
<input type="radio" id="userRoles" name="userRoles" value="2" onmousedown="checkUrole()">Manager
<input type="radio" id="userRoles" name="userRoles" value="3" onmousedown="checkUrole()">Team Leader
<input type="radio" id="userRoles" name="userRoles" value="4" onmousedown="checkUrole()">User
I don't like write a code like this,
if(document.getElementById("userRoles1").checked{
something here;
}else if(document.getElementById("userRoles2").checked{
something here;
}else{
something here;
}
above I think makes the program a bit less dynamic 'cos if a new user role is added I've add a new IF to the loop.
So is there any way I solve this and I like to use JavaScript if can.
UPDATE: Thanks to #zer00ne I solved this problem and below is the finale working code hope this helps any one in the future as well.
My HTML:
<script language="JavaScript" type="text/javascript" src="../jScripts/userCreatFunctions.js">
<div id="userRoles">
<input type="radio" name="userRoles" value="1" checked>Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
My JaveScript:
$(document).ready(function () {
/*Register the change element to #roles
|| When clicked...*/
//This code base was originally developed by zer00ne I'm using it under his permission
//Thanks man.
var form = document.getElementById('userRoles');
if (form){
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Reference the submit button
var btn = document.querySelector('[name=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
}
function roleDist(rank) {
var display = document.getElementById("msg");
if (rank !== null) {
display.innerHTML = "All done! You can save";
} else {
display.innerHTML = "Please Select User Type";
}
}
});
Use the $(document).ready(function () {}) other wise the script get loaded before the DOM which leads to a NULL value making the script none functional.
Firstly, you don't need the id's on every input element. You can get an array of the button element by name using getElementsByName, here is an example of how you would do "something" based on one of those being checked:
JS (Using ES6)
const getRadioValue = (name) => {
const radios = document.getElementsByName(name);
let val;
Object.keys(radios).forEach((obj, i) => {
if (radios[i].checked) {
val = radios[i].value;
}
});
return val;
}
document.getElementById('form').addEventListener('change', (e) => {
getRadioValue('userRoles'); // value of checked radio button.
});
HTML
<div id="form">
<input type="radio" name="userRoles" value="1">Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
JsFiddle Example
UPDATE - improved
A more efficient method would be using the Array.prototype.find() method, this is better because:
The find method executes the callback function once for each index of the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element.
In other words, it doesn't need to iterate the entire Array, once we find what we want it returns.
Note: Use the below snippets within the change event mentioned above to retrieve the checked value.
JS (Using ES6)
const getCheckedRadioValue = (name) => {
const radios = document.getElementsByName(name);
try {
// calling .value without a "checked" property will throw an exception.
return Array.from(radios).find((r, i) => radios[i].checked).value
} catch(e) { }
}
getCheckedRadioValue('userRoles');
JsFiddle Example
JS (Without ES6)
function getCheckedRadioValue(name) {
var radios = document.getElementsByName(name);
var val;
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
return val; // return value of checked radio or undefined if none checked
}
getCheckedRadioValue('userRoles');
JsFiddle Example
References
Array.prototype.forEach()
Array.from()
Array.prototype.find()
Not exactly sure what you are trying to do, so here is what I'm guessing:
Need to determine the value of a checked radio input
Need to enable a submit button that's determined by a checked radio
Need to effectively call upon other functions, run additional interactions, etc. depending on what was specifically checked.
Details are commented in Snippet
SNIPPET
// Reference #roles
var form = document.getElementById('roles');
/* Register the change element to #roles
|| When clicked...
*/
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Find the textNode next to target
var label = target.nextSibling;
// Reference the #display
var display = document.getElementById('display');
// Display the <label>s text and radio value
display.value = label.textContent + ' - Rank: ' + target.value;
// Reference the submit button
var btn = document.querySelector('[type=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
function roleDist(rank) {
switch (rank) {
case '4':
alert('Rank 4 - Limited Access');
// Take user to landing page
break;
case '3':
alert('Rank 3 - Basic Access');
// Take user to dashboard
break;
case '2':
alert('Rank 2 - Advanced Access');
// Take user to database
break;
case '1':
alert('Rank 1 - Full Access');
// Take user to admin panel
break;
}
}
input,
output,
[type=submit] {
font: inherit;
cursor: pointer;
}
[type=submit] {
float: right;
}
<form id='roles'>
<input type="radio" name="role" value="1">Admin
<input type="radio" name="role" value="2">Manager
<input type="radio" name="role" value="3">Team Leader
<input type="radio" name="role" value="4">User
</form>
<br/>
<label for='display'>Role: </label>
<!--
Since #display and submit button are outside of
the <form>, using the form attribute and the
<form>'s #id as the value establishes an
association between them and <form>
-->
<output id='display' form='roles'></output>
<br/>
<input type='submit' form='roles' disabled>
There is very basic mistake in your markup you should not use elements with same id's in
You can use class instead of id (give class to radioboxes)
document.getElementsByClassName("userRoles")
<input type="radio" class="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
Rest of your code seems ok
I'm new to JavaScript and my form validation works but keeps jumping to validate username on submit even when its validated. Heres my code
function validate_form(form)
{
var complete=false;
if(complete)
{
clear_all();
complete = checkUsernameForLength(form.username.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkEmail(form.email.value);
}
if (complete)
{
clear_all();
complete = checkphone(form.phone.value);
}
}
function clear_all()
{
document.getElementById('usernamehint').style.visibility= 'hidden';
/*.basicform.usernamehint.style.backgroundColor='white';*/
document.getElementById("countrthint").style.visibility= 'hidden';
/*document.basicform.countrthint.style.backgroundColor='white';*/
document.getElementById("subhint").style.visibility= 'hidden';
/*document.basicform.subject.style.backgroundColor='white';*/
document.getElementById("phonehint").style.visibility= 'hidden';
/*document.basicform.phone.style.backgroundColor='white';*/
document.getElementById("emailhint").style.visibility= 'hidden';
/*document.basicform.email.style.backgroundColor='white';*/
}
heres the functions
function checkUsernameForLength(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 2) {
fieldset.className = "welldone";
return true;
}
else
{
fieldset.className = "";
return false;
}
}
function checkEmail(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt))
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkphone(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if ( /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/.test(txt)) {
fieldset.className = "welldone";
}
else
{
fieldset.className = "FAILS";
}
}
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
} else {
window.onload = function()
{
oldonload();
func();
}
}
}
function prepareInputsForHints()
{
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++)
{
inputs[i].onfocus = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
inputs[i].onblur = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
addLoadEvent(prepareInputsForHints);
and heres my form
<form form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" >
<fieldset>
<label for="username">Name:</label>
<input type="text" id="username" onkeyup="checkUsernameForLength(this);" />
<span class="hint" id="usernamehint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="country">Country:</label>
<input type="text" id="country" onkeyup="checkaddress(this);" />
<span class="hint" id="countryhint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="Subject">Subject:</label>
<input type="text" id="subject" onkeyup="checkaddress(this);" />
<span class="hint" id="subhint">Please Indicate What Your Interest Is !</span>
</fieldset>
<fieldset>
<label for="Phone">Phone:</label>
<input type="text" id="Phone" onkeyup="checkphone(this);" />
<span class="hint" id="phonehint">This Feld Must Be Numeric Values Only !</span>
</fieldset>
<fieldset>
<label for="email">Email Address:</label>
<input type="text" id="email" onkeyup="checkEmail(this);" />
<span class="hint" id="emailhint">You can enter your real address without worry - we don't spam!</span>
</fieldset>
<input value="send" type="button" onclick="validate_form(this.form)"/>
<br /><br /> <br /><br />
</form>
Please point amateur coder in right direction Thanks
Like others said, you are trying to access the username inside a condition, where the condition is always false. You set complete=false on start and right after that you try to see if that is true.
By the way, clear_all() may not have the behavior you want before the first validation. It will hide every input in the screen, so if there is anything else wrong, you won't be able to see that. I should go for hiding at the end (or at the beginning like #mplungjan stated, and always depending on what you need), maybe reusing your if(complete) structure:
function validate_form(form)
{
clear_all();
var complete = checkUsernameForLength(form.username.value);
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
}
Also, and after stating the username validation works, you should return a boolean value in the other methods =)
EDIT: Also, checking the errors the others said is a high priority issue.
EDIT2: I turned to see a repeated condition. Now I deleted it. To keep using the if(complete) that way, you should also do these changes:
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
return true; // <-- this change
}
else
{
fieldset.className = "";
return false; // <-- and this change
}
}
Also, change the other methods to return true and false when you need.
Don't panic.
Everyone has to start somewhere and it can be very frustrating when you're only just learning the ropes.
In answering this question, we need to look not only at your JavaScript, but at the HTML as well.
You don't have a submit input type; instead opting for a regular button. That wouldn't necessarily be a problem, except nowhere in your JavaScript are you actually submitting your form. That means every time someone clicks the "Send" button, it will fire the validate_form() function you've defined but do nothing further with it. Let's make a couple of changes:
Replace your button with a submit input:
<input value="send" type="submit" />
Next, add the following code to your form tag so that we define an action to take when the user tries to submit your form:
onsubmit="validate_form(this)"
So your whole form tag now looks like this:
<form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" onsubmit="return validate_form(this)">
Notice I removed an extra "form" from that element.
Ok, next we want to handle what happens when the form is ready to be validated.
function validate_form(form)
{
// ...we can step through each item by name and validate its value.
var username = checkUsernameForLength(form["username"].value);
var email = checkaddress(form["country"].value);
// ...and so on.
return (username && email && {my other return values});
}
Each method you call (e.g. CheckUsernameForLength) should return either true or false, depending on whether the input is valid or not.
Our last return is probably a little inelegant, but is a verbose example of a way to aggregate our returned values and see if there are any "failed" values in there. If all your methods returned true, that last return will evaluate to true. Otherwise (obviously) it will return false.
The submission of the form will depend on whatever value is returned from your validate_form() function.
Please start with this ( http://jsfiddle.net/4aynr/4/ )
function validate_form(form)
{
var complete=false;
clear_all();
complete = checkUsernameForLength(form.username); // pass the FIELD here
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
if (!complete) alert('something went wrong')
return complete;
}
and change
<form form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform" >
to
<form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform"
onSubmit="return validate_form(this)">
and change
<input value="send" type="button" onclick="validate_form(this.form)"/>
to
<input value="send" type="submit" />