Validity and error messages from jquery validator [duplicate] - javascript

Using the jQuery Validation plug-in for the following form:
<form id="information" method="post" action="#">
<fieldset>
<legend>Please enter your contact details</legend>
<span id="invalid-name"></span>
<div id="id">
<label for="name">Name: (*)</label>
<input type="text" id="name" class="details" name="name" maxlength="50" />
</div>
<span id="invalid-email"></span>
<div id="id">
<label for="email">Email: (*)</label>
<input type="text" id="email" class="details" name="email" maxlength="50" />
</div>
</fieldset>
<fieldset>
<legend>Write your question here (*)</legend>
<span id="invalid-text"></span>
<textarea id="text" name="text" rows="8" cols="8"></textarea>
<div id="submission">
<input type="submit" id="submit" value="Send" name="send"/>
</div>
<p class="required">(*) Required</p>
</fieldset>
</form>
How can I place the errors inside the span tags? (#invalid-name, #invalid-email, #invalid-text)
I read the documentation about error placement but I did not get how it works.
Is it possible to handle each single error and place it in the specified element?
Thank you

You can also manually add error labels in places you need them. In my particular case I had a more complex form with checkbox lists etc. where an insert or insert after would break the layout. Rather than doing this you can take advantage of the fact that the validation script will evaluate if an existing label tag exists for the specified field and use it.
Consider:
<div id="id">
<label for="name">Name: (*)</label>
<input type="text" id="name" class="details" name="name" maxlength="50" />
</div>
Now add the following line:
<label for="name" class="error" generated="true"></label>
which is standard error label:
<div id="id">
<label for="name">Name: (*)</label>
<input type="text" id="name" class="details" name="name" maxlength="50" />
</div>
<div id="id-error">
<label for="name" class="error" generated="true"></label>
<div>
jQuery will use this label rather than generating a new one. Sorry I could not find any official documentation on this but found other posts that came across this behaviour.

This is a basic structure, you can use whatever selector you would like in the method. You have the error element and the element that was invalid.
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo(element.prev());
}
});
Or to target the ID, you could do
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo('#invalid-' + element.attr('id'));
}
});
Not tested, but should work.

I found that using .insertAfter rather than .appendTo works:
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.insertAfter('#invalid-' + element.attr('id'));
}
});

I'm using the metadata extension with the validator.. (note, I'm setting it to use the data-meta attribute on the markup...)
<input ... data=meta='{
errorLabel: "#someotherid"
,validate: {
name:true
}
}' >
then in code...
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo($(
$(element).metadata().errorLabel
));
}
});
I've been using the metadata for a lot of similar functionality, which works rather nicely... note, I used the single ticks (apostrophes) around the meta data, this way you can use a JSON serializer server-side to inject into that portion of the tag (which should use double-quotes around strings)... a literal apos may be an issue though, (replace "'" with "\x27" in the string).

Related

jQuery appending HTML elements out of order

I'll start this off by saying I use JS very infrequently, so this is likely a simple mistake. I came across the need to generate a form on the spot when a button is pressed. After some searching, I decided on using the append function from jQuery. Here is the code I wrote:
function replyToComment(commentId) {
var element = document.getElementById("reply-form");
if (element != null) {
element.remove()
}
const html = `
<div id="reply-form">
<label for="comment-form">Comment:</label>
<form method="post" id="comment-form" style="padding-bottom: 10px;">
<input type="hidden" name="csrfmiddlewaretoken" value="${csrf_token}"
<div class="form-group">
<div>
<textarea type="text" name="body" maxlength="1500" class="textarea form-control" cols="40" rows="10"></textarea>
</div>
</div>
<input type="text" name="comment-send" style="display:none;" readonly>
<input type="text" name="comment_id" value=${commentId} style="display:none;" readonly>
<button type="submit" class="btn btn-success">Send</button>
</form>
</div>`
$(`#${commentId}`).append(html)
}
When inspecting the final result, the argument passed into the append function is out of order:
I am not sure if the image will load in properly, but if it doesnt, its mostly irrelevant. Am I misusing the append function? Is there another way to do this that will handle the data I want to pass in properly?
It appears that you're neglecting to close one of your input tags.
You have:
<input type="hidden" name="csrfmiddlewaretoken" value="${csrf_token}"
This should be:
<input type="hidden" name="csrfmiddlewaretoken" value="${csrf_token}" />

