HTML:
<input type="text" name="name" id="name_1" value="" class="showimage" />
<div class="icon_1" id="icon" style="display:none;"></div>
<input type="text" name="name" id="name_2" value="" class="showimage" />
<div class="icon_2" id="icon" style="display:none;"></div>
JQuery:
<script type="text/javascript">
$(document).ready(function() {
// Add onclick handler to checkbox w/id checkme
$('.showimage').click(function() {
var id = $(this).attr('id');
var ret = id.split("_");
var str1 = ret[1];
//alert(str1);
var id = $(this).attr('id');
var ret = id.split("_");
var str2 = ret[1];
//alert(str2);
//$(".icon_"+id).show();
// $("#icon").show();
if (str1 == str2) {
alert(str1);
$(".icon_" + str1).show();
//exit;
//alert("hi")
} else {
alert("sec");
$(".icon_" + str1).hide();
}
});
});
</script>
why not hide the else part
Your question: why not hide the else part?
That is because of $(this) it refers to the current element which have got the selector's context the event has raised on. So,
var id = $(this).attr('id');
The above variable has been used two times and both refers to the same object. So in the if condition:
if (str1 == str2) {
both values are always same and thus else never gets executed.
Better to use .focus()/.blur() events with .toggle(condition):
$(function(){
$('.showimage').on('focus blur', function(e){
$(this).next('div').toggle(e.type === "focus")
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name" id="name_1" value="" class="showimage" />
<div class="icon_1" id="icon" style="display:none;">one</div><br>
<input type="text" name="name" id="name_2" value="" class="showimage" />
<div class="icon_2" id="icon" style="display:none;">two</div>
input[type="text"] {} input[type="text"] + div {
display: none;
}
hr {} input[type="text"]:focus + div {
display: inline-block;
/* added for style you can also use display:block */
}
<input type="text" name="name" id="name_1" value="" class="showimage" />
<div class="icon_1" id="icon">test1</div>
<hr>
<input type="text" name="name" id="name_2" value="" class="showimage" />
<div class="icon_2" id="icon">test2</div>
Related
I've this small form in which the 1st field(title) is required by default. The 2nd and the 3rd are required only in a specific condition.
Case-I: If tool name is filled out, both tool name & tool URL become required.
Case-II: If tool URL is filled out, both tool name & tool URL become required.
I'm not sure it is working as expected.
Could you please help me correct my code?
$(document).ready(function(){
articleTitle = $('#title').val();
toolName = $('#toolName').val().trim();
toolURL = $('#toolURL').val();
if(((toolName.length>0)&&(toolURL==="")) || ((toolName.length<=0)&&(toolURL!==""))){
$('#toolName').prop('required', true);
$('#toolURL').prop('required' , true);
} else {
$('#toolName').prop('required', false);
$('#toolURL').prop('required', false);
}
$("#myForm").submit(function(){
sayHello();
return false;
});
});
label {
float: left;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<button>Submit</button>
</form>
You can simplify your code quite a bit, please see the comments for a description.
var $toolName = $('#toolName')
var $toolURL = $('#toolURL')
var $toolInputs = $($toolName).add($toolURL)
function sayHelloToMyLittleFriend() {
alert('sup! form was submitted')
}
$toolInputs.on('change', function(e) {
var toolName = $toolName.val()
var toolURL = $toolURL.val()
$toolInputs.prop('required', toolName || toolURL)
})
$('form').submit(function(e) {
var toolName = $toolName.val()
var toolURL = $toolURL.val()
var bothFilled = !!toolName && !!toolURL
var noneFilled = !toolName && !toolURL
if (bothFilled || noneFilled) {
sayHelloToMyLittleFriend()
return true
}
return false
})
label {
float: left;
width: 100px;
}
/* this will show what element has the required attribute */
[required] {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<button>Submit</button>
</form>
Here is a straightforward approach using library-less javascript (rather than jQuery).
(Albeit, you'll see that it's very similar to the jQuery).
Whenever data is entered into or removed from the form, the form inputs are checked and, as appropriate, the required attributes are added or removed.
var myForm = document.getElementById('myForm');
var toolName = document.getElementById('toolName');
var toolURL = document.getElementById('toolURL');
function checkInputs() {
if ((toolName.value !== '') || (toolURL.value !== '')) {
toolName.setAttribute('required','required');
toolURL.setAttribute('required','required');
}
if ((toolName.value === '') && (toolURL.value === '')) {
toolName.removeAttribute('required');
toolURL.removeAttribute('required');
}
}
myForm.addEventListener('keyup', checkInputs, false);
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<input type="submit" value="Submit" />
</form>
I'm trying to make a contact form, which should apply a class for css transitions when the input is onfocus/clicked by the user. If the user has typed name, the class from onfocus should stay there. If nothing is typed, an onblur event should remove the class and the effect.
I'm trying something like this, but I can't even make the onfocus event tricker an alert for testing my steps...
HTML:
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
CSS:
.input-expand {
transition: .7s;
width: 90px;
}
JS:
var inputValue = document.getElementsByClassName("input-value");
inputValue.onfocus = function() {
if (!inputValue.classList.hasClass("input-expand")) {
inputValue.addClass("input-expand");
}
// If no value is added and user does onblurr event, it should remove class .input-expand, otherwise leave class there.
}
var inputValue = document.getElementsByClassName("input-value");
var onFocus = function() { this.classList.add("input-expand");};
var onBlur = function() {if (!this.value) this.classList.remove("input-expand");};
for (var i = 0; i < inputValue.length; i++) {
inputValue[i].addEventListener('focus', onFocus, false);
inputValue[i].addEventListener('blur', onBlur, false);
}
.input-value {
transition: .7s;
width: 45px;
}
.input-expand {
transition: .7s;
width: 90px;
}
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
Without jQuery you could try:
var inputValue = document.getElementsByClassName("input-value");
[].forEach.call(inputValue,function(el){
el.onfocus=function() {
if (!el.classList.contains("input-expand")) {
el.className +="input-expand";
}
// If no value is added and user does onblurr event, it should remove class .input-expand, otherwise leave class there.
};
})
or as a fiddle:
https://jsfiddle.net/5v7n4je3/2/
mainly i think you problem lies in the ElementsByClassName array you have to iterate over the elements and use onFocus for every single one.
Notice the new Class is added once for every click at the moment.
I guess better solution for you to use css pseudo-classes. Use css style like below:
.input-value {
transition: .7s;
}
.input-value:focus {
width: 90px;
}
In this case you don't need to handle focus event through js and dynamically change classes of elements.
try this:
$(document).ready(function(){
$(".input-value").focus(function(){
//you focus code here
});
});
more reference: https://api.jquery.com/focus/
Using jQuery, try this :
https://api.jquery.com/focus/
$("input").focus(function() { $(this).addClass("input-expand"); });
$("input").blur(function() { $(this).val?null:$(this).removeClass("input-expand"); });
Here is the fix,
var inputValue = document.getElementsByClassName("input-value");
var onFocus = function() {
if (!this.classList.contains("input-expand")) {
this.classList.add("input-expand");
}
};
var onBlur = function() {
if (this.classList.contains("input-expand")) {
this.classList.remove("input-expand");
}
};
for (var i = 0; i < inputValue.length; i++) {
inputValue[i].addEventListener('focus', onFocus, false);
inputValue[i].addEventListener('blur', onBlur, false);
}
.input-expand {
transition: .7s;
width: 90px;
}
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
Try adding the script tag in the end of your body code.
Or else try and implement the solution provided below.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.my-focus-input{
border-color: red;
border-style: solid;
border-width: 1px;
height: 60px;
width: 300px;
}
.my-blur-input{
}
</style>
</head>
<body>
<input onfocus="myFocusFunction(this)" onblur="myBlurFunction(this)">
<script type="text/javascript">
function myFocusFunction(x) {
x.className = "my-focus-input";
}
function myBlurFunction(x) {
x.className = "my-blur-input";
}
</script>
</body>
</html>
Hi you just have to change yours css and js like this:
window.addEventListener("load",function(){
var inputValue = document.getElementsByClassName("input-value");
for(var i=0; i<inputValue.length; i++){
var f = inputValue[i];
f.className = "input-value input-expand";
f.addEventListener("focus", function(){this.style.maxWidth="90px";}, false);
f.addEventListener("blur", function(){if(this.value==""){this.style.maxWidth="30px";}}, false);
}
}, false);
.input-expand {
max-width:30px;
transition:max-width 0.7s ease 0s;
}
<div>
<form class="footer-contact-form" action="">
<fieldset class="footer-form-field">
<input id="name" class="input-value" name="name" type="text" autocomplete="off" required>
<label for="name">Navn*</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="company" class="input-value" name="company" type="text" autocomplete="off">
<label for="company">Firma</label>
</fieldset>
<fieldset class="footer-form-field">
<input id="email" class="input-value" name="email" type="email" autocomplete="off" required>
<label for="email">E-mail*</label>
</fieldset>
<fieldset class="footer-form-field-txt">
<textarea id="message" class="input-value" name="message" required></textarea>
<label for="message">Besked*</label>
</fieldset>
<input class="footer-msg-send" value="Send Besked" type="submit">
</form>
<button class="fetch-deal">Send</button>
</div>
You can try something like this:
window.onload = function() {
var span1 = document.createElement("span");
span1.innerHTML = "test";
span1.className = "info";
span1.style.display = "none";
var span2 = document.createElement("span");
span2.innerHTML = "test";
span2.className = "info";
span2.style.display = "none";
var span3 = document.createElement("span");
span3.innerHTML = "test";
span3.className = "info";
span3.style.display = "none";
var username = document.getElementById("username");
username.parentNode.appendChild(span1);
var password = document.getElementById("password");
password.parentNode.appendChild(span2);
var email = document.getElementById("email");
email.parentNode.appendChild(span3);
username.onfocus = function() {
span1.className = "info";
span1.innerHTML = "infoMsg";
span1.style.display = "inline";
};
username.onblur = function() {
var alphanums = /^[a-z0-9A-Z]+$/;
if (username.value.match(alphanums)) {
span1.className = "ok";
span1.innerHTML = "Accepted";
} else {
span1.className = "error";
span1.innerHTML = "error";
}
if (username.value.length == 0) {
span1.className = "info";
span1.innerHTML = "infoMsg";
span1.style.display = "none";
}
};
password.onfocus = function() {
span2.innerHTML = "infoMsg";
span2.className = "info";
span2.style.display = "inline";
};
password.onblur = function() {
if (password.value.length < 6 && password.value.length > 0) {
span2.className = "error";
span2.innerHTML = "error";
}
if (password.value.length > 6) {
span2.className = "ok";
span2.innerHTML = "Accepted";
}
if (password.value.length == 0) {
span2.className = "info";
span2.innerHTML = "infoMsg";
span2.style.display = "none";
}
};
email.onfocus = function() {
span3.innerHTML = "infoMsg";
span3.className = "info";
span3.style.display = "inline";
};
email.onblur = function() {
var res = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
if (res.test(email.value)) {
span3.className = "ok";
span3.innerHTML = "Accepted";
} else {
span3.className = "error";
span3.innerHTML = "error";
}
if (email.value.length == 0) {
span3.className = "info";
span3.innerHTML = "infoMsg";
span3.style.display = "none";
}
};
};
All this is for this Html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Form Validation</title>
<link rel="stylesheet" href="validate.css" />
<script src="validate.js"></script>
</head>
<body>
<h1>Form Validation</h1>
<form class="signup">
<table>
<tr>
<td><label for="username">Username:</label></td>
<td><input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" name="password" id="password" /></td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="text" name="email" id="email" /></td>
</tr>
</table>
</form>
</body>
</html>
When I try to run the code below, and step into it in the browser debugger, the length it's showing me is 1 or higher, yet it still drops into this block as if it were evaluated as true...am I missing something here?
function checkEmpty() {
var empty = false;
$('form input:text').each(function () {
console.log($(this).val())
if ($(this).val().length === 0) {
empty = true;
}
});
if (empty) {
$('#btnContinueCheckout1').attr('disabled', 'disabled');
$('#btnContinueCheckout2').attr('disabled', 'disabled');
} else {
$('#btnContinueCheckout1').removeAttr('disabled');
$('#btnContinueCheckout2').removeAttr('disabled');
}
}
HTML: (these are the input fields, and they are wrapped around a form, and have 2 checkout buttons that are not shown)
<br />
<br />
<label><strong>Full Name: </strong></label>
<input type="text" required="required" onkeyup="checkEmpty()" name="FullName" style="width: 235px;" /><br />
<br />
<label><strong>Mailing Address: </strong></label>
<input type="text" required="required" name="Address" onkeyup="checkEmpty()" style="width: 235px;" /><br />
<br />
<label><strong>Email: </strong></label>
<input type="text" required="required" style="width: 235px;" name="Email" onkeyup="checkEmpty()" /><br />
<br />
<label><strong>Phone Number: </strong></label>
<input type="text" required="required" name="Phone" onkeyup="checkEmpty()" />
Try this example code in a blank html page with jQuery linked:
<html>
<head>
<title>Example</title>
<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<form>
<label><strong>Full Name: </strong></label>
<input type="text" required="required" onkeyup="checkEmpty()" name="FullName" style="width: 235px;" /><br />
<br />
<label><strong>Mailing Address: </strong></label>
<input type="text" required="required" name="Address" onkeyup="checkEmpty()" style="width: 235px;" /><br />
<br />
<label><strong>Email: </strong></label>
<input type="text" required="required" style="width: 235px;" name="Email" onkeyup="checkEmpty()" /><br />
<br />
<label><strong>Phone Number: </strong></label>
<input type="text" required="required" name="Phone" onkeyup="checkEmpty()" />
<input type="button" id="checkbutton" value="deactivated" disabled/>
</form>
</body>
<script type="text/javascript">
function checkEmpty() {
var empty = false;
$('form input:text').each(function () {
console.log($(this).val());
if ($(this).val().length === 0) {
empty = true;
}
});
if (empty) {
$('#checkbutton').prop('disabled', 'disabled');
} else {
$('#checkbutton').prop('disabled', '');
}
console.log('count of textfields: ' + $('form input:text').length);
}
</script>
</html>
It works 100% for me. Look at the console to check the count for the textfields. If it's more then you expect, check your html if you have missed one. If all fields are filled, the button will be activated.
The problem is that you're assigning empty=true; when you read one input field, but then the loop will keep going and check further input fields. This means that if the first field is empty, but the second one isn't empty, your loop will not work. Try to break out of the .each() loop as soon as you find the first empty input.
function checkEmpty() {
var empty = false;
$('form input:text').each(function () {
console.log($(this).val()); // Also, you forgot the ; here
if ($(this).val().length === 0) {
empty = true;
return false; // Will break out of the .each() loop
}
});
if (empty) {
$('#btnContinueCheckout1').attr('disabled', 'disabled');
$('#btnContinueCheckout2').attr('disabled', 'disabled');
} else {
$('#btnContinueCheckout1').removeAttr('disabled');
$('#btnContinueCheckout2').removeAttr('disabled');
}
}
I want to make it possible to add and/or remove inputfields and a checkbox (for a competition-page)
Even though, when I click on the add button, 2 inputfields gets added and when i click the remove button, only on of those disappear. What is the issue?
var InputsWrapper = $("#answerDiv");
var AddButton = $(".adaddnext");
var x = InputsWrapper.length;
var FieldCount=1;
$(AddButton).click(function (e) {
FieldCount++;
$(InputsWrapper).append('<div class="adinputfield83"><div class="checkaccept cacc1"><label class="option"><input type="radio" id="contestAnswersChk_'+ FieldCount +'" name="correct" class="validate[required]"><span class="checkbox"></span></label> </div><input type="text" id="contestAnswer_'+ FieldCount +'" placeholder="Write possible answer" class="validate[required]"/><span class="font-entypo icon-circled-cross adaddnextremove" aria-hidden="true"></span></div></div>');
x++;
return false;
});
$("body").on("click",".adaddnextremove", function(e){
if( x > 1 ) {
$(this).parent('div').remove();
x--;
}
return false;
})
And the HTML:
<div id="answerDiv">
<div class="adinputfield83">
<div class="checkaccept cacc1">
<label class="option">
<input type="radio" id="contestAnswerChk_1" name="correct" class="validate[required]">
<span class="checkbox"></span>
</label>
</div>
<input type="text" id="contestAnswer_1" placeholder="Write possible answer" class="validate[required]">
<span class="font-entypo icon-plus adaddnext" aria-hidden="true"></span>
</input>
</div>
</div>
Can someone help me out? Thanks...
JSFiddle: http://jsfiddle.net/TrueBlueAussie/R3TLB/2/
You needed a delegated event for your add buttons as well as the delete buttons.
var InputsWrapper = $("#answerDiv");
var x = InputsWrapper.length;
var FieldCount = 1;
$(document).on('click', '.adaddnext', function (e) {
FieldCount++;
var template = $('#template').html();
template = template.replace(/{FieldCount}/g, FieldCount);
$(InputsWrapper).append(template);
x++;
return false;
});
$(document).on("click", ".adaddnextremove", function (e) {
if (x > 1) {
$(this).parent('div').remove();
x--;
}
return false;
})
HTML (using template HTML in dummy script block):
<script id="template" type="text/template">
<div class="adinputfield83">
<div class="checkaccept cacc1">
<label class="option">
<input type="radio" id="contestAnswersChk_{FieldCount}" name="correct" class="validate[required]" /><span class="checkbox"></span>
</label>
</div>
<input type="text" id="contestAnswer_{FieldCount}" placeholder="Write possible answer" class="validate[required]" /><span class="font-entypo icon-circled-cross adaddnextremove" aria-hidden="true">Del</span>
<input type="button" class="adaddnext" value="Add" />
</div>
</script>
<div id="answerDiv">
<div class="adinputfield83">
<div class="checkaccept cacc1">
<label class="option">
<input type="radio" id="contestAnswerChk_1" name="correct" class="validate[required]" /> <span class="checkbox"></span>
</label>
</div>
<input type="text" id="contestAnswer_1" placeholder="Write possible answer" class="validate[required]"> <span class="font-entypo icon-plus adaddnext" aria-hidden="true"></span>
</input>
</div>
<input type="button" class="adaddnext" value="Add" />
</div>
Notes:
Do not use $('body') to listen for delegated events. It can have odd side-effects with certain events (including click). Use a fallback of $(document) instead, if you do not have a closer non-changing ancestor to your dynamic elements. Really you should be using $('#answerDiv').on('click'... as that is the closest static ancestor (more efficient and more specific).
You have already defined you variables as selector $(...) so you should use only var names: AddButton.click()
The code looks then:
var InputsWrapper = $("#answerDiv");
var AddButton = $(".adaddnext");
var x = InputsWrapper.length;
var FieldCount=1;
AddButton.click(function (e) {
FieldCount++;
InputsWrapper.append('<div class="adinputfield83"><div class="checkaccept cacc1"><label class="option"><input type="radio" id="contestAnswersChk_'+ FieldCount +'" name="correct" class="validate[required]"><span class="checkbox"></span></label> </div><input type="text" id="contestAnswer_'+ FieldCount +'" placeholder="Write possible answer" class="validate[required]"/><span class="font-entypo icon-circled-cross adaddnextremove" aria-hidden="true"></span></div></div>');
x++;
return false;
});
$("body").on("click",".adaddnextremove", function(e){
if( x > 1 ) {
$(this).parent('div').remove();
x--;
}
return false;
})
or you can also define your variables as string, for example:
var AddButton = ".adaddnext"
then you can use it, as you did in your code:
$(AddButton).click(...)
Then is should look like:
var InputsWrapper = "#answerDiv";
var AddButton = ".adaddnext";
var x = InputsWrapper.length;
var FieldCount=1;
AddButton.click(function (e) {
FieldCount++;
InputsWrapper.append('<div class="adinputfield83"><div class="checkaccept cacc1"><label class="option"><input type="radio" id="contestAnswersChk_'+ FieldCount +'" name="correct" class="validate[required]"><span class="checkbox"></span></label> </div><input type="text" id="contestAnswer_'+ FieldCount +'" placeholder="Write possible answer" class="validate[required]"/><span class="font-entypo icon-circled-cross adaddnextremove" aria-hidden="true"></span></div></div>');
x++;
return false;
});
$("body").on("click",".adaddnextremove", function(e){
if( x > 1 ) {
$(this).parent('div').remove();
x--;
}
return false;
})
<pre>
<script>
// here i want to check form validation
//if i use for loop txtbox2 is not exist in my form so i am getting Js error
//Don't write individual validation
//check element is exist or not if exist check for validation
//I need know how to check an element is exist or not
</script>
<form
<input type="text" id="txtbox1" name="txtbox1" />*
<input type="text" id="txtbox3" name="txtbox3" />*
<input type="text" id="txtbox4" name="txtbox4" />*
<input type="text" id="txtbox5" name="txtbox5" />*
<input type="text" id="txtbox15" name="txtbox15" />*
<input type="text" id="txtbox28" name="txtbox28" />*
</pre>
Apply a class to them:
<input type="text" id="txtbox1" name="txtbox1" class="txt" />
<input type="text" id="txtbox3" name="txtbox3" class="txt" />
<input type="text" id="txtbox4" name="txtbox4" class="txt" />
<input type="text" id="txtbox5" name="txtbox5" class="txt" />
<input type="text" id="txtbox15" name="txtbox15" class="txt" />
<input type="text" id="txtbox28" name="txtbox28" class="txt" />
and go about like this:
function validate(){
var elms = document.getElementsByTagName('input');
for (var i = 0; i < elms.length; i++){
if (elms[i].className === 'txt'){
if (elms[i].value === ''){
alert('Make sure to fill in all required fields');
// now focus it
elms[i].focus();
return false;
}
}
}
return true;
}
And then call the above function like this:
<form ............ onsubmit="return validate();">
Post your code.
Easiest way to validate is by using jquery validate plugin.(Why write your own code when somebody else has done the same?).
An example
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#feedbackform").validate();
});
</script>
<body>
<form id = "feedbackform" method = "POST" action = "">
<h3><span>Contact Us</span></h3>
<fieldset>
<legend>Contact form</legend>
<label for="id_name">Name *</label>
<input id="id_name" class="required" type="text" name="name" />
<label for="id_email">Email</label>
<input id="id_email" type="email" name="email" class="email"/>
<label for="id_comments">Message *</label>
<textarea id="id_comments" class="required" name="comments"></textarea>
<button type="submit">Send</button>
</fieldset>
</form>
The elements that you want to validate add class="required". I hope the example provided is self-explainatory
You can get a reference to the element and check if the reference is null or not:
for (var i=1; i<=100; i++) {
var elem = document.getElementById('txtbox' + i);
if (elem != null) {
...
}
}
Another approach is to look at the elements in the form, but then you need a way to access the form of course:
var elems = document.getElementById('IdOfTheForm').elements;
for (var i=0; i<elems.length; i++) {
var elem = elems[i];
if (elem.tagName == 'INPUT' && elem.type == 'text' && elem.id.length > 6 && elemt.id.substr(0,6) == 'txtbox') {
...
}
}