How to assign value to unchecked checkboxes - javascript

I'm creating a form with multiple checkboxes and I want to value of the checked checkboxes to be "yes" and the value of unchecked checkboxes to be "no". The site I'm hosting my form on does not let me add the hidden field with the same name and a different value so I have to find script that will add the hidden checkbox on submission and include the value of "no". Currently, when I submit the form the unchecked boxes are recorded as undefined but for data purposes I need it to be filled with "no".
Here is what I found:
$(document).ready($("#foo").submit(
function() {
// Add an event listener on #foo submit action...
// For each unchecked checkbox on the form...
$(this).find($("input:checkbox:not(:checked)")).each(
// Create a hidden field with the same name as the checkbox and a value of 0
// You could just as easily use "off", "false", or whatever you want to get
// when the checkbox is empty.
function(index) {
var input = $('<input />');
input.attr('type', 'hidden');
input.attr('name', $(this).attr("name")); // Same name as the checkbox
input.attr('value', "no"); // or 'off', 'false', 'no', whatever
// append it to the form the checkbox is in just as it's being submitted
var form = $(this)[0].form;
$(form).append(input);
} // end function inside each()
); // end each() argument list
return true; // Don't abort the form submit
} // end function inside submit()
));
Why is the script not working?

You need to check out the jQuery API documents
$(document).ready(function(){}); it takes function callback, which may not needed here.
$("#foo").submittakes function callback, which will be called right before the form is submitted.
No need to wrap selector in $.find
You need to figure out the context of this
The this in $(this).attr("name") is referring the input box
The this in $(this)[0].form is still the input box
I guess you are trying to get the reference of forms. You may use document.forms

You need to change the input with $(this). Within the .each function $(this) will refer to the checkbox itself.

It isn't normal to have severals input with same name you can put the value directly in checkbox
$(this).find($("input:checkbox:not(:checked)")).each(function(){
$(this).val($(this).is(':checked') ? "yes" : "no")
})

I was able to use this much simpler script. Works perfectly.
$('#foo').click(function () {
$(this).find('input[type="checkbox"]').each( function () {
var checkbox = $(this);
if( checkbox.is(':checked')) {
checkbox.attr('value','yes');
} else {
checkbox.after().append(checkbox.clone().attr({type:'hidden', value:'no'}));
}
});
});

Related

jQuery get submitted form values

I have 2 form and this forms have same input field (same names)
$("#first-form, #second-form").submit(function(event) {
$('#name').val()
});
In my example I get first form input value, I need to get submited form value.
I also trgu use $(this)('#name').val() but this method not work.
How to get submited form input values, if I have 2 same forms.
$('form').submit(function(event) {
$(this).find('[name=yourfieldsname]').val();
});
should do the trick.
$("#first-form, #second-form").submit(function(event) {
$('#'+$(this).attr('id')+' #name').val();
});
Once you've corrected the issue of (apparently) having duplicated IDs, you can select the input with a given name only inside the form that's been submitted like so:
$('form').submit(function() {
var name = $('[name="name"]', this).val();
});
Inside the submit event handler this refers to the form that triggered the event (i.e. the form being submitted), and $(selector, element) is equivalent to $(element).find(selector) which searches only inside of element for elements matching the selector.

Radio button REQUIRED if input field has content

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.

Form validation causing wrong input in database from form field

I'm using a javascript that validates a form by radio buttons being checked, depending on which button is checked I want a value for that button submitted to MySQL but when I select a button it submits the button name to MySQL. changing the name of the button causes the script to stop working. How can I change the script so it allows the button value to post to MySQL instead of the button name?
jsFiddle
function ValidateForm(form) {
ErrorText = "";
if ((form.job_status[0].checked === false) && (form.job_status[1].checked === false)) {
alert("Before you can get a signature you must mark a selection.\n Is the work completed or do you need to return?");
return false;
}
if (ErrorText = "") {
form.submit();
}
}
job_status[0] ,job_status[1] means with name job_status two radio buttons exist.
If you change one of the radio buttons name either of job_status[0] job_status[1] one will exist.So you are getting exception
Instead of doing all that process by default select a radio button.That solves all your problems.I updated the link
see here

Jquery click event with binded event

