jQuery check if Checkboxes are on page - javascript

I have a form that loads via ajax. Depending on the parameters sent to fetch the form, the form may have no checkboxes or it may have one or more check boxes.
I want to check if a checkbox is present on the page and if yes prompt the user to select one during validation if not selected.
If present, the checkboxes have the same class and a different ID.
<input type="checkbox" name="associatedClass"
value="$associatedClsNumVal" class="getAssociatedClass"
id="$associatedClsNumVal" />
What is the best approach? Can jquery "sense" if there are checkboxes on a page/in a form?
Thanks.
Thanks for the help on my previous post. I am adding to this one as it's the same type problem.
I now have a page where there are one or more groups of checkboxes and I need to ensure that only one checkbox is checked in each group.
Since I do not know how many groups there are until the page loads, what is the best approach to check this?
Thanks!

The easiest way is to check if there are any inputs of the type checkbox on the page. With jQuery you can use CSS selectors such as input[type="checkbox"] to find elements in the DOM. Combine that with .length and you can get how many there are on the page. The complete jQuery code for this would be
if ( $('input[type="checkbox"]').length ) {
// Validate checkboxes
}
If there could be other checkboxes on the page that you wouldn't want validated then you can limit your search to a particular element. For example, if you only wanted to validate checkboxes within a specific form with an ID of myForm then you can select the form and use .find() to search for checkboxes within and only within that form.
if ( $('#myForm').find('input[type="checkbox"]').length )
{
// Validate checkboxes
}
However with the validation you probably want to check each input individually and so instead of just checking the length to make sure there is at least one checkbox on the page we can use .each to find all checkboxes and then process them one at a time.
$('input[type="checkbox"]').each(function () {
// Validate this checkbox
});
The advantage of that is if there are none on the page it won't try and validate anything and it's perfectly valid, so we don't need to check to see if there are any before our validation.

$(':checkbox').length
will get you a count of all checkboxes on the page. You can narrow this down by giving them a common class if you need to be more specific.
For example, to just count the checkboxes with class 'section1':
var $checks = $('.section1:checkbox');
console.log('There are ' + $checks.length + ' checkboxes');
https://jsbin.com/bowasi/edit?html,js,console,output

if ( $( "#myElement" ).length ) {
// Your code here
}

Related

Want to take a radio and checkbox value from one form to another

I have values from one form that need to be transferred to another.
var manager = $('input[type=checkbox]:checked').val();
I'm capturing the value with this. and trying to send it to this.
$('input[type=checkbox]:checked').val(manager);
but I don't know what to put into the next set of jquery to transfer it over.
.val() works for strings/numbers but not checkboxes or radio buttons which I am trying to do.
Please advice.
Try jQuery prop() function to transfer the state of one checkbox to another.
Also use correct selectors. $('input[type=checkbox]:checked') will only select CHECKED checkboxes.
see this fiddle for an example: https://jsfiddle.net/iPirat/p5f07br4/
in this fiddle, the checkbox in the first form is selected similarly to what you did.
the checkbox insecond form is selected using an ID.

how to duplicate the value of one form field in another in jquery

I have a form where a user can chose the applications he has access to? and when he the applications he wants access to, he is presented with more options. One of them is notification email address. if the user choses two applications, he gets two notification email address fields to fill. But both of them are stored in the same column in the database.
There are multiple fields like user authorisation level, user branch etc which are uniform accross all applications.
i am trying to replicate the value of one field in the other with jquery. i tried the below which obviously fails. Can anyone suggest how to acheive the replication?
$("#email").val().change(function() {
$("#email1").val($("#email").val());
});
Edit: I have drop down fields as well as text boxes.
.val() returns a string which cannot have a change event. You need to use
$("#email").change(function() {
$("#email1").val($(this).val());
});
You will want to bind the change event using on or live depending on your version of jquery, if you haven't wrapped this piece of code in a ready block.:
$("#email").on("change",function() {
$("#email1").val($(this).val());
});
This fiddle shows setting a <select> tags value using .val() http://jsfiddle.net/8UG9x/
It is an often asked question:
Copy another textbox value in real time Jquery
depending on when you need this action to execute, but if live
$(document).ready(function() {
$('#proname').live('keyup',function() {
var pronameval = $(this).val();
$('#provarname').val(pronameval.replace(/ /g, '-').toLowerCase());
});
});
http://jsfiddle.net/KBanC/
another one, basically same:
JQUERY copy contents of a textbox to a field while typing

Alternate required inputs in one page

