Javascript/jQuery: Get specific elements from form - javascript

I have an extense form with around 25 inputs (text, radio and checkboxes). I want that when I click the button that opens the jQuery dialog, loads the form and set all fields except 5 of them disabled. Seems so easy, but I want that into a "generic" function. I mean, that I have this method:
function disableInputs(jQueryElement, exceptions, booleanClean) {
//Some stuff
}
I want to get all the inputs from the jQueryElement, but ignoring all the elements with the ids that have exceptions. Exceptions is an Object like this one:
var exceptions = {
0: 'clientId',
1: 'clientName',
2: 'clientFirstSurname',
3: 'clientSecondSurname',
4: 'clientAlias'
}
This is my full code and what I've tested, but this is the only way to make it work and, if I have recieved the third parameter (booleanClean), It will set value='' to all inputs, instead to the elements that weren't excluded from being disabled. That boolean works to check if you want to clean inputs when this function is called:
function disableInputs(jQueryElement, exceptions, booleanClean) {
var inputs = jQueryElement.find('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].setAttribute('disabled', true);
for (var attr in exceptions) {
if (inputs[i].getAttribute('id') === exceptions[attr]) {
inputs[i].removeAttribute('disabled');
} else {
if (booleanClean === true) {
inputs[i].value = null;
}
}
}
}
}
I know why is not working the clean "option". What I want is where I have to put that to do it properly or if I can set a condition when I get the inputs to get only the inputs that are not excluded (preferible second option for optimization and not set an attribute to each input and remove them if are excluded. Seems much easier to work).

I'd suggest changing the exceptions object to be a conventional array:
var exceptions = ['clientId',
'clientName',
'clientFirstSurname',
'clientSecondSurname',
'clientAlias'];
...because then you can simplify your function a lot:
function disableInputs(jQueryElement, exceptions, booleanClean) {
var inputs = jQueryElement.find('input');
if (exceptions.length > 0) {
exceptions = "#" + exceptions.join(",#");
inputs = inputs.not(exceptions);
}
inputs.prop("disabled",true);
if (booleanClean)
inputs.val("");
}
I'm a bit confused about whether you want to clean all inputs or just the ones not on the exceptions list. My code above just cleans those not on the list. To clean them all move that if(booleanClean) inputs.val(""); to before the other if statement.

Try
function disableInputs(jQueryElement, exceptions, booleanClean) {
var not = jQuery.map(exceptions, function(item, index){
return '#' + item;
}).join(',')
var inputs = jQueryElement.find(':input').not(not).prop('disabled', true);
if(booleanClean){
inputs.val('')
}
}

Are you able to give a class name to the items that are exceptions? That's what I would do.
<input class="exception" />
$( "input:not(.exception)" ).prop("disabled", true);

Try this one:
HTML
<form>
<input type="text" name="input1" value="val1" />
<input type="text" name="input2" value="val2" />
<input type="text" name="input3" value="val3" />
</form>
JS
function disableInputs(jQueryElement, exceptions, booleanClean) {
jQueryElement.find('input').not( exceptions.join(', ') ).each(function(){
if( booleanClean ){
$(this).val('');
}
$(this).prop('disabled', true);
});
}
var exceptions = ['input[name=input1]', 'input[name=input3]'];
disableInputs( $('form'), exceptions, true );
Here is working sample: http://jsfiddle.net/4Dwwk/

Related

Get html checkbox list checked values to a hidden field

