Javascript validation for multiple textboxes - javascript

I am having some trouble figuring out how to validate my textboxes using js. I have 10 textboxes, the user can fill out any number 1-10, but cant fill out 0. Here is the js that I have written, but it only returns true if all 10 textboxes are filled, rather than just checking if one is filled.
function submitIt() {
if (document.isForm.Student_ID.value == null) {
alert ("You must enter a Colleague ID.");
return false;
} else {
return true;
}
}
And here is the form.....
<form name="isForm" onSubmit="return submitIt()">
<input name="Student_ID" type="text" id="idField1" />
<input name="Student_ID" type="text" id="idField2" />
<input name="Student_ID" type="text" id="idField3" />
<input name="Student_ID" type="text" id="idField4" />
<input name="Student_ID" type="text" id="idField5" />
<input name="Student_ID" type="text" id="idField6" />
<input name="Student_ID" type="text" id="idField7" />
<input name="Student_ID" type="text" id="idField8" />
<input name="Student_ID" type="text" id="idField9" />
<input name="Student_ID" type="text" id="idField10" />
<input name="SUBMIT" type="submit" />
</form>
I realize that I could change all of the names, and check each one, but I am trying to avoid that much clutter in my code, and am curious the best way to do this. Any help is appreciated, thanks!

You can get a collection of all these textboxes with document.getElementsByName. Then loop through them, and make sure at least one is filled in:
var allTbs = document.getElementsByName("Student_ID");
var valid = false;
for (var i = 0, max = allTbs.length; i < max; i++) {
if (allTbs[i].value) {
valid = true;
break;
}
}
DEMO

Function is iterating by all of the student text boxes and return true if some element is filled out. Protected against that if input contain only spaces :)
function submitIt() {
for( var i = 0, t = document.getElementsByName( "Student_ID" ), l = t.length; i < l; i++ )
if( t[i].value && !/^\s+$/.test( t[i].value ) )
return true;
return false
}
Demo on: http://jsfiddle.net/hhD2x/

you can use jquery.
add common class name for all your textboxes i.e.
<input name="Student_ID" type="text" id="idField1" class="student" />
now in js function
function submit()
{
$('.student').each(function() {
if($(this).val() == '' || $(this).val() == null)
{
// your error message
return false;
}
}
}
this function check all the elements with student class.

$('input[type="text"], select,
:input[type="date"],
:input[type="email"],
:input[type="radio"]').each(function () {
if ($.trim($(this).val()) == '' ) {
// your error message here
isValid = false;
}
});

Related

JS Function is invoked but no result

When I invoke the function it is getting invoked but it flashes the result. Could please tell me what is the mistake I did?
Below is the HTML Code I used:
I have replaced the input type as a button but still, error not fixed.
function reg() {
//Name Field
var f = document.forms["registration"]["fullname"].value;
if (f == "") {
alert("Enter the name");
return false;
} else if (!f.match(/^.[a-zA-Z]+$/))
{
alert("Enter only alphabets");
return false;
}
document.getElementById('details').innerHTML = "Hi" + registration.fullname.value;
}
<form name="registration" onsubmit="return reg()">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
Here is what I believe you want to do.
Note it is better to add an event handler in the script rather than having an inline handler, but for now I pass the form itself in the function
function reg(form) {
//Name Field
var f = form.fullname.value;
if (f == "") {
alert("Enter the name");
return false;
}
// no need for else when you return
if (!f.match(/^[\. a-zA-Z]+$/)) { // I personally have a space in my full name
alert("Enter only alphabets and space");
return false;
}
document.getElementById('details').innerHTML = "Hi " + f;
// change to true if you want to submit the form but you will then not be able to see the HI
return false;
}
<form name="registration" onsubmit="return reg(this)">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
<span id="details"></span>

Prevent multiple alert on "oninvalid" html