I want to have alternate required inputs. My goal to my form is to hide and show the inputs regarding with what position (Faculty Member or Student as options) and store to the database. Different input fields for the Student, as well as different fields too for the Faculty Member. I used this code for my javascript hide & show inputs:
<script type="text/javascript">
$(document).ready(function(){
$('#fac').hide();
$('#stud').hide();
$("#thechoices").change(function(){
$("#all").children().show();
$("#" + this.value).show().siblings().hide();
});
$("#thechoices").change();
});
</script>
However, when I choose Student (so Student input fields appear now and Faculty Member input fields are hidden),fill up the fields, and click Submit button, I can't proceed to the form action I put because the hidden fields for faculty member are also required to be filled. And if I eliminate the required attribute on each input, my database could be destroyed (such as multiple inputs, blank inputs). I got almost the same question but I still did not understand the given answer. What should I do?
I suppose you have used JQuery.
Try this approach.
You can intercept the form submission with this event handler.
Add this to your existing script.
$("form").submit(function( event ) {
// check if field is visible
if ( $("field").is(":visible") ) {
// validate it
}
}
For more info, Check JQuery Documentation at below links
Form Submit http://api.jquery.com/submit/
Visible selector : http://api.jquery.com/visible-selector/
HTH

Process each form fields in a form using JQuery

I have many questions based on form. I don't know the title suits or not. I created a JSP page and contains a form. It has many fields like input, select, textarea.
First is I want to count the number of fields in the form using JQuery. I tried the following.
var ln=$("#fileUpload").find('input,select,textarea').length;
alert(ln);
The form has one select box, 3 input fields and a textarea. But it was giving 0, instead of 5.(#fileUpload is the form id I want to submit)
How to get the exact number of fields?
Next is, I want to get each element in the form and find some attribute value. For examaple I want to get the name or id attribute for each element.
I would recommend using each() function:
$("#fileUpload input,select,textarea").each(function(){
console.log(this);
}
Btw: don't use alert, use console.log() instead ;)
You need to make sure that the form is loaded before your js script is launched.
To do so, wrap it in document ready like so:
$(function () {
var ln = $('#fileUpload').find('input, select, textarea').length;
alert(ln);
});
There should no problem in your code
Check that you have added the jquery and add an attribute to your form
id="fileUpload" then check
Also, check you don't have any other element having id fileUpload
like input type="file"
In your page <form id='fileUpload' ... > must be unique
Fiddle http://jsfiddle.net/qUJZf/

Jquery - SerializeArray() checkbox that is not "checked"

so I am trying to implement the Jquery .serializeArray() method to transform a form into a JSON string to send it out in a request. This works great for my form except for checkboxes and radio buttons. The only time this works properly is when they are checked. Sometimes, I need to know if they are unchecked. They still need to get serialized.
I suppose I could manually loop through the form and grab the values and build the JSON object, but that would not be optimal.
According to the Jquery documentation found here: Jquery Docs anything that fits the W3 standards for a successful control found here should get included. Unfortunately, this does not include checkboxes that are not checked. Does anyone have a work around for this behavior? Thanks in advance...
var form = document.getElementById('f');
console.log($(form).serializeArray();
That spits out the serialized form with the checkboxes that are not checked excluded...
If you really want to use checkboxes and radio buttons, have those input fields update a corresponding hidden field. That way, the hidden input will always be sent.
how about trying this, I had a similar problem, I thought unchecked checkboxes should have a value as well, here is a quick work around,
add an extra class on each checkbox on your form "cbx"
make data an array from the form with serialise
then loop through all checkboxes with a class of "cbx"
and add them to the array with a value of 0, AFTER the array has been created with (serializeArray())
when you post the data you will see the unchecked checboxes and values of 0 will get transferred with the post.
var data = $('#form').serializeArray();
$(".cbx:not(:checked)").each(function() {
data.push({name: this.name, value: '0' });
});
$.post("testpage.asp", data);
An alternative would be to use a jQuery plugin. For example, serializeJSON has the option to set the value for unchecked checkboxes like this:
$('form').serializeJSON({checkboxUncheckedValue: "false"});
In any case, it is usually best to use hidden inputs for unchecked values.
Alright, so I developed a workaround.
Basically I wrote a function to compare the original JSON object to the serialized form. As I looped through, I compared the components. If there was a discrepancy, I pulled the component off the form and manually inserted it into the JSON. I used the array.splice() method to add the missing components. Worked for all of the missing inputs.

Categories

Resources