All,
I have the following bit of PHP to check a checkbox:
<input type="checkbox" name="check_out_gear[]" id="'.$resultsetgear['gear_checkout_id'].'" value="'.$resultsetgear['gear_checkout_id'].'" class="gear_checkout_checkbox" checked disabled>
That code works fine and the checkbox is checked and it is disabled. I'm checking to see if it at least one checkbox is checked by using the following jQuery:
var fields = jQuery(".gear_checkout_checkbox").serializeArray();
if (fields.length == 0)
{
jQuery.wl_Alert('Please select a piece of equipment that you\'re checking out!','warning','#no_answers','#workform', {sticky:false});
one_selected = false;
}
When that checkbox is checked and disabled the length is always 0. However as soon as I remove the disabled from the code it has a length of at least 1. Any idea how I can get this code to work with a disabled checkbox?
serializeArray mimics a form submitting. When a form is submitted, disabled elements do not get sent.
Use is(":checked") instead.
jQuery(".gear_checkout_checkbox").is(":checked")
From the docs:
The .serializeArray() method uses the standard W3C rules for
successful controls to determine which elements it should include; in
particular the element cannot be disabled and must contain a name
attribute.
This is documented behavior for disabled inputs. From the jQuery docs on .serializeArray():
The .serializeArray() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute.
Just check for the length of the checked boxes using the :checked selector [jQuery docs], like so:
if (jQuery(".gear_checkout_checkbox:checked").length === 0)
A disabled checkbox will not be sent, regardless of whether it is checked or not. Therefore it won't be picked up by serializeArray. You should check whether the checkbox itself is checked, not if it would be submitted.
A disabled input will not show up because it is disabled. The fact that it is checked is of no consequence.
If you're using jQuery to enable and disable the checkbox, you could use jQuery to also set a value on a hidden input when disabling the checkbox (and to change it again when the checkbox is enabled again). You can then process the hidden input along with the checkboxes and do the correct thing.
Another possibility is to not disable the checkbox at all, but then use CSS changes to indicate it is locked and catch the onchange event to prevent it from being modified.
You can use length property of jQuery object not the length of the array that is returned by serializeArray() method, try the following:
if ($(".gear_checkout_checkbox:checked").length === 0) {
jQuery.wl_Alert('Please select a piece of equipment that you\'re checking out!','warning','#no_answers','#workform', {sticky:false});
one_selected = false;
}
Related
I'm working with forms where the checkboxes are present, but the target model's fields must be in boolean type, since they are defined in my migrations as boolean. For example:
$table->boolean('is_active')->default(true);
The Model's values are filled in this way:
foreach (static::getFillableFields() as $field) {
$entry->$field = $request->input($field);
}
So I added the cast to make this field boolean:
class Entry extends Model
{
protected $casts = [
'is_active' => 'boolean',
];
But now what I see: when the form's checkbox is checked and I have '1' string in the request, it works well - '1' gives 'true' when I access $entry->is_active then. But when checkbox isn't checked, it gives the 'null' value, and - I don't know why - when the model's field is set to null, then it returns null (not 'false', as I expected).
Why is it so? This makes casts useless in my case. Can I change this behavior?
I'm not too inspired with idea of adding this (accessors/mutators) for every boolean field (but in fact this results in what I need):
public function setIsActiveAttribute($value)
{
$this->attributes['is_active'] = (bool)$value;
}
public function getIsActiveAttribute(bool $value): bool
{
return $value;
}
As #Devon mentioned, checkboxes that are not checked are not included in the request data sent to the controller. The HTML spec deems unchecked checkboxes as unsuccessful, and therefore does not submit them.
One trick that is used to get around this "limitation", however, is to add a hidden input to your HTML that has the same name as your checkbox, but contains the false value. This hidden input must come before your checkbox input.
This will allow you to continue to use your mass-assignment functionality.
So, your form should look something like:
<input type="hidden" name="is_active" value="0" />
<input type="checkbox" name="is_active" value="1" />
Now, when the form is submitted with an unchecked checkbox, the hidden input will ensure the input value exists in the request data with the false value (0).
When the form is submitted with a checked checkbox, both inputs will submit successfully with the same name, but the server side will only take the last value it sees. This is why the checkbox must come after the hidden input field, so that the last value the server sees is the successful value defined on the checkbox (1).
As a side note, this is also how the Ruby on Rails form helper handles checkboxes. From their documentation.
The HTML specification says unchecked check boxes are not successful, and thus web browsers do not send them. Unfortunately this introduces a gotcha: if an Invoice model has a paid flag, and in the form that edits a paid invoice the user unchecks its check box, no paid parameter is sent. So, any mass-assignment idiom like
#invoice.update(params[:invoice])
wouldn’t update the flag.
To prevent this the helper generates an auxiliary hidden field before the very check box. The hidden field has the same name and its attributes mimic an unchecked check box.
This way, the client either sends only the hidden field (representing the check box is unchecked), or both fields. Since the HTML specification says key/value pairs have to be sent in the same order they appear in the form, and parameters extraction gets the last occurrence of any repeated key in the query string, that works for ordinary forms.
This is a controller issue, not a model issue. HTML checkboxes will not have a value if they are unchecked, this is how they work.
Therefore, when retrieving the value from your Request object in the controller, you should set the default value as false.
Example in controller method:
$model->is_active = $request->input('is_active', false);
If you leave the second argument of input() empty, it will default to null.
Suddenly: casts don't work for Model::save() method.
laravel eloquent model casts on save?
So all that's left for me is to use accessors/mutators..
The form used to add a new item into the database and edit existing items is the same form. A "Mode" is passed into the form to tell it if were adding something new or to load the existing item for editing. So....
<input type="checkbox" name="fflreq" id="fflreq" value="<?=$row['FFLr']?>" <?php if ($row['FFLr']=="Yes") {echo 'checked';} ?>>
When a new item is being added, $row['FFLr'] doesn't exist so of course the value is BLANK or NULL or i guess 0 if i don't initially check the checkbox- The form processor coverts this into a "No" and inserts it into the database.
Now here is my problem - When I come back to a item and the form is in edit mode, the VALUE in this checkbox is now "No" - when I am clicking the checkbox to change its status, I see the checkbox become 'checked' but the value is not changing. in other words the click/check status is not setting the value of $_POST['fflreq'] to YES or 1.
I thought, that checking or unchecking a form checkbox replaces whatever is currently in the value='' attribute with a 1 or 0 to represent yes/no on/off or whatever. Why would the value pulled in from the database not change on form submission?
You need to do it in this way:
<input type="checkbox" name="fflreq" id="fflreq" value="Yes" <?php if ($row['FFLr']=="Yes") {echo 'checked';} ?>>
and when submit the form if the above checkbox is checked then you recieved the $_POST["fflreq"] in the form submit page and if it is not checked you recieve nothing in $_POST
so in the submit page you can do this:
$fflreq = "No"
if(isset($_POST["fflreq"]) && $_POST["fflreq"] == "Yes")
{
$fflreq = $_POST["fflreq"];
}
//then you can simply do anything with the $fflreq such as inserting it into database etc.
I hope this can be of some help.
That's not how it works. If you have "checked" the check box then it (along with it's value) will be sent with the post/get (i.e. submission) of the form. If you haven't checked it, then it won't be set...
If the checkbox is active, the browser sends the key/value pair defined in the input tag. However, if the checkbox is not active, nothing at all is sent for this checkbox.
There are two options to deal with this:
The clean option is to be aware of this on the server side, and assume that the checkbox was not active whenever no value comes through.
A more dirty variant is having a <input type="hidden"> tag just before the checkbox, using the same name, but the value you need to see when the checkbox is inactive. This way, when the checkbox is active, you'll still get the desired value from the checkbox, because it will overwrite the hidden value. However, if the checkbox is inactive, you'll get the value from the hidden field.
Not really, the check/unchecked status is read out by looking if the HTML name attribute value is present in the $_POST param.
You can check this with:
<?
if (!empty($_POST['fflreq'])){ /*checked*/ }
else{ /*unchecked*/ }
?>
The value of the HTML attribute value always stays whatever it is in your HTML. So no user interaction (except JS) can change that.
Working with PHP empty() function lets you bypass all the "Yes" "1" string int casting issues.
Further I would use ternary notation for these kind of things:
<input type="checkbox" name="fflreq" id="fflreq"
value="<?=$row['FFLr']?>" <?=(!empty($row['FFLr'])?'checked':'')?>>
All
I have the following form input element:
<input name="payment_amount" type="text" id="payment_amount" value="" disabled>
I then manipulate the value of this form element by using jQuery:
jQuery(document).on('click','#remaining_balance',function(){
jQuery("#payment_amount").attr('disabled', 'disabled');
send_amount = jQuery("#value_to_transfer").val();
jQuery("#payment_amount").val(send_amount);
});
When I click on that radio button it populates the value into my payment_amount field but when I submit the form the value doesn't get passed to my receiving page. Any idea why that it?
Thanks in advance.
Disabled elements are not sent to the server. Enable it, send the data, then disable it again.
From this site:
http://webdesign.about.com/od/forms/a/aa071805.htm
I can see that "the disabled element will not be successful when submitting the form"
So, disabled form-fields aren't sent
Your jquery code isn't *un*setting the disabled field, so you're setting the value, sure. But you're not sending it.
SOLUTION:
// To enable
$('#payment_amount').removeAttr('disabled');
// OR you can set attr to ""
$('#payment_amount').attr('disabled', '');
(i got that code snippet from
http://jquery-howto.blogspot.com/2008/12/how-to-disableenable-element-with.html)
ADDED BONUS:
your jquery hurt my eyes. Why not use
$('#remaining_balance').click( function(){
...
}
Actually, why aren't you using the $ operator at all? Um, you use it instead of the "jquery" keyword.
So, that said, the solution you'd want is (if you want to keep on not using the $ operator):
jQuery("#payment_amount").removeAttr('disabled');
I have a select with some options. But this select section is not always shown. It is only shown if a user has clicked another element. If the user submits the form than the default values (first entries) of the select are also submitted. How can I clear the select value?
I tried it with $('#ExpM').val('') and also with this:
$('#Form').submit(function() {
if (!$('#radio_dump').is(':checked')){
$('#ExpM').selectedIndex=-1;
$('#ExpY').selectedIndex=-1;
}
});
But the values are also sent in the post. These values are not required. What can I do?
Try this:
$('#Form').submit(function() {
if (!$('#radio_dump').is(':checked')){
$('#ExpM').attr('name','');
$('#ExpY').attr('name','');
}
});
Basically, name it blank so nothing for it is sent.
foreach($_POST as $key => $value)
if ( empty($value) ) unset($_POST[$key]);
This is some idea only, I have not tested if it solves your problem:
Disabled form controls are not submitted. You could disable those form controls which should not be submitted, so you would not need to worry any longer which item is selected at all.
See Disabled and read-only controlsHTML4.
I'm pretty sure jQuery has something to disable a form field, see jQuery - Disable Form Fields.
I have a few checkboxes in my form and I need to change their value when the checkbox is checked.
For example this is one of the checkboxes:
<input type="checkbox" name="drink" value=""/>
I know .val() can change it but I wasn't able to do this with if statement.
I appreciate your answer in advance.
What you are seeking is actually very meaningless. See, when a form is submitted, only the checked checkboxes actually send values, so it makes no sense to change the value especially for the unchecked checkbox.
Better Solution
You should instead give it the "checked" value, and keep it that way, that will cause it to submit correctly even without changing the values.
You can add a click event listener on the checkbox:
$('input[name="drink"]').click(function() { // when click on it
if ($(this).attr('checked')) { // if the checkbox is checked
$(this).val("value #1"); // change the value
} else { // otherwise if is unchecked
$(this).val("value #2"); // change the value
}
});
// attach an onchange handler to all checkboxes on the page
$("input[type='checkbox']").change(function() {
// or if($(this).prop("checked")) {
if(this.checked) {
$(this).val("value for checked");
} else {
$(this).val("value for unchecked");
}
});
The onchange event is the one you should be interested when it comes to checkboxes, as it fires whenever you change the checked state of it.
The checked property determines whether or not the checkbox has been checked.
The .val() method allows you to conveniently read/write element values.