I am using Jquery validate to provide feedback to a user and provide them updates on the validity of the details they enter in the form. But I am having trouble customising the behaviour Jquery validate creates.
I have a simple form like this:
<form id="form1">
<label for="input1" />
<input name="input1" />
<input type="submit" />
</form>
When the user enters invalid information I want Jquery validate to output something like this:
<form id="form1">
<label for="input1" />
<input name="input1" class="error"/><span class="errorIcon">Error</span>
<p class="errorText">Error message</p>
<input type="submit" />
</form>
When the user fills out the field with valid information I want Jquery validate to output:
<form id="form1">
<label for="input1" />
<input name="input1" /><span class="successIcon">Success</span>
<input type="submit" />
</form>
I have set up the required rules and custom validation messages so they fire fine but I am having trouble getting the behaviour described above.
I have this currently:
$('#form1').validate({
showErrors: function(errorMap, errorList) {
if (errorList < 1 ) {
$('span.errorIcon').remove();
$('p.errorText').remove();
$('input.error').removeClass('error');
$('select.error').removeClass('error');
return;
}
$.each(errorList, function(index, error) {
if ($(error.element).siblings('.errorText').length === 0 && $(error.element).siblings('.errorIcon').length === 0) {
$(error.element).next('p.errorText').remove();
$(error.element).addClass('error');
$(error.element).after(
$('<p/>')
.addClass('errorText')
.append(error.message)
);
$(error.element).after(
$('<span>There is an issue with this field</span>')
.addClass('errorIcon')
);
}
});
},
//rules and messages defined here
);
So the above doesn't achieve what I want need currently and it also feels like I might be over complicating this issue. I am fairly inexperienced with javascript and Jquery. Any guidance in getting this sorted would be appreciated.
Cheers
EDIT:
Here is a link to a jsfiddle: http://jsfiddle.net/WJ9Vt/4/ with the sample form.
Could also post you css file, or do a jsfiddle on it ? Because you errorIcon is probably not shown because <span> will not display something as long as it has no content or you set display:block; and a special height and width.
Related
I am trying to get an event handler on an HTML form. I am just trying t get the simplest thing working, but I just cannot see what I am missing.
It is part of a wider project, but since I cannot get this bit working I have reduced it down the most very basic elements 1 text field and a button to try and see what it is I am missing.
All I want to do is get some text entered and flash up message in a different area on the screen.
The user enters text into the input field (id=owner).
The plan is that when the button (id="entry") is pressed the event handler (function "entry") in the entry.js file should cause a message to display.
I don't want the form to take me to a different place it needs to stay where it is
I just want some form of text to go in the: <div id="feedback" section.
When I can get it working: I intend the create the text from the various text fields that get entered.
I Know that this is beginner stuff & I know that I have reduced this down such that it barely worth thought but I would welcome any input please & thank you.
HTML code is:
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
<script src="entry.js"></script>
Code for entry.js is:
function entry() {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementByID('feedback');
elMsg.textContent = 'hello';
}
var elEntry = document.getElementById('entry');
elEntry.onsubmit=entry;
I have tried:
Adding in a prevent default:
window.event.preventDefault();
doing this through an event Listener:
elEntry.addEventListener('submit',entry,false);
using innerHTML to post the message:
elMsg.innerHTML = "
At present all that happens is that the pushing submit reloads the page - with no indication of any text being posted anywhere.
One issue is that you have a typo, where getElementById capitalized the D at the end.
Another is that preventDefault() should be called on the form element, not the input.
Here's a working example that corrects those two mistakes.
function entry(event) {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
event.preventDefault();
}
var entryForm = document.getElementById('entry').form;
entryForm.onsubmit = entry;
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
I also defined a event parameter for the handler. I don't remember is window.event was ever standardized (it probably was), but I'd prefer the parameter.
Be sure to keep your developer console open so that you can get information on errors that may result from typos.
var elEntry = document.getElementById('entry');
elEntry.addEventListener("click", function(e) {
e.preventDefault();
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
});
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
I've tried, I've researched, and I still can't figure out how to validate this form using jQuery. I've even tried to check out the jQuery API and I had no luck with it. This shouldn't be as hard as it seems. There are a few id's that i'm not using yet because I want to get what I have so far working before I continue. The best I could find for validating emails is just straight up JavaScript. Here's my code.
$(document).ready(function(){
$("#sendForm").click(function(){
var validForm=true; //set valid flag to true, assume form is valid
//validate customer name field. Field is required
if($("#custName").val()) {
$("#custNameError").html(""); //field value is good, remove any error messages
} else {
$("#custNameError").html("Please enter your name.");
validForm = false;
}
//validate customer phone number. Field is required, must be numeric, must be 10 characters
var inPhone = $("#custPhone").val(); //get the input value of the Phone field
$("#custPhoneError").html(""); //set error message back to empty, assume field is valid
if(!inPhone) {
$("#custPhoneError").html("Please enter your phone number.");
validForm = false;
} else {
//if( !$.isNumeric(inPhone) || Math.round(inPhone) != inPhone ) //if the value is NOT numerice OR not an integer. Rounding technique
if( !$.isNumeric(inPhone) || (inPhone % 1 != 0) ) //if the value is NOT numerice OR not an integer. Modulus technique
{
$("#custPhoneError").html("Phone number must be a number.");
validForm = false;
} else {
if(inPhone.length != 10) {
$("#custPhoneError").html("Phone number must have 10 numbers");
validForm = false;
}
}
}
//ALL VALIDATIONS ARE COMPLETE. If all of the fields are valid we can submit the form. Otherwise display the errors
if(validForm) {
//all values are valid, form is good, submit the form
alert("Valid form will be submitted");
//$("#applicationForm").submit(); //SUBMIT the form to the server
} else {
//form has at least one invalid field
//display form and associated error messages
alert("Invalid form. Display form and error messages");
}
}); //end sendform.click
}); //end .ready
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
label {
width:150px;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>
<h3>Form Validation Project - Complaint Form</h3>
<form id="form1" name="form1" method="post" action="">
<p>Please enter the following information in order to process your concerns.</p>
<p>
<label for="custName">Name:</label>
<input type="text" name="custName" id="custName" />
<span id="custNameError" class="errorMsg"></span>
</p>
<p>
<label for="custPhone">Phone Number: </label>
<input type="text" name="custPhone" id="custPhone" />
<span id="custPhoneError" class="errorMsg"></span>
</p>
<p>
<label for = "email">Email:</label>
<input type = "text" name = "emailAdd" id = "emailAdd" />
<span id = "emailError" class = "emailError"></span>
</p>
<p>Please Select Product Group:</p>
<p>
<label>
<input type="radio" name="custProducts" value="books" id="custProducts_0" />
Books
</label>
<br />
<label>
<input type="radio" name="custProducts" value="movies" id="custProducts_1" />
Movies
</label>
<br />
<label>
<input type="radio" name="custProducts" value="electronics" id="custProducts_2" />
Consumer Electronics
</label>
<br />
<label>
<input type="radio" name="custProducts" value="computer" id="custProducts_3" />
Computer
</label>
<br />
</p>
<p>Description of problem: (Limit 200 characters)</p>
<p>
<label for="custComplaint"></label>
<textarea name="custComplaint" id="custComplaint" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="button" id="button" value="File Complaint" />
<input type="reset" name="button2" id="button2" value="Reset" />
</p>
</form>
<p> </p>
$("#button").click(function(e){
e.preventDefault(); // you need to stop the initial event to have a chance to validate
var validForm=true;
// etc...
You can use jquery.validate.js to validate your forms , it will overcome all your manual efforts to create the validation rules also it is providing the various predefined rules like required,email, minlength and maxlength, etc. So, it will be easier for you to achieve what you need very easily.
https://jqueryvalidation.org/
I have a simple jquery form validation and submission package - see if that's of any help - it's easy to install and you can customise quite a few things: https://github.com/sebastiansulinski/ssd-form
Just to get you started, your submit control in the html has id "button", so you should use $('#button').click, not $('#sendForm').click.
Also, if you want to stay on the page (like to do validations, show errors, etc), you have to prevent the form from submitting automatically when the button is clicked. There are lots of ways to do this, but the easiest way is to just change your button type from submit to button. Ie, replace this:
<input type="submit" name="button" id="button" value="File Complaint" />
with this:
<input type="button" name="button" id="button" value="File Complaint" />
------
That should get you started, at least your code will run, you can use console.log to debug, etc. Good luck.
UPDATE
I should add that if you take my advice, the form will never submit on it's own - that is good if some validation fails and you want to stay on the page and give some error feedback to the user.
When you do want the form to submit, you have to make it happen yourself. Again, there are lots of ways to do this, but the simplest one is probably:
$('#form1').submit();
If you have a <form> and a <button type='submit'> and you click on the submit button, it will do the default form validation, such as checking whether an <input> is required or not. It would normally say Please fill out this field.
However, if I programmatically submit the form through $("form").submit() for example, it would submit it without performing any checks.
Is there a simpler way to perform the default form validations using native JavaScript? There seems to be only checkValidity() on the form element which return true or false. And if I call the same native function on the input itself, it doesn't really do anything.
Here is a demo code of what I mean:
http://jsfiddle.net/totszwai/yb7arnda/
For those still struggling:
You can use the Constraint validation API - https://developer.mozilla.org/en-US/docs/Web/API/Constraint_validation
<div id="app">
<form>
<input type="text" required placeholder="name">
<input type="text" required placeholder="email">
</form>
<button id="save">Submit</button>
</div>
const form = document.querySelector("form");
document.getElementById("save").addEventListener("click", e => {
e.preventDefault();
if (form.checkValidity()) {
console.log("submit ...");
} else {
form.reportValidity();
}
});
Check out and play here: https://stackblitz.com/edit/js-t1vhdn?file=index.js
I hope it helps or gives you ideas. :)
I think this might be the answer you are looking for :
JavaScript :
document
.getElementById('button')
.addEventListener("click",function(e) {
document.getElementById('myForm').validate();
});
HTML :
<form id="myForm" >
First name: <input type="text" name="FirstName" required><br>
Last name: <input type="text" name="LastName" required><br>
<button id="button">Trigger Form Submit</button>
</form>
Demo : http://jsfiddle.net/2ahLcd4d/2/
I have a form on my page and want to be able to submit the text box value (partnumber) as a query string in a hyperlink without submitting the form itself ? Is this possible ?
I have done some research and have tried document.getElementById("partnumber").value but am getting the error "Object Required". Code Below.
<form id="form3" name="form3" method="post" action="formpost?rmaid=<%=rmaid%>">
<input name="partnumber" type="text" id="partnumber" size="10" />
<span class="style11">Suggest Link</span>
<input name="invoice" type="text" id="invoice" size="15" />
</form>
I'll set the new page to open in a pop up window and list a series of values in the database but then I need the value selected to come back into the invoice field on the original page. I believe this can be done with JavaScript but I am new to this, can anyone help ?
For those Looking to pass values back I have found this snippet that works...
Put this in the child window
<script language="javascript">
function changeParent() {
window.opener.document.getElementById('Invoice').value="Value changed..";
window.close();
}
</script>
<form>
<input type=button onclick="javascript:changeParent()" value="Change opener's textbox's value..">
</form>
For the input field you should add an OnChange to it. This event should call a function which will then set your link's value.
You can see an example of this here (it uses a button press though and not an input OnChange Event): http://www.java2s.com/Code/JavaScript/HTML/ChangeURLandtextofahyperlink.htm
Edit: Added a Stack Snippet illustrating the solution.
function SetSuggestLink() {
var suggest = document.getElementById('partnumber').value;
document.getElementById('innerSpan').innerHTML =
"Suggest Link: suggest.asp?partnumber=" + suggest;
document.getElementById('QueryLink').href =
"suggest.asp?partnumber=" + suggest;
}
.style11 {
color:black;
}
.style2 {
text-decoration:none;
}
<form id="form3" name="form3" method="post" action="formpost?rmaid=SomeValue">
<input name="partnumber" type="text" id="partnumber" size="10"
OnChange="SetSuggestLink()" /> </br>
<a id="QueryLink" class="style2" href="#">
<span id="innerSpan" class="style11">Suggest Link</span>
</a></br>
<input name="invoice" type="text" id="invoice" size="15" />
</form>
I just a got a requirement to disable the send button in the form until the users enter his data.Can any one guide me?
thanks
Have the button initially disabled by having such HTML
<input type="submit" id="btnSubmit" disabled="disabled" value="Send" />
Then in the blur event of your form elements check if user entered all required data and when this happens, enable the button using such code:
document.getElementById("btnSubmit").disabled = false;
form action="javascript:aNameForAnAjaxSendPostFunction"
function aNameForAnAjaxSendPostFunction()
{
if ((document.getElementById('your field').value.strlen>0))
{
<< SEND REQUEST >>
}
}
Normally, I would code it for you, but I'm in a hurry, and you do have to learn how to search for yourself, so here's a hint:
addEventListener(), and you can check the length of the data within an input by calling document.body.getElementById('yourInput').length, and then you can change the button.disabled property to either true (make the default value false in the source code). All you need to do for yourself is find out how to use addEventListener
A simple way of doing what you want using JQuery:
(this works if you have only input texts)
HTML:
<form method='POST' action=''>
<input type='text' name='name' />
<input type='text' name='phone' />
<input type='text' name='email' />
<button type='submit' disabled='disabled'>Send</button>
</form>
Javascript:
$(function() {
$("input").change(function() {
if($("input[value='']").length == 0) {
$("button").removeAttr("disabled");
} else {
//disable again if a field is cleared
$("button").attr("disabled",true);
alert("Please fill all fields");
$("input[value='']").eq(0).focus();
}
});
});