How to enable autocomplete in <input > with <label ><input ><button >

I am not web developer, but I have a task to add autocomplete function for an input box. Please treat me as a very beginner.
<div>
<label id="email_label" for="send_email" style="padding-right:5px">
Send Email:
</label>
<input id="send_email" type="text" placeholder="e.g. xx.yy#zz.com" />
<button id="ack" onclick="requestAck()">
Request
</button>
</div>
requestAck() is a javascript function sending a email to address given by user (i.e. address in <input >). I am trying to add a flag in <input autocomplete="on" ...>, but it doesn't work. Perhaps because it's not in a <form></form> environment.
Could you help me to modify this code adding autocomplete (from cache) without changing other functions. Many thanks!
Try setting the property name="email" on the input tag, without that set the browser doesn't know what's supposed to autocomplete the field with :)
protip: I warmly suggest you to set the type of the input to email with type="email" instead of text, it's not required but it will help validating the input!
check this code:
<div>
<label id="email_label" for="send_email" style="paddingright:5px">Send Email:</label>
<input id="send_email" type="email" name="email" placeholder="e.g. xx.yy#zz.com" />
<button id="ack" onclick="requestAck()">Request</button>
</div>
EDIT: Final solution discussed in comments
<form onsubmit="submitForm(event)">
<label id="email_label" for="send_email" style="padding-right:5px">Send Email:</label>
<input id="send_email" type="email" autocomplete="email" name="email" placeholder="e.g. xx.yy#zz.com" />
<button id="ack" type="submit">Request</button>
</form>
<script>
function submitForm(e) {
e.preventDefault(); // this prevents the page from reloading
requestAck();
}
//dummy function so the javascript won't crash:
function requestAck() {}
</script>
Working example: https://codesandbox.io/s/focused-cray-ubkw4

jQuery: Validating fields before submitting (multistep form)

I have a form which consists of 2 steps. What I'd like to do is validate each step before continuing to the next; the user should not be able to get to step 2 of step 1's fields are invalid.
js fiddle: http://jsfiddle.net/Egyhc/
Below you can find the simplified version of the form:
<form>
<div id="step1" style="display: block;">
<label for="first_name">First Name</label>
<input type="text" value="" name="first_name" id="FirstName"/>
<label for="last_name">Last Name</label>
<input type="text" value="" name="last_name" id="LastName"/>
</div>
<div id="step2" style="display: none;">
<label for="first_name">Address</label>
<input type="text" value="" name="address" id="Address"/>
</div>
Continue to step 2
<input type="submit" id="submit_btn" value="Verstuur" style="display: none;" />
</form>
​
$(function() {
$('#step1_btn').click(function() {
$('#step1').hide();
$('#step2, #submit_btn').show();
});
});​
How do you guys suggest I achieve this?
There's a very neat setting of jQuery validate that lets you ignore validation on hidden fields. So you can handle the show/hide logic of your steps and for validation you could just do this:
As this suggests: ignore hidden
$("form").validate({
ignore: ":hidden"
});
If you need to check for validation on something besides the default form submit, you can use the valid method like this: $("form").valid().
I noticed you don't have any validation classes on your form, so I'm assuming you're handling that somewhere else. Just in case you're not, you can tell jQuery validate your rules through css classes like this: <input type="text" class="required digits"/>
See more here: http://bassistance.de/2008/01/30/jquery-validation-plugin-overview/

problem with jquery : minipulating val() property of element

