Input Text Box keeps getting erased, along with input effects - javascript

I'm trying to create a simple text input box. When the submit button is pressed, the input in the text box is sent to a search script that compares the input to an array of possible values.
However, once I press the submit button, the correct result of the function flashes quickly on the screen, after which the default value of the text box returns, and the function result disappears quickly again. This all happens in a matter of like 100 ms.
Could anyone explain how I can prevent this reset from happening? I've been looking online everywhere, and can only find people who are asking how to reset it, so I'm a bit confused as to what I'm doing wrong.
Result after pressing submit
Result right after displaying the result
Body:
<body>
<div id="blogmenu"></div>
<div ID="RECEPT">
<h1>Search Bar</h1>
<br>
<h2> Time for Searchin' </h2>
<form name="inputForm">
<div><input type="text" min="1" max="50" value="" class="slider" id="a" name="a"></div>
<div><input type="submit" onclick="SearchItem(document.getElementById('a').value);"></div>
</form>
<div ID="ijsjes" style="display:none"> IJsjes </div>
<div ID="spaghetti" style="display:none"> Spaghetti </div>
<div ID="gniocchi" style="display:none"> Gniocchi </div>
<div ID="bananen" style="display:none"> Bananen </div>
</div>
</body>
Function:
<script>
function SearchItem(Term) {
console.log('I did get here');
document.getElementById('a').value = Term;
var ijsjes = {
kleur : "wit",
smaak : "zoet",
type : "dessert"
};
var spaghetti = {
kleur : "geel",
smaak : "hartig",
type : "pasta"
};
var gniocchi = {
kleur : "geel",
smaak : "hartig",
type : "pasta"
};
var bananen = {
kleur : "geel",
smaak : "zoet",
type : "fruit"
};
console.log(spaghetti.kleur + " also " + (spaghetti.kleur == Term));
if (ijsjes.kleur == Term) {
document.getElementById('ijsjes').style.display = 'block';
console.log('ijsjes matched');
} else {
document.getElementById('ijsjes').style.display = 'none';
console.log('ijsjes not matched');
}
if (spaghetti.kleur == Term) {
document.getElementById('spaghetti').style.display = 'block';
console.log('spaghetti matched');
} else {
document.getElementById('spaghetti').style.display = 'none';
console.log('spaghetti not matched');
}
if (gniocchi.kleur = Term) {
document.getElementById('gniocchi').style.display = 'block';
console.log('gniocchi matched');
} else {
document.getElementById('gniocchi').style.display = 'none';
console.log('gniocchi not matched');
}
if (bananen.kleur = Term) {
document.getElementById('bananen').style.display = 'block';
console.log('bananen matched');
} else {
document.getElementById('bananen').style.display = 'none';
console.log('bananen not matched');
}
}
</script>

Your input is of type submit which by default will result in the onsubmit function of your form being fired, which by default does a postback on your page
you can either drop the form and change your button to type="button" or move the function to the onsubmit property of the form (as in my snippet) and use event.preventDefault() to stop the post back
function SearchItem(event) {
event.preventDefault();
var Term = document.getElementById('a').value;
console.log('I did get here');
document.getElementById('a').value = Term;
var ijsjes = {
kleur: "wit",
smaak: "zoet",
type: "dessert"
};
var spaghetti = {
kleur: "geel",
smaak: "hartig",
type: "pasta"
};
var gniocchi = {
kleur: "geel",
smaak: "hartig",
type: "pasta"
};
var bananen = {
kleur: "geel",
smaak: "zoet",
type: "fruit"
};
console.log(spaghetti.kleur + " also " + (spaghetti.kleur == Term));
if (ijsjes.kleur == Term) {
document.getElementById('ijsjes').style.display = 'block';
console.log('ijsjes matched');
} else {
document.getElementById('ijsjes').style.display = 'none';
console.log('ijsjes not matched');
}
if (spaghetti.kleur == Term) {
document.getElementById('spaghetti').style.display = 'block';
console.log('spaghetti matched');
} else {
document.getElementById('spaghetti').style.display = 'none';
console.log('spaghetti not matched');
}
if (gniocchi.kleur = Term) {
document.getElementById('gniocchi').style.display = 'block';
console.log('gniocchi matched');
} else {
document.getElementById('gniocchi').style.display = 'none';
console.log('gniocchi not matched');
}
if (bananen.kleur = Term) {
document.getElementById('bananen').style.display = 'block';
console.log('bananen matched');
} else {
document.getElementById('bananen').style.display = 'none';
console.log('bananen not matched');
}
}
<body>
<div id="blogmenu"></div>
<div ID="RECEPT">
<h1>Search Bar</h1>
<br>
<h2> Time for Searchin' </h2>
<form name="inputForm" onsubmit="SearchItem(event)">
<div><input type="text" min="1" max="50" value="" class="slider" id="a" name="a"></div>
<div><input type="submit"></div>
</form>
<div ID="ijsjes" style="display:none"> IJsjes </div>
<div ID="spaghetti" style="display:none"> Spaghetti </div>
<div ID="gniocchi" style="display:none"> Gniocchi </div>
<div ID="bananen" style="display:none"> Bananen </div>
</div>
</body>