I was thinking, can i stop the alerts after the first?
I'll explain it better, every time I confirm the form, start an aler for every input that has oninvalid.
so if i have 10 inputs, i'll have 10 alarms. Is it possible to interrupt them after the first one?
<form>
<input type="text" oninvalid="alert('test1')" required />
<input type="text" oninvalid="alert('test2')" required />
<button>Send</button>
</form>
Fiddle: https://jsfiddle.net/9d1L5pxd/1/
You can consider doing something like I demonstrate below. Basically just add an event handler to the send button, which will call a validation function on your form each time it's clicked.
The validation function checks all the text type field values. If a text field with an invalid value is encountered, the function will return false (stop immediately).
If the function doesn't find any problems with the user input then it will return true. You can use the return value to determine if the form should be submitted or whatever if you need to.
var btnSend = document.getElementById('btnSend');
btnSend.addEventListener('click', function() {
var isValid = validateForm();
if (isValid)
console.log('Form is ready to submit.');
});
function validateForm() {
var formToValidate = document.getElementById('dataForm');
var elements = formToValidate.elements;
var i;
for (i = 0; i < elements.length; i++) {
if (elements[i].type == 'text') {
//replace this with your actual validation
var invalid = elements[i].value.length == 0;
if (invalid) {
alert(elements[i].id + ' is invalid.');
return false;
}
}
}
return true;
}
<form id="dataForm">
<input id="field1" type="text" required />
<input id="field2" type="text" required />
<input id="btnSend" type="button" value="Send">
</form>

JavaScript Form Validation Not Showing Alert or Changing Input Background Colour

I made this script to validate my forms however, when I leave a textfield blank nothing happens, there is no red background to the input box or alert message as I expected there to be.
function validateForm()
{
/* For all forms in the document */
for(var i in document.forms)
{
/* Get the forms inputs */
var inputs = document.forms[i].getElementsByTagName("input");
for(var j in inputs)
{
/* Make sure we don't try to validate the submit button */
if(inputs[j].type == "text")
{
if(inputs[j].value.trim() == "" || inputs[j].value.trim() == null)
{
inputs[j].style.backgroundColor = "red";
alert("Please ensure all boxes are filled in");
return false;
}
}
}
}
}
Here is one of my forms if that helps:
<form name="searchArtists" method="get" onsubmit="return validateForm()">
<input type="text" name="artists" placeholder="Search Artists" maxlength="255" size="32" />
<input type="submit" name="submit" value="Search"/>
</form>
Use placeholder attribute for placeholder text
<input type="text" name="artists" placeholder="Search Artists"...
Another issue I suggest to don't allow spaces as well
if(inputs[j].value.trim() == "") { ...
In your code i is a form and j is an input. Because of that, document.forms[i] and inputs[j] don't work.
Fixed JavaScript function:
function validateForm()
{
/* For all forms in the document */
for(var i in document.forms)
{
/* Get the forms inputs */
var inputs = i.getElementsByTagName("input");
for(var j in inputs)
{
/* Make sure we don't try to validate the submit button */
/* Trim value to not allow values with only spaces */
if(j.type == "text")
{
if(j.value == null || j.value.trim() == "")
{
j.style.backgroundColor = "red";
alert("Please ensure all boxes are filled in");
return false;
}
}
}
}
}
HTML:
<form name="searchArtists" method="get" onsubmit="return validateForm()">
<input type="text" name="artists" placeholder="Search Artists" maxlength="255" size="32" />
<button type="submit">Search</button>
</form>
Let's cut this down a bit, first add an ID to the element we want to validate, I also suggest changing your current "value" to a "placeholder", like so:
<input id="artistQueryInput" type="text" name="artists" placeholder="Search Artists" maxlength="255" size="32" />
Now on to the Javascript:
function validateForm(){
//Get element
var inputElement = document.getElementById('artistQueryInput');
//Get value
var rawArtistQueryString = inputElement.value;
//Strip all whitespace
var baseArtistQueryString = rawArtistQueryString.replace(/ /g, "");
//Validate string without whitespace
if((baseArtistQueryString == '') || (baseArtistQueryString == NULL) ||){
//Assuming j is artistQueryInput
inputElement.style.backgroundColor = "red";
alert("Please ensure all boxes are filled in");
return false;
}
}

Validating group of radio buttons

function validate()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var valid = true;
if(a.value.length<=0 || b.value.length<=0 || a.value.trim()=="" || b.value.trim()=="")
{
alert("Don't leave the field empty!");
valid = false;
}
if(isNaN(a.value) || isNaN(b.value))
{
alert("Enter a proper number!");
valid = false;
}
for(var i=0; i<form.elements.length; i++)
{
if(form.elements[i].checked)
{
valid = true;
}
else
{
alert("No option selected!");
valid = false;
}
}
return valid;
};
This is my JavaScript function to validate group of radio buttons to check if atleast one of them is selected. And, the one below is my form.
<form name="myForm" font-size="75px;" action ="serv" method="get" onsubmit="return validate();" >
<hr/>
Enter the 1st number: <input type="text" name="a" id="a" /><br/>
Enter the 2st number: <input type="text" name="b" id="b"/><br/><br/>
<label>Add</label><input type="radio" name="option" value="Add" id="r1" /><br/>
<label>Subtract</label><input type="radio" name="option" value="Subtract" id="r2" /><br/>
<label>Multiply</label><input type="radio" name="option" value="Multiply" id="r3" /><br/>
<label>Divide</label><input type="radio" name="option" value="Divide" id="r4" /><br/>
<input type="submit" value="Submit" />
</form>
When i give input and no radio button is selected it should alert the user, but its not happening. Can someone guide where I've gone wrong? And help me out with this? I know there might be lot of duplicates, but I've tried them all to no avail. When i click submit without selecting the radio button it gives me a blank page. Any help is appreciated. Thanks.
Try this, Check the demo here Fiddle
function validate()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var valid = true;
if(a.value.length<=0 || b.value.length<=0 || a.value.trim()=="" || b.value.trim()=="")
{
alert("Don't leave the field empty!");
valid = false;
}
if(isNaN(a.value) || isNaN(b.value))
{
alert("Enter a proper number!");
valid = false;
}
var ele = document.getElementsByName("option");
var flag=0;
for(var i=0; i<ele.length; i++)
{
if(ele[i].checked)
{
flag=1;
break;
}
}
if(flag == 0)
{
alert("No option selected!");
valid = false;
}
return valid;
};