Please help!
I have some form elements in a div on a page:
<div id="box">
<div id="template">
<div>
<label for="username">Username</label>
<input type="text" class="username" name="username[]" value="" / >
<label for="hostname">hostname</label>
<input type="text" name="hostname[]" value="">
</div>
</div>
</div>
using jquery I would like to take a copy of #template, manipulate the values of the inputs and insert it after #template so the result would look something like:
<div id="box">
<div id="template">
<div>
<label for="username">Username</label>
<input type="text" class="username" name="username[]" value="" / >
<label for="hostname">hostname</label>
<input type="text" name="hostname[]" value="">
</div>
</div>
<div>
<label for="username">Username</label>
<input type="text" class="username" name="username[]" value="paul" / >
<label for="hostname">hostname</label>
<input type="text" name="hostname[]" value="paul">
</div>
</div>
I am probably going about this the wrong way but the following test bit of javascript code run in firebug on the page does not seem to change the values of the inputs.
var cp = $('#template').clone();
cp.children().children().each( function(i,d){
if( d.localName == 'INPUT' ){
$(d).val('paul'); //.css('background-color', 'red');
}
});
$("#box").append(cp.html());
although if I uncomment "//.css('background-color', 'red');" the inputs will turn red.
Why not just use a selector for input elements with the clone as root like so:
$( "input", cp ).val("paul");
instead of using the calls to children?
EDIT: It looks like as of jQuery 1.4, when you call clone, it should also copy the data of the elements instead of just the markup. That may solve your problem of having to copy over the values directly. Relevant piece of documentation (emphasis mine):
withDataAndEventsA Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4 element data will be copied as well.
I slightly modified your HTML by assigning a "hostname" class to the hostname input.
Here's the updated HTML:
<div id="box">
<div id="template">
<div>
<label for="username">Username</label>
<input type="text" class="username" name="username[]" value="" / >
<label for="hostname">hostname</label>
<input type="text" class="hostname" name="hostname[]" value="">
</div>
</div>
</div>​​​
And here's a JS:
$(function() {
$('#template div:first').clone().appendTo("#box");
$('#box div:last .username').val("Paul");
$('#box div:last .hostname').val("google");
});
Also, you might want to take a look the jQuery Template proposal at http://wiki.github.com/nje/jquery/jquery-templates-proposal

jQuery serialize function with multple forms

I'm using the jQuery .serialize function and can't get it to serialize the proper form on submit.
my js code:
function getquerystring(form) {
return $("form").serialize();
}
my forms:
<div class="leave_message_box">
<form name="leave_message_form">
<input type="text" name="clock_code" placeholder="Clock Code" />
<input type="text" name="message" placeholder="Message (Blank for none)"/>
<input type="hidden" name="type" value="leave_message" />
<input value="Leave Message" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "leave_message_form")'></p>
</form>
</div>
<div class="outside_job_box">
<form name="outside_job_form">
<input type="text" name="clock_code" placeholder="Clock Code" />
<input type="text" name="message" placeholder="Message (Blank for none)"/>
<input type="hidden" name="type" value="ouside_job" />
<input value="Outside Job" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "outside_job_form")'></p>
</form>
</div>
I must be doing something wrong in passing the variable. the full code # pastie. The function I have does work, however, its always the last form that gets submitted.
Using this code:
$("form")
will find all the <form> elements in your document.
Given that form is a string containing the name of the form, what you want instead is this:
$("form[name='" + form + "']")
Looking at your supplied code, I have this suggestion. Instead of passing the form name to your function, why not just pass the form itself?
<button onclick="xmlhttpPost('blah', this.form)">
You also don't need to put javascript: in the onclick, onfocus, onwhatever properties.
I would suggest putting an ID attribute on the form and then using that ID as an explicit selector for jQuery:
<div class="outside_job_box">
<form id="outside_job_form" name="outside_job_form">
<input type="text" name="clock_code" placeholder="Clock Code" />
<input type="text" name="message" placeholder="Message (Blank for none)"/>
<input type="hidden" name="type" value="ouside_job" />
<input value="Outside Job" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "outside_job_form")'></p>
</form>
</div>
Then you would select and serialize it like this;
var f = $("#outside_job_form").serialize();
Not only making your code more effecient but more readable, in my opinion.
If the sole purpose is to encode simple text into URL format then use encodeURIComponent().

Categories

Resources