Hi guys I am having a problem with Events. I have a checkbox list and I have a main check box that checks all boxes. When I clickEvent some of my checkbox list items it should add data-id attr to the "selected obj". So in my case when I press main check box to check all others every thing is ok (it simply clicks all other elements). but when i do that it empties my array. I mean if i uncheck it will be the way it supposed to be but checked (when uncheck it fills when i check it empties).
......
var selected = {};
var reload = function(){
selected = {};
$('.checkbox_all').unbind('click');
$('.table_checkbox').unbind('click');
$('.checkbox_all').bind('click', checkAll);
$('.table_checkbox').bind('click', checkMe);
}
var checkMe = function(e){
var checkbox = $(e.target);
var id = checkbox.attr('data-id');
//console.log(id);
if(checkbox.attr('checked')){
selected[id] = id;
}else{
if(selected[id]) delete selected[id];
}
console.log(selected);
}
var checkAll = function(e){
if($(e.target).attr('checked')){
$('.table_checkbox').each(function(){
if($(this).attr('checked') === false){
$(this).click();
}
});
}else{
$('.table_checkbox').each(function(){
if($(this).attr('checked') === true){
$(this).click();
}
});
}
//console.log(selected);
}
.......
HTML:
<tr><th class="table-header-check"><input type="checkbox" class="checkbox_all"/></th></tr>
<tr class=""><td><input type="checkbox" data-id="5" class="table_checkbox"></td></tr>
<tr class="alternate-row"><td><input type="checkbox" data-id="6" class="table_checkbox"</td></tr>
<tr class="alternate-row"><td><input type="checkbox" data-id="8"
....ETC\
My problem is that when i click .checkbox_all it should click on all .table_checkbox(that r cheched or uncheched)... it just clicks all checkboxes like a main checkbox... it works fine, but i have an event all other checkboxes if i click em i add some data to array when i unclick em it removes data from array.... so when im clicking checkboxes sepperatly they add /remove data to array properly... but when im clicking on main checkbox... it clicks on right checkboxes but the data array is empty when all checked and full when all unchecked... it must be the opposite way
Could you instead go for a cleaner solution, and generate selected on the fly? See here for an example (and a JSFiddle for everyone else): http://jsfiddle.net/turiyag/3AZ9C/
function selected() {
var ret = {};
$.each($(".table_checkbox"),function(index,checkbox) {
if($(checkbox).prop("checked")) {
ret[$(checkbox).prop("id")] = true;
}
});
return ret;
}
** EDIT: **
If you're looking to have an array that is added to and removed from, then this JSFiddle (http://jsfiddle.net/turiyag/pubGb/) will do the trick. Note that I use prop() instead of attr(), in most cases, especially this one, you should use prop() to get the value you want.
To work with your own code you need to understand the order of events. When you programmatically call click() on the checkbox the javascript (checkMe() for children) executes before the state of each child checkbox is changed (e.g., adding attribute 'checked'). It is because of this reason that the checkMe() function was adding and removing ids in the selected array in the reverse order. You can confirm this by adding the following debug line in the checkMe function:
console.log('Checked state of checkbox id:' + id + ' is: ' + checkbox.prop('checked'));
Case1: Clicking checkAll when it is Unchecked; it calls checkMe() for each child checkbox but finds the 'checked' attribute as undefined. So it executes the delete code. After executing checkMe the 'checked' attribute is added on the checkbox.
Case2: Clicking checkAll when it is Checked; the checkMe() function finds the 'checked' attribute previously added and fills the array. Later an event is probably fired to remove the 'checked' attribute.
I changed the following lines to quickly test this and seems to be working:
Bind checkMe on change event instead of click in reload function:
$('.table_checkbox').bind('change', checkMe);
Change the condition for unchecked children in checkAll function when the .checkbox_all is checked:
if($(this).prop('checked') === false) {/*call child click*/}
//Use prop instead of attr because it takes care of 'undefined' cases as well. If you want to keep using attr because you're on an older version of jquery then add something like:
typeof $(this).attr('checked') == 'undefined'
and also the condition when .checkbox_all is unchecked:
if($(this).prop('checked') === true) {/*call child click*/}
Hope this helps. Here's a jsbin to play with..

How do I use jQuery to disable a form's submit button until every required field has been filled?

I have a form with multiple inputs, select boxes, and a textarea. I would like to have the submit button be disabled until all of the fields that I designate as required are filled with a value. And after they are all filled, should a field that WAS field get erased by the user, I would like the submit button to turn back to disabled again.
How can I accomplish this with jQuery?
Guess my first instinct would be to run a function whenever the user starts modifying any of the inputs. Something like this:
$('#submitBtn').prop('disabled', true);
$('.requiredInput').change(function() {
inspectAllInputFields();
});
We then would have a function that checks every input and if they're validated then enable the submit button...
function inspectAllInputFields(){
var count = 0;
$('.requiredInput').each(function(i){
if( $(this).val() === '') {
//show a warning?
count++;
}
if(count == 0){
$('#submitBtn').prop('disabled', false);
}else {
$('#submitBtn').prop('disabled', true);
}
});
}
You may also want to add a call to the inspect function on page-load that way if the input values are stored or your other code is populating the data it will still work correctly.
inspectAllInputFields();
Hope this helps,
~Matt
Here's something comprehensive, just because:
$(document).ready(function() {
$form = $('#formid'); // cache
$form.find(':input[type="submit"]').prop('disabled', true); // disable submit btn
$form.find(':input').change(function() { // monitor all inputs for changes
var disable = false;
$form.find(':input').not('[type="submit"]').each(function(i, el) { // test all inputs for values
if ($.trim(el.value) === '') {
disable = true; // disable submit if any of them are still blank
}
});
$form.find(':input[type="submit"]').prop('disabled', disable);
});
});
http://jsfiddle.net/mblase75/xtPhk/1/
Set the disabled attribute on the submit button. Like:
$('input:submit').attr('disabled', 'disabled');
And use the .change() event on your form fields.
Start with the button disabled (obviously). Bind an onkeyup event to each required text input, and an onchange or onclick to the select boxes (and any radio buttons/checkboxes), and when it fires, check whether all required inputs are filled. If so, enable the button. If not, disable it.
There is one loophole here, though. Users can delete the value of a text field without triggering the onkeyup event by using the mouse to "cut" the text out, or by holding down the delete/backspace key once they have deleted it all, and clicking the button before deleting it.
You can get around the second by either
disabling the button with onkeydown and checking if it is ok on onkeyup
checking for validity when the button is clicked
An idea from me:
Define a variable -with global scope- and add the value true- Write a submit function within your check the value above varibale. Evalue the the submit event only, if the value is true.
Write a function which ckecks all value from input fields and select fields. Checking the length of value to zero. if the value length of one field zero then change the value of the global variable to false.
After that, add to all input fields the event 'onKeydown' or 'onKeyUp' and to all select boxes the event 'onChange'.
I recommend taking a slightly different approach and using jquery's validation http://docs.jquery.com/Plugins/validation. The tactic you are suggesting is prone to security holes. The user could easily using firebug enable that button and then submit the form.
Using jquery validation is clean and it allows you to show error messages under the required fields if so desired on submit.

Categories