I have following html form. There will be many business validations – and if validation fail an "error" attribute will be set on the element.
In the following form, I am returning a flag to see whether the validation is failed. How to make a common function to find all elements that has "error" attribute, and alert the value of "errDesc" attribute?
Note: I am looking for a JavaScript solution without using other libraries.
Note: My client browsers does not support HTML5
<html>
<head>
<script type="text/javascript">
function loadMessage(frm)
{
alert("Page Loaded");
}
function CustomSetError(element, msg) {
alert("calledSUB");
var isError = false;
//In productioon code, error will be set based on business validation
try {
//Set error
element.setAttribute("error", "true");
element.setAttribute("errDesc", msg);
isError = true;
}
catch (e) { }
return isError;
}
function ValidateForm(frm) {
alert("validate");
var isErrorPresent = CustomSetError(frm.txtBillAddressText, "TestMessage");
if (isErrorPresent) {
return false;
}
}
</script>
</head>
<body bgcolor="#E5DBE2" topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" onload="loadMessage(frmPOHeader)">
<form name="frmPOHeader" method="post" id="frmPOHeader">
<input name="txtBillAddressText" class="ArrowSmall" type="text" readonly="readonly" id="txtBillAddressText" fieldname="Bill To" />
<input name="hidBillToBuyerAddressCD" type="hidden" id="hidBillToBuyerAddressCD" />
<input type="submit" name="btnSubmit" value="Submit" onclick="return ValidateForm(frmPOHeader);" language="javascript" id="btnSubmit" class="ButtonSmallBlue" />
<br /><br />
<input name="txtDummy" class="ArrowSmall" type="text" readonly="readonly" id="txtDummy" fieldname="Dummy" />
</form>
</body>
</html>
You can use querySelectorAll to get all the div.
Then use hasAttribute to check if the element has an attribute error
Use getAttribute to get the errDesc
// will give all the div
var a = Array.prototype.slice.call(document.querySelectorAll("div"))
a.forEach(function(item){
if(item.hasAttribute('error')){
console.log(item.getAttribute('errDesc'))
}
})
JSFIDDLE
Note:querySelectorAll will select all the div which may be costly. You can actually add a class to error element. errorDesc can be as it is there.
Then you can do document.querySelectorAll("div.error") which will select dom only with error class
Related
How do I identify empty textboxes using jQuery? I would like to do it using selectors if it is at all possible. Also, I must select on id since in the real code where I want to use this I don't want to select all text inputs.
In my following two code examples the first one accurately displays the value typed into the textbox "txt2" by the user. The second example identifies that there is an empty textbox, but if you fill it in it still regards it as empty. Why is this?
Can this be done using just selectors?
This code reports the value in textbox "txt2":
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#cmdSubmit').click(function() {
alert($('[id=txt2]').val());
});
});
</script>
</head>
<body>
<form>
<input type="text" name="txt1" id="txt1" value="123" /><br />
<input type="text" name="txt2" id="txt2" value="" /><br />
<input type="text" name="txt3" id="txt3" value="abc" /><br />
<input type="submit" name="cmdSubmit" id='cmdSubmit' value="Send" /><br />
</form>
</body>
</html>
This code always reports textbox "txt2" as empty:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#cmdSubmit').click(function() {
if($('[id^=txt][value=""]').length > 0) {
if (!confirm("Are you sure you want to submit empty fields?")) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
}
});
});
</script>
</head>
<body>
<form>
<input type="text" name="txt1" id="txt1" value="123" /><br />
<input type="text" name="txt2" id="txt2" value="" /><br />
<input type="text" name="txt3" id="txt3" value="abc" /><br />
<input type="submit" name="cmdSubmit" id='cmdSubmit' value="Send" /><br />
</form>
</body>
</html>
Another way
$('input:text').filter(function() { return $(this).val() == ""; });
or
$('input:text').filter(function() { return this.value == ""; });
or
// WARNING: if input element does not have the "value" attribute or this attribute was removed from DOM then such selector WILL NOT WORK!
// For example input with type="file" and file does not selected.
// It's prefer to use "filter()" method.
// Thanks to #AaronLS
$('input:text[value=""]');
Working Demo
code from the demo
jQuery
$(function() {
$('#button').click(function() {
var emptyTextBoxes = $('input:text').filter(function() { return this.value == ""; });
var string = "The blank textbox ids are - \n";
emptyTextBoxes.each(function() {
string += "\n" + this.id;
});
alert(string);
});
});
You could also do it by defining your own selector:
$.extend($.expr[':'],{
textboxEmpty: function(el){
return $(el).val() === "";
}
});
And then access them like this:
alert($(':text:textboxEmpty').length); //alerts the number of text boxes in your selection
$(":text[value='']").doStuff();
?
By the way, your call of:
$('input[id=cmdSubmit]')...
can be greatly simplified and speeded up with:
$('#cmdSubmit')...
As mentioned in the top ranked post, the following works with the Sizzle engine.
$('input:text[value=""]');
In the comments, it was noted that removing the :text portion of the selector causes the selector to fail. I believe what's happening is that Sizzle actually relies on the browser's built in selector engine when possible. When :text is added to the selector, it becomes a non-standard CSS selector and thereby must needs be handled by Sizzle itself. This means that Sizzle checks the current value of the INPUT, instead of the "value" attribute specified in the source HTML.
So it's a clever way to check for empty text fields, but I think it relies on a behavior specific to the Sizzle engine (that of using the current value of the INPUT instead of the attribute defined in the source code). While Sizzle might return elements that match this selector, document.querySelectorAll will only return elements that have value="" in the HTML. Caveat emptor.
$("input[type=text][value=]")
After trying a lots of version I found this the most logical.
Note that text is case-sensitive.
There are a lot of answers here suggesting something like [value=""] but I don't think that actually works . . . or at least, the usage is not consistent. I'm trying to do something similar, selecting all inputs with ids beginning with a certain string that also have no entered value. I tried this:
$("input[id^='something'][value='']")
but it doesn't work. Nor does reversing them. See this fiddle. The only ways I found to correctly select all inputs with ids beginning with a string and without an entered value were
$("input[id^='something']").not("[value!='']")
and
$("input[id^='something']:not([value!=''])")
but obviously, the double negatives make that really confusing. Probably, Russ Cam's first answer (with a filtering function) is the most clear method.
Building on #James Wiseman's answer, I am using this:
$.extend($.expr[':'],{
blank: function(el){
return $(el).val().match(/^\s*$/);
}
});
This will catch inputs which contain only whitespace in addition to those which are 'truly' empty.
Example: http://jsfiddle.net/e9btdbyn/
I'd recommend:
$('input:text:not([value])')
This will select empty text inputs with an id that starts with "txt":
$(':text[value=""][id^=txt]')
Since creating an JQuery object for every comparison is not efficient, just use:
$.expr[":"].blank = function(element) {
return element.value == "";
};
Then you can do:
$(":input:blank")
Apologies if this question isn't layed out correctly (my first time using stack overflow).
I'm trying to validate if my inputs on a form are filled in when a user presses submit, it alerts the user when the inputs are empty but also when they are not, I'm not sure whats going wrong. Here is my Javascript:
<script>
function validation() {
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
Here is a link to an expanded part of the code for reference:https://pastebin.com/Dj5fA3gB
The general syntax for accessing a form element and element's value are:
document.forms[number].elements[number]
document.forms[number].elements[number].value
If you are using submitButton as in and you are calling validation on onSubmit of the form then you need to call event.preventDefault();
<!DOCTYPE html>
<html>
<body>
<form onsubmit="validation()" name="bookingForm">
First Name: <input type="text" name="id" value="Donald"><br>
Last Name: <input type="text" name="lname" value="Duck">
<input type="submit" value="Submit" />
</form>
<script>
function validation() {
event.preventDefault();
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
</body>
</html>
As suggested in my comment the most clean solution is to use the html attribute required by adding it to your inputs.
Looks something like this.
<form>
<input type="text" name="example" required>
<input type="submit" name="send">
</form>
The biggest advantage is that it works without any additional JS which is in my opinion always the prefered solution.
You didn't include return keyword in the form tag and adding unnecessary keyword "name" in the form tag.
<form onsubmit="return validation()" method="POST"
action="">
remove the "name" attribute from form tag and add action attribute.
Within the parenthesis in the action attribute, mention what happen if your validation success
Ex:(this code help you understand "action" attribute)
<form onsubmit="return productsvalidationform();" method="POST"
action="AddProductServlet">
when the form was successfully validated, I directed to AddProductServlet.(AddProductServlet is JSP servlet).
so that mention where do you need to redirect.
I need to show message "Please wait Processing" on click of Submit button using a hidden DOM element which contains the message and make it visible, but the message is not showing.
My html for the form and my validate function are given below.
<form name="siteSearchForm" method=post action="<%=request.getContextPath()%>/servlet/visibilityController" onsubmit="javascript:return validate();on_load()">
<td align="center" width="10%"><input type=submit name="siteSearchSubmit" value="SUBMIT" > <input type="RESET" name="clearTN" value="RESET"></td>
</form>
I tried the below code by calling on_load on form tag during onsubmit but it is not showing message
<head>
<script type="text/javascript">
function on_load(){
var y = document.getElementById("txtHiddenUname");
y.type= "text";
}
</script>
</head>
<body>
<input type="hidden" id="txtHiddenUname" value="invalid input" />
</body>
Becuase the return statement will exit the function call and nothing after it will run. You would need to add it BEFORE the return.
onsubmit="on_load(); return validate();"
or you can do
onsubmit="return validate() && on_load();"
but your on_load function needs to return true.
function on_load(){ return true; }
Also why are you using an input to display a message? Seems like you should be using a paragraph with display none/block. javascript: is not needed in event handlers, and on_load seems like it should be called on window load, not a form submission.
Also add the following line :
y.style.display = "block";
I'm making a chrome extension, and so far I'm just testing some things. The HTML for the extension is this:
<!doctype html>
<html>
<head>
<title>Title</title>
<script src="processform.js"></script>
</head>
<body>
<form name="myform" onSubmit="ExampleJS()">
First name: <input type="text" id="fname" name="firstname" /><br />
Last name: <input type="text" id="lname" name="lastname" /><br />
<input name="Submit" type="submit" value="Update" />
</form>
</body>
</html>
The processform.js file is this:
function ExampleJS(){
var jFirst = document.getElementById("fname").value;
var jLast = document.getElementById("lname").value;
alert("Your name is: " + jFirst + " " + jLast);
}
When I press the submit button the alert doesn't appear.
You cannot use inline code in a Chrome extension due to its Content Security Policy, and setting onsubmit in the element counts as inline.
A jQuery-based solution (you will need to include jQuery with the extension and add it to the page, but there's no harm in that):
// processform.js
$(document).ready(function(){
// Bind from JS, not inline
$("form").submit(ExampleJS);
});
A pure JavaScript solution would be:
// processform.js
document.addEventListener('DOMContentLoaded', function(){
// Bind from JS, not inline
document.forms["myform"].addEventListener('submit', ExampleJS);
});
Please put the following code -
$(document).ready(function(){
$("form").submit(ExampleIS);});
This should work.
I have some javascipt code here that validates a user form. When the user inputs the correct answer it tells them and gives them the link to the next question. At least, that's what it is supposed to do. When i click the form it reloads the page but it should not because i added return false.
the div tra holds 35
and the div usermsg is the user inputted value.
<script>
$("#submit").click(function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6<>rightanswer)
{
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else
{
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
</script>
Any ideas why this is not working?
It should be
if (clientmsg6 != rightanswer)
not
if (clientmsg6<>rightanswer)
To prevent a form submission, you need to return false on the form itself instead of on the submit button. Your code should become:
HTML
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="submit" value="Submit" />
</form>
JS (please note the line where you have clientmsg6, you have a syntax error)
$("#myform").on('submit', function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6 != rightanswer) { //This line was also wrong, should be != instead of <>
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else {
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
Alternatively, you can keep your existing code by changing your submit button to be just a plain old button, but you will lose the extra functionality of the user being able to hit the enter key and performing the same action.
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="button" value="Submit" />
</form>
Instead of using .html(), try using .text()
if #submit is a link tag otherwise use the form ID and the submit event
$("#submit").click(function(e){
e.preventDefault()
...
...
...
});
You need to attach handlers once the document has finished loading.
Wrap your script in the following
<script>
$(function() {
// script
});
</script>