Assigning text box "other" value to radio button value

I've spent over three hours on this trying to work with the code I've been given. I've never done javascript. Please help.
I have a form with 4 radio buttons, one specifying "other" and next to a text box that is supposed to post the user specified value. Here's what I've tried.
HTML:
<td id="amount_container">
<input name="chargetotal" type="radio" value="75.00" onclick="donation_value();" />$75<br />
<input name="chargetotal" type="radio" value="125.00" onclick="donation_value();" />$125<br />
<input name="chargetotal" type="radio" value="250.00" onclick="donation_value();" />$250<br />
<input name="chargetotal" type="radio" value="other" />other
<input type="text" name="specified" size="10" />
</td>
javascript:
<script type="text/javascript">
function donation_value(){
var val = 0;
for( i = 0; i < document.form1.chargetotal.length; i++ ) {
if( document.form1.chargetotal[i].checked == true ) {
val = document.form1.chargetotal[i].value;
if(val=='other') {
document.form1.specified.disabled=false;
document.form1.specified.focus();
document.form1.chargetotal.value=document.form1.specified.value;
} else {
document.form1.specified.disabled=true;
}
}
}
}
</script>
It seems, you forgot to add onclick handler to "other" radio.
I think it should be
<input name="chargetotal" type="radio" value="other" onclick="donation_value();"/>
Update
I think I understood what your problem is :)
You can add callback, whick will be invoked when page is submitted. This callback will set value for "other" radio if it is selected. Something like
function assignOtherValue() {
for( i = 0; i < document.form1.chargetotal.length; i++ ) {
if( document.form1.chargetotal[i].checked == true ) {
var val = document.form1.chargetotal[i].value;
if(val=='other') {
document.form1.chargetotal[i].value=document.form1.specified.value;
}
}
}
return true;
}
And add to form:
<form name="form1" onSubmit="return assignOtherValue();">
Fix your js:
function donation_value(){
var val = 0;
var the_form = document.forms['form1'];
for( i = 0; i < the_form.chargetotal.length; i++ ) {
if( the_form.chargetotal[i].checked == true ) {
val = the_form.chargetotal[i].value;
if(val=='other') {
the_form.specified.disabled=false;
the_form.specified.focus();
the_form.chargetotal.value=the_form.specified.value;
} else {
the_form.specified.disabled=true;
}
}
}
}
fiddle: http://jsfiddle.net/maniator/vQNyY/

Categories

Resources