Your last 2 conditions (last 2 if-else block) are assigning value rather than comparing.Because of this your value is printed for a while before getting over-ridden.
Also, as soon as you find the element/search value, you should break/stop because other if/else statements would then overwrite previous results.One way to achieve this would be to have nested if-else, so that the code execution continues only when the conditions/values are not being met.
The input type="button" does a postback, so you are using onclick function to call javascript so you do not need to submit the data anywhere. Just make input type="button" instead of "submit"

Related

How to show a response when filtering through a list of elements using javascript

Hello I am creating an FAQ page that has to be filtered using javascript as below
Credit : https://makitweb.com/jquery-search-text-in-the-element-with-contains-selector/
$(document).ready(function () {
$('#filter').keyup(function () {
// Search text
var text = $(this).val().toLowerCase();
var error = document.getElementById("error");
// Hide all content class element
$('.mobrog-ux-text').hide();
// Search
$('.mobrog-ux-text').each(function () {
if ($(this).text().toLowerCase().indexOf("" + text + "") != -1) {
$(this).closest('.mobrog-ux-text').show();
setTimeout(
function () {
var x = document.getElementById("myDIV");
x.style.display = "none";
}, 4000);
error.style.display = "none";
}
else if($(this).text().toLowerCase().indexOf("" + text + "") == 0) {
error.style.display = "block";
}
});
});
});
<form align="center">
<input id="filter" onkeydown="keydownFunction()" oninput="keyPress(this.value)" class="searchfield" type="text"
name="search" placeholder="Search the help center">
</form>
<div style="color: white;padding : 10px" align="center"></div>
</div>
<div class="content2">
<h2>Frequently asked questions</h2>
<div id"pag"="id" pag""="pag" ""></div>
<div align="center" class="col-10">
<div class="mobrog-tab-container maxwidth">
<div id="myDIV" class="loader"></div>
<div class="error" id="error"> No result found!!</div>
<div id="results" class="mobrog-ux-vertical-tabs">
<div id="tar" class="mobrog-tabs">
<button data-tab="tab1" class="active">sample tab button?<span></span></button>
<button class="empty"></button>
</div>
<div class="mobrog-maincontent">
<div data-tab="tab1" class="mobrog-tabcontent active">
<div class="mobrog-ux-text">
<button class="mobrog-accordion">sample button</button>
<div class="mobrog-panel">
<p>
sample text
</p>
</div>
</div>
Which works, but then I am trying to show a message when the filtered word is not found within the list of DIVS I'm searching through on my FAQ page
I tried the below with
else if ($(this).text().toLowerCase().indexOf("" + text + "") == 0) {
//error message display
}
But then it does not work
(e.g when I type in a word which does not exist within my FAQ I want to display an error message which is in a div) and vice versa when the word is found in my FAQ page)
like the way its been used in the method of RegExp
Live search on an Div with input filter
at the moment when I type in available and unavailable words the error message appears
Please how do I effectively display a message when a filtered word is found or not found
Thanks
Expanding on my comment, this is an example of how you could implement something like this.
To reiterate - the main problem was that the error was being shown if any result didn't match instead of showing if none match
To fix that, we can add a variable outside the loop to determine if any result was matched
$(document)
.ready(function () {
$('#filter')
.keyup(function () {
// Search text
var text = $(this).val().toLowerCase();
var error = document.getElementById("error");
// storing this in a variable will reduce how many times you call the function
var $ux_texts = $('.mobrog-ux-text');
// Hide all content class element
$ux_texts.hide();
// variable to update if any match is found
var has_match = false;
// Search
$ux_texts
.each(function () {
var $this = $(this);
if ($this.text().toLowerCase().indexOf("" + text + "") === -1) {
// flip the logic so we can return early - makes for cleaner code
return;
}
$this.closest('.mobrog-ux-text').show();
setTimeout(function () {
var x = document.getElementById("myDIV");
x.style.display = "none";
}, 4000);
has_match = true;
});
// error handling
if (has_match) {
error.style.display = "none";
} else {
error.style.display = "block";
}
});
});

