JQuery Form Validation - javascript

I need to do a form validation with jQuery. But I'm having a problem in this.
I have a HTML form as below:
<FORM id="formID" method="POST" onsubmit="return checkRequiredFields(this)" action="">
<td><input class="required" type="text" id="input1" value="" /></td>
<td><input class="required" type="text" id="input2" value=""/> </td>
<td><input class="required" type="text" id="input3" value=""/> </td>
<td><input type="text" id="input4" value=""/> </td>
<td><input type="submit" id="save" value="Save" /></td>
</FORM>
The first three input text fields are required fields. I tried writing the script like below:
<script type="text/javascript">
function checkRequiredFields(form){
var no_errors = true;
$(form).find(".required").each(function(){
alert("Inside Loop");
var field = $(this);
if (field.val() == ""){
$("#"+field ).css("color","red");
no_errors = false;
} else {
$("#"+field ).css("color","white");
}
});
return no_errors;
}
</script>
But, the above code is not working as I expected. The alert() is never executed, meaning that the control does not find any element with class "required". So, what is the problem in my code?

$("#"+field ).css("color","red"); is not right. field is an object not a string, but since it's already a jQuery object you can just do this: field.css("color","red");. You'll have to do that for the other .css() call too: $("#"+field ).css("color","white"); => field.css("color","white");
Here is a demo: http://jsfiddle.net/eehV6/

Related

Set focus to next input field in a table after maxlength reached

