I have a script thats validating some form information. Currently it adds a CSS class of .error (adds red border) and also applies the shake effect when the input value is seen to be less than 1 character.
I also need to do this on various selects in the form if nothing has been selected. What would I need to do with the following code to get this to work please?
//check if inputs aren't empty
var fields = $('.validate');
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<1 || value==field_values[$(this).attr('id')] ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
I have limited Javascript / Jquery knowledge and this is a modified script I found online. You can see it in action here: site, step 2 of the form is where you can find the selects.
you can check if a selection was made by checking if there is an option selected :
if ($("#mySelect option:selected").length){
//something has been selected
}
if (!$("#mySelect option:selected").length){
//nothing has been selected
}
You can use this jQuery validation plugin instead it will make ur life way easier specially with errors and error displaying..
http://jqueryvalidation.org/
Related
I have a drop-down generated by a backoffice. I cannot change how this drop-down is coded by the backoffice. But I need to make user selection mandatory for this dropdown.
I am using the following code and this works in the JSFIDDLE HERE. However, this code sees if the user chooses another value than value "A" to determine if a selection is made. But this in not good enough in my situation because this value indication changes in other drop-downs.
I need the code to see if the user choice has changed from the text "PLEASE SELECT - $0,00" The "- $0,00" may also vary in different drop-downs, so I need the code to only filter on the "PLEASE SELECT" part of the drop-down text.
Also I need the browser to not ask to turn these warnings off in this case.
Can anyone help please?
function selection()
{
var cat = document.getElementById('select').value;
if (cat == "A") {
alert('Please make a selection');
return false;
}
return true;
}
Alert whatever text you want in a span instead of using alert()
document.getElementById('alert').innerHTML = "Please make a selection";
Check the updated fiddle
So there is couple of questions in your question, lets start with
1) Ensuring the selected item does not start with "PLEASE SELECT".
function selection()
{
var sel = document.getElementById('select');
var selectedText = sel.options[sel.selectedIndex].text;
if (selectedText.startsWith("PLEASE SELECT")) {
alert('Please make a selection');
return false;
}
return true;
}
2) Stopping the user forcing the browser to no longer allow alert
This is not something you can control. If you want full control over a model dialog then there are plenty of these available - bootstrap has one, jQueryUI has one. Any UI framework you're using will almost certainly have one
You can try something like:
function selection()
{
var cat = $('#select option:selected').val();
if (cat == $('#select option:first-child').val()) {
alert('Please make a selection');
return false;
}
return true;
}
For the warnings you will need to change you alert to a modal or on the page as a notice/warning message
I have a a reasonably quick problem to solve (I think). I have a form online and it validates the required content for the user's data, but has no validation on the first part of the form.
I've been asked however if I can make a radio button REQUIRED depending on whether an input field has been filled in.
The form can be found here:
http://www.elcorteingles.pt/reservas/livros_escolares/form.asp
So if the person start's filling in the input fields on the first line, that the radio buttons in the group become REQUIRED (for either the CDROM ou CADERNO but not both)
You can handle the focusout and blur events for the input:
$(function () {
// Handle every input type text.
// To select specific inputs, give them a common class and change the
// selector accordingly.
$("input[type=text]").on("focusout blur", function () {
// Check for inputs with class radio_btns which are in
// the parent element (li).
// Set their required property.
$(this).parent().find("input.radio_btns")
.prop("required", $(this).val().trim().length > 0);
});
});
Demo
jQuery reference (Tree Traversal)
jQuery reference (.prop())
jQuery reference (.focusout())
jQuery reference (.blur())
This will work. You can include the following JQuery code in the script tag, and also the JQuery cdn link in the head tag.
$(document).ready(function(){
$('#01titulo').focusout(function(){
if ($(this).val() !== "") {
$('[name="01caderno"]').prop('required', true);
} else {
$('[name="01caderno"]').prop('required', false);
}
alert($('[name="01caderno"]').attr('required'));
});
});
Try using the following js code its working:
$(document).ready(function(){
$(".titulo_books").each(function(){
$(this).focus(function(){
var radioChecked=0;
var currElemId = parseInt($(this).attr('id'));
var radioSelecterId = (currElemId>9) ? currElemId : "0"+currElemId;
$("input:radio[name="+radioSelecterId+"caderno]").each(function(){
if(radioChecked==0)
{
radioChecked==1;
$(this).attr("checked","checked");
}
});
});
});
});
I have checked it by executing this from console on your site and it seems to work fine. You can alter this in the way you want. I have checked one of the four available radio button. User can change the input value if required. Or you can also change the default radio button selected through my code.
I'm working on a form which has a validation script before submitting data.
Basically in all input fields, I have a function to test if the content of input is correct, triggered by 'onchange' event. If the content is 'invalid', the function will set the background of that input field to red.
function looseColorQty(t)
{
var n = t.value;
if(isNaN(n) == true || n < 0){
t.style.backgroundColor="red";
} else {
t.style.backgroundColor="";
}
}
Then when the user click 'submit' button, there's another script to check if this form can be submitted based on if any of the input fields is 'red'.
var canNotSubmit = 0;
function checkError(){
var fieldsToCheck = document.getElementsByTagName("input");
var fieldsQty = fieldsToCheck.length;
for(var i=0; i<fieldsQty; i++){
var checkTarget = fieldsToCheck[i].style.backgroundColor;
if( checkTarget == "red"){
document.getElementById("tips").className = "tipError";
document.getElementById("tips").innerHTML = "Please correct all RED fields before you submit.";
canNotSubmit = 1;
return;
}
}
}
It actually works but I just have a weird feeling that this validation is based on color. I wanna know if there's any drawback by doting so.
I think this is not a good idea.
Instead, if you're not using HTML5 field validation, I would attach (or change) an attribute on the field; for instance instead of setting t.style.backgroundColor="red" attach a data-validation="invalid" attribute, and then use your CSS to style it as a red background.
Base things on semantics (meaning) not on appearance.
Then you onsubmit handler can check for any data-validation="invalid" fields and issue messages based on those.
Don't forget to always validate again on the server after the submit, because you can't trust the client-side validation -- the data can always be tampered with after it has passed client validation.
I would add an additional classname to the element. Like value-is-invalid. Than you could check if the elements classname contains this class. You can also move your background-color: red; into this class in a css file. So you can seperate style from logic and change the style more easier later.
Like:
.value-is-invalid {
background-color: red;
}
As Stephen P pointed out you can't rely on client-side validation. always validate on server-side, too.
I have made a custom directive to do input validation, now the directive works fine in most cases but the way I have done it is to invalidate the field before I inspect it with ctrl.$setValidity('validation', false); and then I validate the field change it's $setValidity to true if it's valid. But my problem is when I use onBlur event inside my directive, because I invalidate the field as soon as I start typing it becomes dirty and shows invalid even though I just want it invalid after the onBlur, so I found out that the best is to invalidate the Form instead of each fields.
So to make it short how can I find the parent form of the input element and set it to invalidate?
When knowing the form name, I know I can do this scope.myFormName.$setValidity('validation', false); and it works, but I am trying to be generic and find the form object by myself and then invalidate it. I am trying to loop with the elm.parent() but not much success yet...and I'm trying to stay as generic as possible so with jqLite.
EDIT
I got some code working but it's not exactly clean code, does anyone have a better way?
var j = 0;
var parentElm = elm.parent();
var parentFormElm = null;
do {
if(parentElm.prop('tagName').toUpperCase() === "FORM") {
parentFormElm = parentElm;
break;
}
parentElm = parentElm.parent(); // next parent
}while(parentElm !== "form" && j++ < 50);
scope[parentFormElm.prop('name')].$setValidity('validation', false);
Since it's just a matter of styling things (as pointed out in the comments) you can just tweak Angular's CSS classes so the input field gets highlighted only when it's not focused:
.ng-invalid.ng-dirty:not(:focus) {
background-color: #ff7373;
}
Plunker
If you can't afford to use CSS3 selectors, then you'll need two CSS classes:
.ng-invalid.ng-dirty {
background-color: #ff7373;
}
.ng-invalid.ng-dirty:focus {
background-color: #fff;
}
Plunker
I need to be able to tell if the checkboxes are checked to do some basic validation. Problem: I don't have access to the PHP generating this. There is no class added, or the basic checked=checked that most forms have. What's the easiest way to target the checked boxes?
http://www.inpresence.in/event-registration?ee=4
EDIT: freak out!! here's the code, i just need to target the checked boxes, everything else is working. the :checked method of jquery uses checked=checked within the checkbox, which isn't there.
$(document).ready(function(){
//when the submit button is clicked...
$("input.btn_event_form_submit").click(function(){
//find the value of the drop down with one evening or four evenings
var priceOption = $("#price_option-4").val();
//match a string ending with "one evening" as the first numbers will be randomly generated by php
var oneEvening = /^\d{2}\|One Evening$/.test(priceOption);
//match a string ending with "four evenings" as the first numbers will be randomly generated by php
var fourEvenings = /^\d{2}\|Four Evenings$/.test(priceOption);
//HOW DO I GET THE CHECKED BOXES?!
var checkedBoxCount = $('#dates-1351733097 .valid').is(':checked').length;
//if one evening is selected make sure the checked boxes count does in fact equal one
if(oneEvening && checkedBoxCount != 1){
//if it doesn't alert the user and return false
alert('You must select one date');
return false;
}
//if one evening isn't selected, four is. make sure the count does indeed in 4
else if (fourEvenings && checkedBoxCount != 4){
//if it doesnt alert the user and return to the form
alert('You must select four dates');
return false;
}
//else, everything checks out!
else {
return;
}
});
});
Using this JavaScript code you can check if a checkbox is checked:
var isChecked = document.getElementById("my-checkbox").checked;
Or using jQuery:
var isChecked = $('#my-checkbox').is(':checked');
EDIT: Try this and tell me if it works:
var checkedBoxCount = $('#dates-1351733097 .valid:checked').length;
Have you tried using jquery to resolve this?
http://jquery-howto.blogspot.co.uk/2008/12/how-to-check-if-checkbox-is-checked.html
$('#edit-checkbox-id').is(':checked');
use the jquery :checked selector. http://api.jquery.com/checked-selector/
This will give you a boolean in javascript of what you want:
document.getElementById("Nov.12-4_1").checked
You can view source and find the elements to view whatever id's they have.
Other answers: the OP didn't specify that he wanted a jquery answer. If he hasn't used jquery for anything up to this point. I think adding it just for this would be a tad overkill.