Disable button not working inside if-else, but working without if-else

I'm trying to create a button that should check if user input is not empty before submitting. When user input is set, the button would be disabled, change in innerHTML and have a spinner at the bottom.
Below are what I have got so far.
let form = document.getElementById("form");
let button = document.getElementById("btnSub");
let text = document.getElementById("inpSub");
let spin = document.getElementById("soonSpin");
button.addEventListener("click", submit_fn, false);
function submit_fn() {
if (text.innerHTML.length == 0) {
alert("Please fill out the question");
// return;
}
form.submit();
text.disabled = true;
button.disabled = true;
button.innerHTML = " Please wait! Loading...";
spin.className = "spinner-border";
spin.setAttribute("role", "status");
let span = document.createElement("span");
span.className = "sr-only";
span.innerHTML = "Loading...";
spin.appendChild(span);
}
<form id="form" method="post" action="{{url_for('prediction')}}" enctype="multipart/form-data">
<input class="border border-danger" id="inpSub" type="text" name="question" placeholder="Enter question here" required />
<button class="btn-danger" type="submit" id="btnSub">Find closest answer</button>
</form>
<div id="soonSpin"></div>
My code always shows the alert in both cases when I have the input or having nothing. And, it doesn't run any of the code outside if statement, but do render to the next page.
Does anyone know what's the problem here?
Thanks in advance!
You need to listen for the change on the text input as well to disable / enable the button :
text.addEventListener("input", e => {
if (text.value.length > 0) {
button.disabled = false
} else {
button.disabled = true
}
});
Check the comments to see the differences in the code : ( mainly check text.value instead of text.innerHTML )
let form = document.getElementById("form");
let button = document.getElementById("btnSub");
let text = document.getElementById("inpSub");
let spin = document.getElementById("soonSpin");
button.addEventListener("click", submit_fn, false);
text.addEventListener("input", e => {
if (text.value.length > 0) {
button.disabled = false
} else {
button.disabled = true
}
});
function submit_fn(e) {
if (text.value == 0) {
alert("Please fill out the question");
// return;
}
e.preventDefault(); // comment this to submit the form
// uncomment this line to submit the form
// form.submit();
text.disabled = true;
button.innerHTML = " Please wait! Loading...";
spin.className = "spinner-border";
spin.setAttribute("role", "status");
let span = document.createElement("span");
span.className = "sr-only";
span.innerHTML = "Loading...";
spin.appendChild(span);
}
<form id="form" method="post" action="{{url_for('prediction')}}" enctype="multipart/form-data">
<input class="border border-danger" id="inpSub" type="text" name="question" placeholder="Enter question here" required />
<button class="btn-danger" type="submit" disabled id="btnSub">Find closest answer</button>
</form>
<div id="soonSpin"></div>

How to connect JS functions to checkbox

