I'm having trouble getting the validation function results "Required field" to fill the text input box of a table.
The current code is placing the result to the right of the cell instead of inside.
I'm fairly positive it's the $(this).parent().append portion but after trying several other variations I haven't achieved the expected results.
*The code verifies that a value is currently in the cell by means of examining the class = requiredField attribute.
Any tips are much appreciated. -Thank you.
<script type="text/javascript">
$(document).ready(function() {
$('form#commentform').submit(function() {
$('form#commentform .error').remove();
var hasError = false;
$('.requiredField').each(function() {
if(jQuery.trim($(this).val()) == '') {
$(this).parent().append('<span class="error">*Required field</span>');
hasError = true;
}
});
if(!hasError) {
alert('Validation Complete');
}
return false;
});
});
</script>
You can use the after() method:
$(this).after('<span class="error">*Required field</span>');
http://api.jquery.com/after/
Related
I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.
Friends i am new to javascript, I am trying to write a script to validate the entire form whenever any input field value is changed of input fiels with the data attribute of required.
HTML
<form>
<input type="text" name="FirstName" class="inputField" data-required="true"></input>
<input type="text" name="MiddleName" class="inputField"></input>
<input type="text" name="LastName" class="inputField" data-required="true"></input>
</form>
SCRIPT
var field, required, isValid, fieldVal;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
var isValid = true;
for(var i=0; i < field.length; i++){
required = field[i].dataset.required;
if(required){
field[i].addEventListener('blur', function(e){
fieldVal = this.value;
if(fieldVal == ''){
isValid = false;
}
checkSubmitBtn();
}, true);
}
}
function checkSubmitBtn() {
if(isValid = true) {
console.log(isValid);
document.getElementById("submitButton").disabled = false;
}
}
}
window.addEventListener("load", validatedForm);
PROBLEM 1:
The isValid is not updating hence even an empty blur on the input field makes the button disable to be false.
PROBLEM 2:
In case there are multiple forms on the page then how to validate only the desired forms .. just like in jQuery we add a script tag in the end to initialize the script according to it.
PROBLEM 3:
Is there a way to change the disable state of the button without the GetElementID ... I mean if that can be managed depending on the submit button of that particular form on the page where the script is suppose to work.
Any help will be highly appreciated. Thanks in advance.
I think you need something like the following form validation..
<script type="text/javascript">
var field, fieldVal, required = false;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
field.forEach(function(elem) {
required = elem.dataset.required;
if(required){
elem.addEventListener('blur', function(e) {
checkSubmitBtn(field);
});
}
});
}
function checkSubmitBtn(field) {
var isDisabled = false;
field.forEach(function(elem) {
fieldVal = elem.value.trim();
if(fieldVal == ''){
isDisabled = true;
return false;
}
});
document.getElementById("submitButton").disabled = isDisabled;
}
window.addEventListener("load", validatedForm);
</script>
I hope it helps...
There are quite a few things going on here. First, your checkSubmitBtn function used a single = operator in the if statement. This won't actually check the variable, it instead will set the variable to that value. Here is the fixed function:
function checkSubmitBtn() {
if (isValid == true) {
document.getElementById("submitButton").disabled = false;
}
}
You mentioned not wanting to use getElementById. There are a few ways around this. One way would be to call the function once and store it in a variable to use later, like so:
var button = document.getElementById("submitButton");
...
function checkSubmitBtn() {
button.disabled = !isValid;
}
Another way would be to use jQuery. It still is technically calling getElementById in the backend, but the code is much simpler. If you wanted to avoid that, you also can still combine this with the technique I described above.
$("#submitButton").attr("disabled", !isValid);
I'd also like to point out that your code doesn't account for a situation where a form goes from invalid (starting point) to valid and back to invalid again. Say a user types in all of the fields but then backspaces everything. Your code will fall apart.
Lastly, your <input> HTML tags should not be closed. There are certain tags that are considered "self-closing", i.e. you don't have to write the closing tag, </input>.
i have a form with few input fields with class "inputfields" need to validate each field if empty alert 'fieldname is empty' otherwise return true my jquery code is not working keep getting errors at the console log can any one help please ?
jQuery(document).ready(function() {
$('.inputfields').each.on('change keyup' ,function(){
var ope = $(this).attr('name');
if (ope.val()==''){
alert(ope+'is empty');
}else {
console.log(ope);
}
});
});
I believe you want to check different types of input fields, hence want to use change and keyup.
I tried something based on your code, but this following solution will only work, if you want to validate text type input fields. For select or other input types you have to put some more checks inside the loop or have to some other way to validate.
$('.inputfields').each(function() {
$(this).bind('change keyup', function() {
var ope = $(this).attr('name');
if ($(this).val() == '') {
console.log(ope+'is empty');
} else {
console.log(ope+ ' : ' + $(this).val());
}
});
});
Hope this will lead you to find your desired solution.
I am having the following JQuery function that is working properly:
$(function () {
$('#accmenu').change(function() {
$(".insightsgraphs div").hide();
$(".insightsoptions input").removeClass("green");
$("#newLikes").one('click', function () {
$.ajax({type:'GET', url: 'newLikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
var json = response.replace(/"/g,'');
json = "[" + json + "]";
json = json.replace(/'/g,'"');
var myData = JSON.parse(json);
var myChart = new JSChart('dailyNewLikes', 'line');
myChart.setDataArray(myData);
myChart.setAxisNameX('');
myChart.setAxisNameY('');
myChart.setAxisValuesColorX('#FFFFFF');
myChart.setSize(470, 235);
myChart.setTitle('Daily New Likes');
myChart.draw();
}});
return false;
});
$("#unlikes").one('click', function () {
$.ajax({type:'GET', url: 'unlikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
$("#dailyUnlikes").html(response);
}});
return false;
});
});
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
return false;
});
});
but I want to create a condition: if one of the following two date inputs:
var since = $('#dateoptions input[name="since_date"]').val();
var until = $('#dateoptions input[name="until_date"]').val();
is empty I want to receive an alert and the .one() function to be executed only when the conditions are met. For example when I click on one of the button without the date inputs in place I want to receive an alert like alert("One of the date or both missing") for example and after I choose the dates and press the button again to execute the .one() function like in the above example. I hope I make myself clear enough. I know that I can use something like:
if (until == "" || since == "") {
alert("One of the date or both missing")
} else {}
but my tries so far was no success. Probably I didn't place the condition where it should... Also it is possible also with an alert the inputs to be focused, highlighted or something similar?
EDIT:
Here's a fiddle with it:
http://jsfiddle.net/DanielaVaduva/ueA7R/6/
I replace the ajax call with something else without to modify the flow.
Try checking your values with:
if (until.trim().length === 0 || since.trim().length === 0) {
//TODO here
}
I suggest you that check your name attribute in your inputs and check that it's the same that you use when you are retrieving the values of the inputs.
If it still not working, try some 'debugging' like:
console.log(since);
And check if it is getting your value properly.
UPDATE
I don't know if you wanted this (demo). If your dates are empty, it will not work. AJAX call will not work on JsFiddle, because you are using a .serialize() and it sends the information via URL, as a GET type and you need to send it as POST. It doesn't matter. If you already prepared your server to recieve a GET method, it will work.
Also, I must add that if you want to change color ONLY if the AJAX was success, you must add your change color function as I used on the demo and if you want to check your date every time you want to send information to server, change .one() function into .on() function and remove the function after the AJAX success with:
$('#myimage').click(function() { return false; }); // Adds another click event
$('#myimage').off('click');
$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });
$('#myimage').off('click.mynamespace');
(More info about removing a function here);
I hope this will help you atleast on the way you want to do. Leave a comment if it is not what you wanted.
I'm not sure if I understood the issue exactly but.. you can check this >>
Fiddle Demo
HTML
Add IDs to the date fields like
<input id="until" type="date" name="until_date" value="Until date">
<input id="since" type="date" name="since_date" value="Since date">
And just for highlighting the required dates >>
CSS
.req{
border:2px red solid;
}
.required{
color:red;
font-size: 0.8em;
font-style:italic;
}
jQuery
$(function () {
//removing the highlighting class on change
$('#until').change(function() {
$(this).removeClass('req').next('.required').remove();
});
$('#since').change(function() {
$(this).removeClass('req').next('.required').remove();
});
$('#accmenu').change(function() {
var dSince= $('#since').val();
var dUntil= $('#until').val();
if(dSince=='' || dUntil==''){
alert('You MUST select Both dates!');
$(this).val(0); // Set the menu to the default
//Adding the Highlight and focus
if(dSince==''){
$('#since').addClass('req').after('<span class="required">- required *</span>').focus();}
if(dUntil==''){
$('#until').addClass('req').after('<span class="required">- required *</span>').focus();}
}else{
$(".insightsgraphs div").hide();
$(".insightsoptions input").removeClass("green");
$("#newLikes").one('click', function () {
$("#dailyNewLikes").html('</p>Test daily new likes</p>');
return false;
});
$("#unlikes").one('click', function () {
$("#dailyUnlikes").html('</p>Test daily unlikes</p>');
return false;
});
} //End of the if statement
});
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
return false;
});
});
Thus whenever an option from the accmenu gets selected, it will check for the values of the two DATEs, if both or any is blank, it won't execute the function.
I have a form which contains couple fields. Its very easy to validate this form. But when I'm using append or clone comand and add couple more fields in it dynamically I cannot validate the appended fields.
Here is the my code:
function addone(container, new_div) {
var to_copy = document.getElementById(new_div);
$(to_copy).clone(true).insertAfter(to_copy);
}
And because it doesn't matter which fields and I want all of them get field out I used class instead of id.
$(document).ready(function(){
$('#add_size').live('click', function(){
if($('.inp').val() == "") {
alert('Need to fill-out all fields')
}
else {
alert('Thanks')
}
})
})
Any idea? Thanks in advance.
$(document).ready(function(){
$('#add_size').live('click', function(){
if( ! checkvalid() ) {
alert('Need to fill-out all fields')
}
else {
alert('Thanks')
}
})
})
function checkvalid(){
var valid = true;
$('.inp').each(function(){
if (this.value == '') {
valid = false;
return;
}
})
return valid;
}
I see one thing that might cause you trouble...:
If you're only going to check fields for validity on submit, then I don't think you need the live handler. You're not adding fields with #add_size, you're adding .inp's. Just do your validations on click, and jQuery should find all the .inp class fields that are there at the time of the event:
$('#add_size').click(function(
$('.inp').each ...
)};
Or maybe I totally read the question wrong...