How to set focus to next input field in a table?
Firstly I worked with that JQuery code: But it only works if the input fields are not spread over different and fields. How could I improve it that code or maybe someone knows a JS code that will work for autofocus fields spread over td and tr fields following tabindex?
<script>
$(document).ready(function(){
$('input').keyup(function(){
if(this.value.length==$(this).attr("maxlength")){
$(this).next().focus();
}
});
});
</script>
My html:
<table>
<tr>
<td><input type="text" id="field1" tabindex="1" name="test1" maxlength = "1"></td>
<td><input type="text" id="field2" tabindex="2" name="test2" maxlength = "1">.</td>
</tr>
<tr><td><input type="text" id="field3" tabindex="3" name="test3" maxlength = "1"></td></tr>
</table>
To do what you require you can retrieve all input elements and get the index of the current one within that collection. To move to the next input, select it from the collection using eq() and the next incremental index value.
Also note that your HTML is invalid - you seem to be missing a <tr> around the final td. I've corrected that in the following example:
jQuery($ => {
let $inputs = $('input').on('input', e => {
let $input = $(e.target);
let index = $inputs.index($input);
if ($input.val().length === $input.prop('maxlength')) {
$inputs.eq(index + 1).focus();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" id="field1" tabindex="1" name="test1" maxlength="1"></td>
<td><input type="text" id="field2" tabindex="2" name="test2" maxlength="1">.</td>
</tr>
<tr>
<td><input type="text" id="field3" tabindex="3" name="test3" maxlength="1"></td>
</tr>
</table>
It's pretty gross, but would work lol
$(document).ready(function(){
$('table input').keyup(function(){
if(this.value.length==$(this).attr("maxlength")){
tableInputs = $('table').find('input');
$(tableInputs[tableInputs.index(this)+1]).focus();
}
});
});

How to run jQuery function in input type text when input type text is in loop

#for (int i = 0; i < ViewBag.Count; i++) {
<tbody>
<tr>
<td> <input type="text" required readonly name="emp[#i].Total_Marks" value="#ViewBag.Total" class="form-control" id="tm" /></td>
<td> <input type="number" required name="emp[#i].Obtained_Marks" class="form-control" id="ob" /></td>
<td> <input type="number" required name="emp[#i].Percentage" class="form-control" id="percentage" onfocus="calcper()" /></td>
<td> <textarea cols="10" required rows="1" name="emp[#i].Remarks" class="form-control"></textarea></td>*
</tr>
</tbody>
}
function calculatePercentage() {
ab = $("#tm").val();
sb = $("#ob").val();
ntb = parseInt(sb) / parseInt(ab) * 100;
console.log(ntb);
document.getElementById("percentage").value = ntb;
}
I am new to mvc 5 and javascript/jQuery please help me how can I use this jQuery function in percentage in every input type which is created by loop but their id is same
As you said you need to call a function on your percentage textbox.
Let me tell you one thing assigning a same Id to a element is bad practice but you can have same name.
Recommend you to use common class attribute or common name attribute
<input type="text" name="percentage1" id="percentage1" class="percentage">
That you can consider as a empty class which will help you for your script operations
eg:
<html>
<head>
<script>
$('.percentage').keypress(function(){
alert('I called');
});
</script>
</head>
<BODY>
<input type="text" name="percentage1" id="percentage1" class="percentage" />
<input type="text" name="percentage2" id="percentage2" class="percentage"/>
<input type="text" name="percentage3" id="percentage3" class="percentage"/>
</BODY>
</HTML>
In the above code I have three textbox where it is pointed to same function which will show alert box.
In your case just apply the emp[#i] to the Id also and have a common class name or have a common name attribute which will help you.
Happy coding.

Javascript validating multiple fields

I want to validate multiple fields in my form. For that i don't want to write separate condition for all the fields. So i have assigned the error messages like a key and value pair.
If i leave all the fields without typing any value then it should populate error message.
This is my html code.
<head>
<title></title>
<script src="Scripts/validate_register.js"></script>
</head>
<body>
<table class="valid">
<tr>
<td>id:</td>
<td><input type="text" id="id1" placeHolder="Enter your name"/></td></tr>
<tr><td>email:</td>
<td><input type="text" id="id2" placeHolder="Enter your email"/></td></tr>
<tr><td>password:</td>
<td><input type="text" id="id3" placeHolder="Enter your password"/></td></tr>
<tr><td>address:</td>
<td><input type="text" id="id4" placeHolder="Enter your address"/></td></tr>
<tr><td>contact no:</td>
<td><input type="text" id="id5" placeHolder="Enter your contact no"/></td>
</tr>
<tr><td><input type="submit" onclick="validate()" value="submit"> </td></tr></table>
</body>
This is my javascript code.
function validate () {
var error={
id1:'name Cannot be empty',
id2:'email cannot be empty',
id3:'password cannot be empty',
id4:'address Cannot be empty',
id5:'contactno cannot be empty'
}
var elements=document.querySelectorAll('input');
for(var i=0;i<elements.length;i++){
if(elements[i]['value']=="")
{
var id=elements[i]['id'];
document.querySelector("."+id).innerHTML=error[id];
}
}
}
This shows an error on the document.querySelector("."+id).innerHTML=error[id]; line about something being null.
document.querySelector("."+id).innerHTML=error[id];
That expects you to have an element with a class corresponding to the input's id (e.g.,
class="id2" and such). You haven't shown any of those in your question. querySelector returns null if it can't find a matching element.
If you add a series of things like this in appropriate locations:
<span class="id1"></span>
...then that element will get the error message for your <input id="id1">. Or of course, as these elements are unique, you could use ids like error_id1, error_id2, and such.
Here's a complete example using classes: Live Copy
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<table class="valid">
<tr>
<td>id:</td>
<td><input type="text" id="id1" placeHolder="Enter your name"/><span class="id1"></span></td></tr>
<tr><td>email:</td>
<td><input type="text" id="id2" placeHolder="Enter your email"/><span class="id2"></span></td></tr>
<tr><td>password:</td>
<td><input type="text" id="id3" placeHolder="Enter your password"/><span class="id3"></span></td></tr>
<tr><td>address:</td>
<td><input type="text" id="id4" placeHolder="Enter your address"/><span class="id4"></span></td></tr>
<tr><td>contact no:</td>
<td><input type="text" id="id5" placeHolder="Enter your contact no"/><span class="id5"></span></td>
</tr>
<tr><td><input type="button" onclick="validate()" value="submit"> </td></tr></table>
</body>
<script>
"use strict";
function validate () {
var error={
id1:'name Cannot be empty',
id2:'email cannot be empty',
id3:'password cannot be empty',
id4:'address Cannot be empty',
id5:'contactno cannot be empty'
}
var elements=document.querySelectorAll('input');
for(var i=0;i<elements.length;i++){
var id=elements[i]['id'];
document.querySelector("."+id).innerHTML=elements[i].value ? "" : error[id];
}
}
</script>
</body>
</html>
In the above, I've also cleared the errors when the field had a value, so that the second time it runs, the error disappears. (I also changed the submit button to just a button, but that's only so the form doesn't get submitted nowhere in the example.)
Side note: I'd move validate to an onsubmit on the form, and have it return false if there are any errors.
. is for classes. If you want to detect ids, you need to use #. Moreover, you need to use value, not innerHTML. So, correct
document.querySelector("."+id).innerHTML=error[id];
to
document.querySelector("#"+id).value=error[id];

Walk through a form in javascript and check for blank inputs?

I apologize for asking such a "noob" question but I'm outside my area of expertise here.
I'm using Dojo 1.9 and I need to walk through a submitted form and determine if any of the input fields are blank. The tricky part is that the form is dynamic, it can contain an array of child elements of each array element, with names like itemList[1].myName:
<form id="businessReferences" action="/yabba/dabba/doo" method="post">
<input id="itemList[0].myName" name="itemList[0].myName" type="text" value=""/>
<input id="itemList[0].myAddress" name="itemList[0].myAddress" type="text" value=""/>
<input id="itemList[1].myName" name="itemList[1].myName" type="text" value=""/>
<input id="itemList[1].myAddress" name="itemList[1].myAddress" type="text" value=""/>
<input id="itemList[2].myName" name="itemList[2].myName" type="text" value=""/>
<input id="itemList[2].myAddress" name="itemList[2].myAddress" type="text" value=""/>
</form>
What is the best way to walk through this form and check to see if all the fields for each parent element are empty? For example if all the fields for itemList[2] are empty? Is there a particular method for doing this? Seems like it would be a fairly common problem but I haven't been able to track down an answer.
Just add an submit button in the form
<form id="businessReferences" action="/yabba/dabba/doo" method="post" onsubmit="return validate()">
<input id="itemList[0].myName" name="itemList[0].myName" type="text" value=""/>
<input id="itemList[0].myAddress" name="itemList[0].myAddress" type="text" value=""/>
<input id="itemList[1].myName" name="itemList[1].myName" type="text" value=""/>
<input id="itemList[1].myAddress" name="itemList[1].myAddress" type="text" value=""/>
<input id="itemList[2].myName" name="itemList[2].myName" type="text" value=""/>
<input id="itemList[2].myAddress" name="itemList[2].myAddress" type="text" value=""/>
<input type='submit' value="Submit"/> <!-- to trigger validation on this button click -->
</form>
Javscript for validation , it will account for dynamically added element also
<script type='text/javascript'>
function validate(){
FromRef = document.getElementById('businessReferences');
for(i=0; i<FromRef.elements.length; i++)
{
if((FromRef.elements[i].value).trim() ==""){ // see if the value is blank popup and alert
alert( FromRef.elements[i].name +"is required");
return false; // not to submit form
}
return true;//submit form
}
</script>

Send data without submit button (Javascript / jQuery)

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="form1" id="form1" action="coillist" method="POST">
<table id="dataTable" border="1">
<tbody>
<tr>
<th>Coil #</th><th>Width</th><th>Gauge</th>
</tr>
<tr>
<td><input type="text" maxlength="7" size="7" name="coil_id" value="coil_11"></td>
<td><input type="text" size="7" name="width" value="120"></td>
<td><input type="text" size="5" name="gauge" value="130"></td>
</tr>
<tr>
<td><input type="text" maxlength="7" size="7" name="coil_id" value="coil_22"></td>
<td><input type="text" size="7" name="width" value="220"></td>
<td><input type="text" size="5" name="gauge" value="330"></td>
</tr>
<tr>
<td><input type="text" maxlength="7" size="7" name="coil_id" value="coil_33"></td>
<td><input type="text" size="7" name="width" value="320"></td>
<td><input type="text" size="5" name="gauge" value="330"></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
I have a dynamic row adding table that could add row into the table.
I am showing it in 3 rows, it could be 1 row, or 4 rows, or n rows if a use wants to add data in.
My question is: How can I send data (coil_id) out without click submit button?
In this example, I want to send a coil_id (coil_id = ”coil_22” in this case) to the server without using submit button.
This is also something like: detect if user enter a coil in length of 7 char or digit (Ex: coil_22 or 2C12345), then it will submit the “coil_22” (not coilL_11 or coil_33) to server without click any submit / send button.
I have used JavaScript / jQuery a while, still feel lost sometimes.
Highly appreciate your help.
You can make it with a .keyup(), just add a class to each input for example
<input type="text" class="coil_input" maxlength="7" size="7" name="coil_id" value="coil_11">
<input type="text" class="coil_input" maxlength="7" size="7" name="coil_id" value="coil_22">
<script>
$('.coil_input').keydown(function() {
if($.trim($(this).val()).length == 7){
var now_input_value = $(this).val();
$.post('file.php', {now_input: now_input_value}, function(){ alert('Data sent'); }).fail(function(){ alert('An error has ocurred'); });
}
});
</script>
All the inputs has to have the same class
Remember to add jQuery to your document.
here is example of jquery ajax. serialize will create generate query string that will be sent to your url.
var datastring = $("#yourForm").serialize();
$.ajax({
type: "POST",
url: "your url",
data: datastring,
dataType: "json",
success: function(data) { alert('all ok');}
});

Categories