Hello,
I am making a simple text changer website where I want the user to be able to select what options to use. Right now I have two options; myConvertOption which capitalizes every odd letter in a word and I have myScrambleOption which randomly mixes up each word a bit.
Right now whenever you click on Caps (checkbox_1) it already executes the function where I only want it to execute whenever the user clicks on the "Convert" button + it also puts spaces in between each letter now.
The Scramble button (checkbox_2) doesn't do anything for some reason, except for console logging the change.
JSfiddle: https://jsfiddle.net/MysteriousDuck/hLjytr2p/1/
Any help and suggestions will be greatly appreciated!
P.S I am new to Javascript.
Checkbox event listeners:
checkbox_1.addEventListener('change', function () {
console.log("checkbox_1 changed");
if (this.checked) {
myConvertFunction();
} else {
//Do nothing
}
})
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
myScrambleFunction(text);
} else {
//Do nothing
}
})
Checkbox HTML:
<div class="checkbox">
<input type="checkbox" id="checkbox_1" >
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2" >
<label for="checkbox_2">Scramble</label>
</div>
this works properly..
You just had to add the event on the button and then test which check box was checked, and other little things
<!doctype html>
<html>
<head>
</head>
<body>
<div class="container">
<h1> Text Changer </h1>
<h2> CAPS + randomize letters text changer</h2>
<div class="checkbox">
<input type="checkbox" id="checkbox_1">
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2">
<label for="checkbox_2">Scramble</label>
</div>
<textarea type="text" autofocus="true" placeholder="input text" id="inputText" value="Input Value" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="convertText">Convert</button>
<textarea type="text" placeholder="converted text" id="convertedText" value="Clear" readonly="true" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="copyText">Copy</button>
</div>
<script>
var text = document.getElementById("inputText").value;
var convertText = document.getElementById("convertText");
var checkbox_2 = document.getElementById("checkbox_2");
var checkbox_1 = document.getElementById("checkbox_1");
//Capitalize every odd letter
function myConvertFunction() {
var x = document.getElementById("inputText").value;
var string = "";
for (let i = 0; i < x.length; i++) {
if (i % 2 == 0) {
string = string + x[i].toUpperCase();
} else {
string = string + x[i];;
}
}
return string;
}
//Scramble words
function myScrambleFunction(text) {
let words = text.split(" ");
words = words.map(word => {
if (word.length >= 3) {
return word.split('').sort(() => 0.7 - Math.random()).join('');
}
return word;
});
return words.join(' ');
}
document.getElementById("copyText").addEventListener("click", myCopyFunction);
//Copy textarea output
function myCopyFunction() {
var copyText = document.getElementById("convertedText");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
eraseText();
}
//Delete textarea output
function eraseText() {
document.getElementById("convertedText").value = "";
document.getElementById("inputText").value = "";
document.getElementById("inputText").focus();
}
//don't add the event to the radio buttons (previously checkboxes), add it to the convert button, and in its function test which radio button has been checked
convertText.addEventListener('click', function() {
if (checkbox_1.checked && checkbox_2.checked) {
console.log("doing both options");
document.getElementById("convertedText").value = myScrambleFunction(myConvertFunction());
} else if (checkbox_2.checked) {
console.log("proceeding scrumble");
document.getElementById("convertedText").value = myScrambleFunction(text);
} else if (checkbox_1.checked) {
console.log("proceeding cap");
document.getElementById("convertedText").value = myConvertFunction();
}
})
</script>
</body>
</html>
You're never updating var text.
You need to update it before using it if you want the value to be something other than an empty string.
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
text = document.getElementById("inputText").value;
myScrambleFunction(text);
} else {
//Do nothing
}

JavaScript alert onclick onchange if statement

I am trying to display an onclick alert if the box is filled in with the world "hello", while a different alert should pop up in "hello" is not typed.
Not sure what I am doing wrong here:
The HTML:
<form>
<input id="box" placeholder="type hello" onchange="sayHello()" style="display: block;" />
<input type="button" onclick="sayHelloTwo()" value="Click me" />
<p id="hidden" style="display: none;">
HELLO
</p>
</form>
The JavaScript:
function sayHello() {
var answer = "hello";
if (answer) {
alert("Click for Hello!");
} else {
alert("you need to type hello!");
return false;
}
}
function sayHelloTwo() {
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").style.color = "#909090";
document.getElementById("hidden").style.fontSize = "40px";
}
You need to check the actual value that the user entered in the box, and then compare it to the value you want (the value inside your answer variable).
There are several ways to do so, one of the is using
document.getElementById('box').value
(Where box is the id of your element).
Here is a working example:
function sayHello() {
var answer = "hello";
var text = document.getElementById('box').value;
if (text == answer) {
alert("Click for Hello!");
} else {
alert("you need to type hello!");
return false;
}
}
function sayHelloTwo() {
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").style.color = "#909090";
document.getElementById("hidden").style.fontSize = "40px";
}
<form>
<input id="box" placeholder="type hello" onchange="sayHello()" style="display: block;" />
<input type="button" onclick="sayHelloTwo()" value="Click me" />
<p id="hidden" style="display: none;">
HELLO
</p>
</form>
To elaborate on Dekels answer some more, the click event also has an event property attached to it that you can use to get the value, like this.
function sayHello(e) {
if (e.currentTarget.value == "hello") {
alert("Click for Hello!");
} else {
alert("you need to type hello!");
return false;
}
}
You have error in checking condition for answer
function sayHello() {
var answer = "hello";
if (answer == "hello") {
alert("Click for Hello!");
} else {
alert("you need to type hello!");
return false;
}
}
You can pass the element value directly as a parameter this.value in your html.
Notice that to make the code case insensitive you must convert the value to lowercase and than check the if statement value.toLowerCase() !== 'hello'
Code:
function sayHello(value) {
if (value.toLowerCase() !== 'hello') {
alert('You need to type hello!');
return false;
}
alert('Click for Hello!');
}
function sayHelloTwo() {
var hidden = document.getElementById('hidden')
hidden.style.display = 'block';
hidden.style.color = '#909090';
hidden.style.fontSize = '40px';
}
<form>
<input id="box" placeholder="type hello" onchange="sayHello(this.value)" style="display: block;" />
<input type="button" onclick="sayHelloTwo()" value="Click me" />
<p id="hidden" style="display: none;">
HELLO
</p>
</form>

Validation stuck at first validation

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" />

Categories