I am newbie in javascript. I have two textboxes
<asp:TextBox id="txtbox1" class="txt" runat="server" />
<asp:TextBox id="txtbox2" class="txt" runat="server" />
I am using javascript validation here so that user can't enter NULL value. My javascript code is fine. On button I am using this code.
<asp:Button ID="btn_add" runat="server" OnClientClick="return validate();" OnClick="btn_add_Click" Text="Submit" />
Now, the problem is that when user leaves textbox blank and click on button, error message is shown and after that user corrects his mistakes and again click on the button then button is not working. Nothing happens.
Edit: My javascript code
<script type="text/javascript">
function validate()
{
var error = 0,value,a,q,i;
value = document.getElementsByClassName("txt");
for (i = 0; i < value.length; i++)
{
if (value[i].textContent == '')
{
document.getElementById("errmsg").innerHTML = "TextBox can't be blank";
error = 1;
break;
}
}
if (error == 0)
{ return true }
else { return false}
}
</script>`
I was thrown by your error variable, I would have expected that to fail. The fix is pretty simple. You are using an input and textContent is not a valid attribute as the text is not nested inside the tag (unlike div, p, textarea etc.).
Inputs contain their content in attributes, when a user modifies an input the value is changed and there is the clue. You must access the inputs value.
<script type="text/javascript">
function validate()
{
var error = 0,value,a,q,i;
value = document.getElementsByClassName("txt");
for (i = 0; i < value.length; i++)
{
if (value[i].value == '')
{
document.getElementById("errmsg").innerHTML = "TextBox can't be blank";
error = 1;
break;
}
}
if (error == 0)
{ return true }
else { return false}
}
</script>`
<form action="form_action.php" method="get">
<div id="errmsg"></div>
<div>
<label>First name</label>
<input class="txt" type="text" name="fname" value="" />
<input type="submit" onclick="return validate()" value="Submit" />
</div>
</form>
If you were to bring this piece of code on a bit I would opt for not using the inline function assignment and as mentioned in other comments, use a required flag, then on DOMready check the form for required fields.
Then you can deal with them as you wish, onSubmit, onChange. It will provide you with a bit more flexibility.
ps. You have got to tell me what this does... var error = 1,value,a,q,i
I soved this when user moved out of text box.I through the error.
<form name="forms.sample" novalidate>
<md-input-container class="md-block" flex-gt-sm>
<label>Name:</label>
<input ng-focus="focus=true" ng-blur="focus=false" style="width:400px;" class="form-control" name="Name" type="text" data-ng-model="Name" ng-pattern="SomePattern" required placeholder="enter the Name here" />
<div ng-messages for="forms.sample.Name.$error" ng-if="!focus">
<div ng-if='forms.sample.Name.$touched' ng-message="required">This is required.</div>
<div ng-if='forms.sample.Name.$touched' ng-message="pattern">Enter a valid domain name</div>
</div>
</md-input-container>
</form>
Related
I have a form which asks user to give some input values. For some initial inputs i am doing custom validation using javascript. At the end of form one field is validated using "html required attribute". But when user clicks on submit button, input box which have required attribute shows message first instead of giving chance to previous ones i.e. not following order of error display. Below i added code and image , instead of showing that name is empty it directly jumps to location input box. This just confuses the end user. Why this problem occurs and how to resolve it?
<html>
<head>
<script>
function validate(){
var name = document.forms['something']['name'].value.replace(/ /g,"");
if(name.length<6){
document.getElementById('message').innerHTML="Enter correct name";
return false;
}
}
</script>
</head>
<body>
<form name="something" action="somewhere" method="post" onsubmit="return validate()">
<div id="message"></div>
Enter Name : <input type="text" name="name" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
</body>
</html>
This is probably just the HTML5 form validation triggered because of the required attribute in the location input.
So one option is to also set the required attribute on the name. And or disable the HTML5 validation with a novalidate attribute. See here for more information: https://stackoverflow.com/a/3094185/2008111
Update
So the simpler way is to add the required attribute also on the name. Just in case someone submits the form before he/she entered anything. Cause HTML5 validation will be triggered before anything else. The other way around this is to remove the required attribute everywhere. So something like this. Now the javascript validation will be triggered as soon as the name input looses focus say onblur.
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
var messageElement = document.getElementById('message');
var string = nameElement.value.replace(/ /g,"");
if(string.length<6){
messageElement.innerHTML="Enter correct name";
} else {
messageElement.innerHTML="";
}
};
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
Now the above works fine I guess. But imagine you might need that function on multiple places which is kind of the same except of the element to observe and the error message. Of course there can be more like where to display the message etc. This is just to give you an idea how you could set up for more scenarios using the same function:
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
validate(nameElement, "Enter correct name");
};
function validate(element, errorMessage) {
var messageElement = document.getElementById('message');
var string = element.value.replace(/ /g,"");
if(string.length < 6){
messageElement.innerHTML= errorMessage;
} else {
messageElement.innerHTML="";
}
}
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
I am new to web development and I am trying to create a simple form validation using javascript/jquery.
I drafted a simple form very similar to what I have that looks like this:
<form>
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<button type="submit" onclick='return validateSubmit();'>Save</button>
</form>
What I want to happen is when the user clicks the submit button, it will check every input box if it contains a valid number (price) before it allows the submit, if one or more of the input box is invalid, it will be highlighted with an alert error "Invalid inputs on highlighted textboxes" or something like that. After couple of searches this is what I have in my script:
var validateSubmit = function () {
var inputs = $('.price');
var errors = 'False';
for (var i = 0; i < inputs.length; i++) {
if (isNaN(inputs[i].value)) {
$('.price')[i].focus();
}
errors = 'True';
}
if (errors == 'True') {
alert('Errors are highlighted!');
return false;
}
return true;
};
I understand what is wrong with what Ive done but I dont know how to fix it.
I know that we can only focus() 1 element at a time but I wanted to have some effect that it highlights the inputboxes with invalid characters.
Please tell me how to do it or if there's a better approach can you show me some examples. I saw bootstrap has some css effects for this focus but I dont know how to implement it. Thank you!
You can add a class to the inputs with bad values. The class can add a border for example.
var validateSubmit = function () {
var inputs = $('.price');
var errors = 'False';
for (var i = 0; i < inputs.length; i++) {
if (isNaN(inputs[i].value)) {
$(inputs[i]).addClass('error');
errors = 'True';
} else {
$(inputs[i]).removeClass('error');
}
}
if (errors == 'True') {
alert('Errors are highlighted!');
return false;
}
return true;
};
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<button type="submit" onclick='return validateSubmit();'>Save</button>
</form>
First, I think you should clean up your HTML. For example, it is always a good idea to give an id attribute to your form tags to reference them. Also, someone correct me if I am wrong, you won't be submitting any values without giving a name attribute to your input fields.
<form id="price-form" action="" method="get">
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<button type="submit">Save</button>
</form>
Now, since you are using jQuery, why not utilize its methods such as on() and .each() ?
$(function() {
$('#price-form').on('submit', function(e) {
// this variable acts as a boolean, so might as well treat it as a boolean
var errors = false;
// remove previous errors
$('.price').removeClass('error');
// check each input for errors
$('.price').each(function() {
if (isNaN(this.value)) {
$(this).addClass('error');
errors = true;
}
});
// alert if there are any errors
if (errors) {
alert('Errors are highlighted!');
e.preventDefault(); // stop submission
}
});
});
In your CSS, you could do
.error {
border: 2px solid #a00;
}
So I guess for context, here is an example from the parsley.js documentation.
<form id="demo-form" data-parsley-validate>
<div class="first">
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" data-parsley-range="[4, 20]" data-parsley-group="block1" />
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" data-parsley-range="[4, 20]" data-parsley-group="block1" />
</div>
<hr></hr>
<div class="second">
<label for="fullname">Fullname:</label>
<input type="text" name="fullname" data-parsley-range="[8, 40]" data-parsley-group="block2" />
</div>
<div class="invalid-form-error-message"></div>
<input type="submit" class="btn btn-default validate" />
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#demo-form').parsley().subscribe('parsley:form:validate', function (formInstance) {
// if one of these blocks is not failing do not prevent submission
// we use here group validation with option force (validate even non required fields)
if (formInstance.isValid('block1', true) || formInstance.isValid('block2', true)) {
$('.invalid-form-error-message').html('');
return;
}
// else stop form submission
formInstance.submitEvent.preventDefault();
// and display a gentle message
$('.invalid-form-error-message')
.html("You must correctly fill the fields of at least one of these two blocks!")
.addClass("filled");
return;
});
});
</script>
Let's say I have a hidden div called "checkmark". How would I show this div upon validation of the firstname field?
I should also clarify that I have read the documentation, but still don't understand how to accomplish what I'm trying to do here, so posting a link to the documentation is not really going to be helpful unless you are using it in your answer.
You should use Parsley's Events. Since you want to display or hide something based on a field validation, you should use parsley:field:success and parsley:field:error.
Working example (with jsfiddle):
<form id="demo-form" data-parsley-validate>
<div class="first">
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" data-parsley-range="[4, 20]" data-parsley-group="block1" required />
<div class="hidden" id="checkmark">This message will be shown when the firstname is not valid </div>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" data-parsley-range="[4, 20]" data-parsley-group="block1" />
</div>
<hr></hr>
<div class="second">
<label for="fullname">Fullname:</label>
<input type="text" name="fullname" data-parsley-range="[8, 40]" data-parsley-group="block2" />
</div>
<div class="invalid-form-error-message"></div>
<input type="submit" class="btn btn-default validate" />
</form>
<script>
$(document).ready(function () {
$('#demo-form').parsley().subscribe('parsley:form:validate', function (formInstance) {
// if one of these blocks is not failing do not prevent submission
// we use here group validation with option force (validate even non required fields)
if (formInstance.isValid('block1', true) || formInstance.isValid('block2', true)) {
$('.invalid-form-error-message').html('');
return;
}
// else stop form submission
formInstance.submitEvent.preventDefault();
// and display a gentle message
$('.invalid-form-error-message')
.html("You must correctly fill the fields of at least one of these two blocks!")
.addClass("filled");
return;
});
$.listen('parsley:field:error', function(ParsleyField) {
if(ParsleyField.$element.attr('name') === 'firstname') {
$("div#checkmark").addClass('show').removeClass('hidden');
}
});
$.listen('parsley:field:success', function(ParsleyField) {
if(ParsleyField.$element.attr('name') === 'firstname') {
$("div#checkmark").addClass('hidden').removeClass('show');
}
});
});
</script>
And here's what I did:
Added a div with ìd=checkmark after the firstname field (with a hidden class, since you're using Bootstrap).
Added this block of javascript:
$.listen('parsley:field:error', function(ParsleyField) {
if(ParsleyField.$element.attr('name') === 'firstname') {
$("div#checkmark").addClass('show').removeClass('hidden');
}
});
$.listen('parsley:field:success', function(ParsleyField) {
if(ParsleyField.$element.attr('name') === 'firstname') {
$("div#checkmark").addClass('hidden').removeClass('show');
}
});
This code will listen to the validation of every input validated by Parsley. This means that when the field lastname fails, the code inside $.listen('parsley:field:error', function(ParsleyField) { will be executed. This is why I used an if to check if the attr name is firstname.
Then you show or hide the div based on the validation result.
Added required to the field, so the message is displayed when you click on the button.
I am trying to get pop-up block when there is no text/blank space. It is working fine in Firefox, Chrome &Safari.
Please check below code in my JavaScript file-:
function submitQuestion(URL,docId,errorMessage)
{
var question = $('textField').value;
if(!question.blank())
{
var submitForm = $("question-form");
submitForm.action = URL+"docId="+docId+"&question="+encodeURIComponent(question);
//alert(submitForm.action);
submitForm.submit();
}
else
{
alert(errorMessage);
return false;
}
}
Above function works fine in Firefox,Safari &Chrome as when there is nothing in textbox (i.e. empty/blank) then it goes to else &prompt errorMessage as a pop-up but in IE, it doesn't go to else &errorMessage pop-up never come.
Please check below code for my forntend form-:
<form method="POST" id="question-form" onsubmit="return submitQuestion('https://localhost/question-post!input.jspa?','ABC12','Enter your question!');">
<span class="fieldwrap">
<input type="text" placeholder="Ask customers about this document" value="" maxlength="255" autocomplete="off" class="questionInputField" id="textField">
</span>
<div class="clear"></div>
<div id="question-submit" class="widget-div clearfix">
<input type="submit" value="Submit question to the portal" class="questionSubmitFormButton">
</div>
</div>
</form>
What happened here in IE is it will take placeholder as a value for text field when we didn't provide any i.e. When we keep text field empty or blank then it will take placeholder as a text field value &instead of giving pop-up alert, it goes to if loop which should not be a case.
To access the value of the textField using jQuery, you should use val() instead of value.
var question = $('textField').val();
if (question != '') {
//
}
else {
//
}
Below is a working example:
<!DOCTYPE html>
<head>
<title>EXAMPLE</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function submitQuestion(URL, docId, errorMessage) {
var question = $('#textField').val();
if (question.trim() != "") {
var submitForm = $("#question-form");
submitForm.attr("action", URL + "docId=" + docId + "&question=" + encodeURIComponent(question));
return true;
}
else {
alert(errorMessage);
return false;
}
}
</script>
</head>
<body>
<form method="POST" id="question-form" onsubmit="return submitQuestion('https://localhost/question-post!input.jspa?','ABC12','Enter your question!');">
<span class="fieldwrap">
<input type="text" placeholder="Ask customers about this document" value="" maxlength="255" autocomplete="off" class="questionInputField" id="textField">
</span>
<div class="clear"></div>
<div id="question-submit" class="widget-div clearfix">
<input type="submit" value="Submit question to the portal" class="questionSubmitFormButton">
</div>
</form>
</body>
I'm trying to validate a form, but doesn't work :\ , When I submit the form goes to mail.php even if the required fields are missing, but I set onsubmit to validate() so it should check, but doesn't work. What's the problem with my code? I can't find it.
HTML:
<form action="mail.php" onsubmit="return validate()" method="post" class="contact-form" id="contactForm">
<div id="errors"></div>
<label for="author">Name:</label><br/><br/>
<input type="text" name="author" id="message" /><br/><br/>
<label for="author">Message:</label><br/><br/>
<textarea name="message" id="message"></textarea><br/><br/>
<input type="submit" class="button" value="Send Message"/>
</form>
Javascript:
<script type="text/javascript">
function error(message){
return "<p class=\"error\">"+message+"</p>";
}
function validate(){
var form = document.getElementById("contactForm");
var author = document.getElementById("author");
var message = document.getElementById("messsage");
var errors = document.getElementById("errors");
alert(author.value);
if(message.value == '' || author.value == ''){
errors.innerHTML = error("Please fill in all fields.");
return false;
} else {
return true;
}
}
</script>
id=author on your first input element.
Also check out jQuery it will save you time in the long run
You have two elements with the id message and none with author.
The Markup Validator would have picked this up for you.
var message = document.getElementById("messsage");
message has an extra "s".
<input type="text" name="author" id="message" />
You need to change "message" to "author"
This is wrong:
<input type="text" name="author" id="message" />
Need to set name and id to the same values (you're using id="message" for the next field, so there's a clash.
Also both your label tags have for="author"; the second one is wrong.
I guess your problem here is too much copy+paste. ;)