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];
Related
#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.
I am using Ajax to submit forms in serial. I am trying to make the first s_referee_email + s_referee_fname pair required while the second or others not - there will be up to five of these pairs. I cant seem to figure how to make just the first pair required without breaking the form. I have tried using HTML5 and some answers from stack but havent been able to get anything to work. Any advice is greatly appreciated!
fiddle: https://jsfiddle.net/badsmell/gcrvqbna/
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<!--serial submit ajax-->
<script>
function mySubmit(){
var myForms = $("form");
myForms.each(function(index) {
var form = myForms.eq(index);
var serializedForm = form.serialize();
serializedForm += '&s_referer_fname='+$('#s_refererFname').val();
$.post("http://post.aspx", serializedForm, function (data, status) {
if (status === "success"){
window.location.href= "http://redirect";
}
});
});
}
</script>
<title>Forward a copy to a friend</title>
<style type="text/css">
*[class=hide] {
display: none
}
</style>
</head>
<body>
<!--hidden iframe-->
<iframe class="hide" id="myIframe"></iframe>
<form method="post" action="post.aspx" target="myIFrame">
<input type="hidden" name="s_referer_email" value="test#test.com" />
<input type="text" size="30" maxlength="255" name="s_referee_email" value="" required >
<input type="text" size="22" maxlength="50" name="s_referee_fname" value="" required >
</form>
<form method="post" action="post.aspx" target="myIFrame">
<input type="hidden" name="s_referer_email" value="test#test.com" />
<input type="text" size="30" maxlength="255" name="s_referee_email" value="" >
<input type="text" size="22" maxlength="50" name="s_referee_fname" value="" >
</form>
<label for="s_referer_fname">Your name:</label> <br /> <input type="text" name="s_referer_fname" value="" size="20" id="s_refererFname" ><br>
<p><button onclick="mySubmit();">Submit</button> </p>
</body>
</html>
Adding required="required" to the tags can let you make any field compulsory to be filled by user.
You should never use .onclick(), or similar attributes from a userscript.
Userscripts operate in a sandbox, and onclick operates in the target-page scope and cannot see any functions your script creates.
Always use addEventListener() (or an equivalent library function, like jQuery .on()).
So instead of code like:
something.outerHTML += '<input onclick="func()" id="button_id" ...>'
You would use:
something.outerHTML += '<input id="button_id" ...>'
document.getElementById ("button_id").addEventListener ("click", func, false);
And for your answer, one method is to perform a check before actually submitting the forms. Check if the required fields have been filled, if yes, go ahead and submit the form, or else don't submit and show an error message instead.
Mobile web application contains order entry form.
Rows contain product code and quantity.
Mobile barcode scanner sends enter after barcode and this causes form to submit.
How to prevent form submit on enter: enter should behave like tab, it must:
activate next input field.
submit should done using submit button only.
jQuery, jQuery-mobile, ASP.NET MVC4 are used. Application is running in Motorola MC2180 computer using its WebKit based browser. This is modern browser and supports html5.
data entry page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<link href="/Scripts/jquery-mobile/jquery.mobile-1.3.2.css" rel="stylesheet"/>
<script src="/Scripts/jquery/jquery-1.9.1.js"></script>
<script src="/Scripts/jquery-mobile/jquery.mobile-1.3.2.js"></script>
<script src="/Scripts/applibrary.js"></script>
</head>
<body>
<div>
<form id='inputform' method="post"
action ="/Detail/SaveFullDocument">
<input type="hidden" name="_rows" />
<table id="tableId">
<tr>
<th>Code</th>
<th>Quantity</th>
<td>
<input type="button" value="+" onclick="addRow('tableId')" /></td>
</tr>
<tr>
<td>
<input type="text" name="Product" /></td>
<td>
<input type="number" name="Quantity" /></td>
<td>
<input type="button" value="-" onclick="deleteRow(this)" /></td>
</tr>
<tr>
<td>
<input type="text" name="Product" /></td>
<td>
<input type="number" name="Quantity" /></td>
<td>
<input type="button" value="-" onclick="deleteRow(this)" /></td>
</tr>
....
</table>
<input type="button" value="+" onclick="addRow('tableId')" />
<input type="submit" value='Save' />
</form>
</div>
</body>
</html>
$('#inputform').on('keydown', 'input', function (event) {
if (event.which == 13) {
console.log($(this));
$(this).next('input').focus();
event.preventDefault();
}
});
if all you need to focus next element upon enter, then no need to loop over all inputs as $(this) will be the target element.
DEMO
First, catch the enter, as the previous answer explained, then identify the next input field and call the .focus() method on it.
$(form).on('keyup', 'input',
function(event)
{
if(event.which() == 13)
{
event.preventDefault(); //this prevents the default, as was previouslynoted
$.each($('input'),
function(index, input)
{
if(input == this)
{
$('input')[index+1].focus();
}
});
}
});
You can prevent it with jQuery as follows:
$(document).on('keyup', 'input', function(event){
if(event.which()===13){ // 13 is the keyCode of enter Key
event.preventDefault();
}
});
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/
The editvalidate() function is not getting called at all:
Please suggest why. What's the remedy?
<script type="text/javascript">
function editvalidate() {
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var numericExpression = /^[0-9]+$/;
if(document.editprofile.userid.value == '' || document.editprofile.password.value == ''||document.editprofile.name.value == ''||document.editprofile.age.value == ''||document.editprofile.collegeid.value == ''||document.editprofile.mobile.value == ''||document.editprofile.address.value == ''||document.editprofile.department.value == ''||document.editprofile.email.value == ''||document.editprofile.sec_ques.value == ''||document.editprofile.answer.value == ''){
alert("Hey! you can't left a field blank!");
return false;
}
else if(!document.editprofile.email.value.match(emailExp)){
alert("You need to enter a valid email address to get proper notifications!");
return false;
} else if(!document.editprofile.mobile.value.match(numericExpression)){
alert("Mobile numbers are all numeric digits i think!");
return false;
} else if(document.editprofile.mobile.value.length < 10){
alert("Mobile number must be 10 digit long!");
return false;
}
else{
return true;
}
}
</script>
the form is given below and its used to fetch data from database and itself getfilled with the values.the editable entries are corrected and the form is submitted.its working fine just not getting validated cz the editvalidate() is not getting called at all.why?
<form name="editprofile" action="editprofile.jsp" method="post" onsubmit="return editvalidate();">
<table align="center">
<%
for(int i = 0; i < list.length ; i++){
%>
<tr>
<td>Name:</td>
<td><input type="text" name="name" size="35" style="width: 219px" value="<%=list[i].getName() %>" maxlength="25"></td>
</tr>
<input type="hidden" name="userid" size="20" style="width: 220px"
value="<%=list[i].getUserid() %>" maxlength="10">
<tr>
<td>Address:</td>
<td><input type="text" name="address" size="46"
style="width: 221px" value="<%=list[i].getAddress() %>"
maxlength="50"></td>
</tr>
<tr>
<td>E-mail:</td>
<td><input type="text" name="email" size="20"
style="width: 220px" value="<%=list[i].getEmail() %>" maxlength="40"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" name="age" size="20" style="width: 219px"
value="<%=list[i].getAge() %>" maxlength="2"></td>
</tr>
<tr>
<td>College ID:</td>
<td><input type="text" name="collegeid" size="20"
style="width: 219px" value="<%=list[i].getCollegeid() %>"
maxlength="10"></td>
</tr>
<tr>
<td>Mobile:</td>
<td><input type="text" name="mobile" size="20"
style="width: 218px" value="<%=list[i].getMobile() %>" maxlength="10"></td>
</tr>
<tr>
<td>Department:</td>
<td><input type="text" name="department" size="20"
style="width: 218px" value="<%=list[i].getDepartment() %>"
maxlength="10"></td>
</tr>
<tr>
<td>Security Question:</td>
<td><input type="text" name="sec_ques" size="20"
style="width: 218px" value="<%=list[i].getSec_ques() %>"
maxlength="50"></td>
</tr>
<tr>
<td>Answer:</td>
<td><input type="text" name="answer" size="20"
style="width: 218px" value="<%=list[i].getAnswer() %>" maxlength="50"></td>
</tr>
<tr>
<td><input type="submit" name="operation" value="editprofile"
style="width: 118px"></td>
<td><input type="reset" value="Reset" name="B2"></td>
</tr>
<%
}
%>
i checked it the way u suggested and found that the function is getting called.but why the rest alerts r nt visible? isnt thatdue to the value attribute in input tags
With the as far given little information, all I can answer is: Just run a Javascript debugger. I can recommend you Firebug for this.
That said, in the future please come up with an SSCCE instead of cutouts of code with unnecessary clutter. This avoids crawling long in the code searching for lines of relevance and at first glance obvious questions as "Are they in the same file?", "Did you add alert('blah') as 1st line of function to see if it actually is invoked?", "Did the browser have JS enables?", "Are you sure that you didn't typo'ed the function name?", "Isn't there more into the code which may have disturbed it?", etcetera.
Here's a basic example of such an SSCCE:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2063598</title>
<script>
function validate(form) {
alert('Validate method invoked!');
return false;
}
</script>
</head>
<body>
<form onsubmit="return validate(this)">
<input type="text" name="foo" class="required">
<input type="submit">
</form>
</body>
</html>
That said, I see that you're still using the legacy scriptlets in your JSP. If you can, I strongly recommend to stop using it and switch to taglibs/EL before it's too late. Raw Java code belongs in Java classes, not in JSP files.
Basic example with JSTL's (just drop jstl-1.2.jar in /WEB-INF) c:forEach:
<table>
<c:forEach items="${users}" var="user">
<tr>
<td><input type="text" name="address" value="${user.address}"></td>
<td><input type="text" name="email" value="${user.email}"></td>
<td><input type="text" name="college" value="${user.college}"></td>
</tr>
</c:forEach>
</table>
And also keep CSS in its own CSS file to separate style from content and to increase webapp performance and maintainability.
you don't call it anywhere from your html, you should probably call it <form onsubmit="return editvalidate();">
Ok now I see he formatted it properly, I don't mind the down votes I give them sometimes as well.
#Robin Agrahari
you probably have somewhere typo in the javascript no one is going to go trought it but you, try to test one by one if by using alert as you do. But don't do it on sumbit, create a mock button that will call(on click) this function editvalidate(); and check your function thoroughly and you will get to the problem eventually
How can you tell it's not being called? I'd put an alert right at the top of the method and see if it hits that. It's possible you're hitting some kind of error somewhere. If an alert at the top of editvalidate doesn't occur, try changing the obsubmit to:
onsubmit="alert('hello!'); return editvalidate();"
then you should at least see "Hello!" when you click the submit button.
looking at the code it should be called
Or Try
onsubmit="editvalidate(); return false;"
Or check where it is not misplaced, I mean the javascript should be in <head> </head>
actually i used a password checking parameter in the first if block document.editprofile.password.value == ''
and i never used an attribute like password in the form.that was my mistake and so it was not working.i found it using the firebug tool.thanks for the help.