How to get the checked checkboxes id in to a hidden variable?
I am getting this error.
SyntaxError: unterminated string literal
var test = $('input[name=\'data-grid_c0[]\').val();
data-grid_c0 is the name of the checkbox array.
<input type="checkbox" name="data-grid_c0[]" id="data-grid_c0_1" value="1">
<input type="checkbox" name="data-grid_c0[]" id="data-grid_c0_2" value="1">
<input type="checkbox" name="data-grid_c0[]" id="data-grid_c0_3" value="1">
Below is the jquery code i have written.
$('#deleteall-button').click(function () {
var atLeastOneIsChecked = $('input[name=\"data-grid_c0[]\"]:checked').length > 0;
var test = $('input[name=\'data-grid_c0[]\').val();
alert(test);
if (!atLeastOneIsChecked)
{
alert('Please select atleast one record to delete');
}
else if (window.confirm('Are you sure you want to delete the records?'))
{
document.getElementById('search-form').action = 'index.php?r=device/bulkDelete';
document.getElementById('search-form').submit();
}
});
I want the value of data-grid_c0 to be assigned to selectedDevices hidden field.
<form action="hotelSearch/hotelSearch" method="post"><input id="selectedDevices" type="hidden" value="" name="selectedDevices" /><a id="deleteall-button" class="btn btn-primary">Bulk Delete</a></form>
So with php i will be able to handle it as following and delete,
//check-boxes
if (isset($_POST['selectedDevices'])) { //data-grid_c0
$del_camps = $_POST['selectedDevices']; //data-grid_c0
$model_camp = new Device;
foreach ($del_camps as $_camp_id) {
$model_camp->deleteByPk($_camp_id);
}
}
You're missing a closing ] and a closing '
var test = $('input[name=\'data-grid_c0[]\').val();
Should become
var test = $('input[name=\'data-grid_c0[]\']').val();
As others have pointed out, you don't necessarily have to escape those inner quotes.
var test = $('input[name="data-grid_c0[]"]').val();
You have incorrect selector to target checked check box and also you are not getting the id correctly. Use:
$('input[name="data-grid_c0[]"]:checked').attr('id');
Escaping is not necessarily needed here, you can use meta-characters as a string inside of the selectors.
var atLeastOneIsChecked = $('input[name="data-grid_c0[]"]:checked').length > 0;
var test = $('input[name="data-grid_c0[]"]').val();
And using " inside of a ' wrapped segment would be considered as a string, Don't confuse in that.

updating values of an array through <input> tags

I have the following three tag:
<input class="forLoopIndex" id="typicalElement" type="text" name="k" size="1" placeholder="10">
<input class="forLoopIndex" type="text" name="n" size="1" placeholder="n">
<input class="forLoopIndex" type="text" name="i" size="1" placeholder="i">
Now I have an event listener that checks when a value comes in, and then stores it in an array. I want the array to be kept at 3 values only. Cause I need to use the third and the second for something, but I need to see when they change. Here is the JS for that:
forloops.keyup(function () {
if (forLoopIndex.length < 2 && forLoopIndex >= 0) {
forloops.each(function () {
forLoopIndex.push($(this).val());
appendingToSigmaLimit();
console.log(sigmaLimit.val());
console.log(forLoopIndex);
});
} else if (forLoopIndex.length > 2) {
forLoopIndex = [];
}
});
Now, the problem is that, the values will only update until I have changed the values of the three inputs again. I have a feeling that the way of the logic is in my JS is making it do that. I just need to update the values every time that I change a value on one of my inputs. Any ideas?
Thanks,
M
Not sure what you expected, something like this will update each input separatly
var forloops= $('.forLoopIndex');
var forLoopIndex = [];
forloops.keyup(function () {
forloops.each(function (i, e) {
forLoopIndex[i] = $(this).val();
console.log(i);
console.log(forLoopIndex);
});
});
FIDDLE
Edit without loop:
var forloops= $('.forLoopIndex');
var forLoopIndex = [];
forloops.keyup(function () {
forLoopIndex[$(this).index('.forLoopIndex')] = $(this).val();
console.log(forLoopIndex);
});
FIDDLE

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

validate a dynamicnumber of checkboxes using javascript

I have some ASP code which presents any where from 1-any number of checkboxes (which are named the same) on the page. This validation does work however I think its a bit weak:
if (document.getElementById('selectedDocs').checked)
{
//this is here to handle the situation where there is only one checkbox being displayed
}
else
{
var checked = false;
var field = myForm.selectedDocs;
for(var j = 0; j < field.length; j++)
{
if(field[j].checked == true)
{
checked = true;
break;
}
}
if(!checked)
{
alert("You have not ticked any options. At least one must be selected to proceed!")
return false;
}
}
I was working with the code in the else block but this only works when there is more than one checkbox. It ignores the fact I have ticked the one single option when there is only one. So I placed the code inside the if section......Although it woks its a bit of a hack, can someone kindly improve it for me?
Thanking you...
Use:
var field = myForm.getElementsByName('selectedDocs');
This always returns a NodeList that you can iterate over.
If they are in a form and all have the same name, they can be accessed as a collection that is a property of the form. So given:
<form id="f0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
...
</form>
All the following return a reference to the form:
var form = document.getElementById('f0');
var form = document.forms['f0'];
var form = document.forms[0]; // if first form in document
and and all the following return a collection of the checkboxes named "cb0":
var checkboxes = form.cb0
var checkboxes = form['cb0'];
var checkboxes = form.elements.['cb0'];

Javascript form validation

I'm trying to figure out what would be the simplest way to validate required fields without having to do an if statement for each element's name. Perhaps just with a loop and verify its class.
What I'm trying to accomplish is to check only the ones that have the class name as "required"
<input name="a1" class="required" type="text" />
<input name="a2" class="" type="text" />
<input name="a3" class="required" type="text" />
Thanks
I'm not at all against the libraries suggested by others, but I thought that you may want some samples of how you could do it on your own, I hope it helps.
This should work:
function validate() {
var inputs = document.getElementsByTagName("input");
for (inputName in inputs) {
if (inputs[inputName].className == 'required' && inputs[inputName].value.length == 0) {
inputs[inputName].focus();
return false;
}
}
return true;
}
Also lets say your inputs are in a form named "theForm":
function validate() {
for (var i = 0; i < theForm.elements.length; i++) {
if (theForm.elements[i].className == "required" && theForm.elements[i].value.length == 0) {
theForm.elements[i].focus();
return false;
}
}
return true;
}
Of course you would trim the value and/or add the appropriate validation logic for the application, but I'm sure you can get the idea from the sample.
You can also store arbitrary data on the input itself and read it using the getAttribute() method on the element. For example you could have this element in your html (regex requires a 3 digit number):
<input name="a1" validate="true" regex="[0-9]{3}" type="text" />
you could use this method to run the regex in the validation routine.
function validate() {
for (var i = 0; i < theForm.elements.length; i++) {
var elem = theForm.elements[i];
if (elem.getAttribute("validate") == "true") {
if (!elem.value.match(elem.getAttribute("regex"))) {
elem.select();
return false;
}
}
}
return true;
}
Hope this helps.
I use the jQuery validation plugin. Works really well and fits your stated desire to only need class attributes.
$(document).ready( function() {
$('form').validate();
});
Is all it takes to set up the validation once you have your required fields marked.
I would recommend you to use this javascript based css selector wich will get all elements of a specific class. Validating the form just like the way you mentioned.
A pattern for this that I have been using for a long time and has served me well is wrapping the control with a DIV, or P and marking that as required.
<div class="form-text required">
<label for="fieldId">Your name</label>
<input type="text" name="fieldName" id="fieldId" value="" />
</div>
This means that I can pick out the required fields to validate easily with a CSS selector.
.required input, .required select
In jQuery, you can test input with something like this:
$('form').submit(function(){
var fields = $(this).find('input, textarea, select'); // get all controls
fields.removeClass('invalid'); // remove
var inv = $(this).find('input[value=""], select[value=""]'); // select controls that have no value
if (inv.length > 0) {
inv.addClass('invalid'); // tag wrapper
return false; // stop form from submitting
}
// else we may submit
});
In plain Javascript it would be more than I care to type out, but along the lines of:
var badfields = [];
var fields = theForm.getElementsByTagName('input');
for (var i=0; i< fields.length; i++ ) {
if ( fields[i] && fields[i].parentNode && fields.value == '' &&
/(^| )required( |$)/.test( fields[i].parentNode.className ) ) {
badfields.push( fields[i] );
}
}
// badfields.length > 0 == form is invalid
The most immediate benefit of wrapping the label and input (and optionally: hint text, error...) as a control "set" in this way is that you can apply CSS styles on the input and label together.
.required input, .required select {
border : 1px solid red;
}
.required label {
color : #800;
}
.invalid input, .invalid select {
background-color : #f88;
}
I recommend using a ready made solution for your form validation as things can quickly add on: How will you validate checkboxes? Can checkboxes be required? (EULA?) What about radio buttons, how will you check those?
Most validation solutions will also provide sugar such as verifying correct data (say, email addresses) rather than just checking if it's there.
I'm a little surprised that no one mentioned YUI.
You can easily use getElementsByClassName method of Dom class in the following manner:
var aElements = YAHOO.util.Dom.getElementsByClassName('required', 'input');
for (var i = 0; i < aElements.length; i++)
{
// Validate
}
More method information is available here and more general info is here

Categories

Resources