Here is my html:
<input type="checkbox" value="1" name="Visual" id="visual">
<input type="checkbox" value="1" name="Tuberculosis" id="Tuberculosis">
<input type="checkbox" value="1" name="Skin" id="Skin">
<script type="text/javascript">
$('#checkbox-value').text($('#checkbox1').val());
$("#checkbox1").on('change', function() {
if ($(this).is(':checked')) {
$(this).attr('value', 'true');
} else {
$(this).attr('value', 'false');
}
$('#checkbox-value').text($('#checkbox1').val());
});
</script>
Here is my view:
Visual = request.POST['Visual']
Tuberculosis = request.POST['Tuberculosis']
Skin = request.POST['Skin']
V_insert_data = StudentUserMedicalRecord(
Visual=Visual,
Tuberculosis=Tuberculosis,
Skin=Skin
)
V_insert_data.save(
Why is it every time I save the data to my database, the Visual, Tuberculosis and Skin are automatically checked even though I didn't check it when I was saving it? Or I think my javascript is wrong?
You don't need $('#checkbox-value').text($('#checkbox1').val());, unless you have such element on the page
which you haven't shown us.
You can't define more than one element on the same page with the same id.
(Same goes for the name attribute).
Use different ids as shown in my code and match the chekboxes by class/name.
Don't put value="1" inside your checkboxes.
Put your jQuery code inside a $(function() { }); which is an alias for $( document ).ready().
More info here.
Don't use bare request.POST values, use the sanitized self.cleaned_data['var_name'] instead.
I don't think it's a good idea to have param names with capital letters (this is just a note, it will not impact the functionality). According
to Python's PEP 8, only classes should start with a capital letter.
Frontend:
<input type="checkbox" name="Visual" id="checkbox1" class="checkbox-js-trigger-class">
<input type="checkbox" name="Tuberculosis" id="checkbox2" class="checkbox-js-trigger-class">
<input type="checkbox" name="Skin" id="checkbox3" class="checkbox-js-trigger-class">
<script type="text/javascript">
$(function() {
$(".checkbox-js-trigger-class").on("change", function(){
var new_val = $(this).is(':checked') ? 1 : 0;
$(this).val(new_val);
});
});
</script>
Backend:
It's best to use Model Form:
class StudentUserMedicalRecordForm(ModelForm):
class Meta:
model = StudentUserMedicalRecord
fields = ['Visual', 'Tuberculosis', 'Skin']
Because you have default value given as "1" here
<input type="checkbox" value="1" name="Visual" id="visual">
And also there is no element with id = "checkbox1" or id = "checkbox-value" which are referenced in your script.
Checkbox inputs are actually a little strange and work differently than how you think they work.
You don't need jQuery to handle the case when a checkbox has been changed. The browser and HTML handle that for you. (Sort of like how you don't need to listen for keys being pressed while the user is focused on a input type="text" to make letters show up in the text box.)
Instead, what happens is if the user checks the checkbox, the input will have an attribute called checked. It can look something like this .
The checkbox input tag also has two other attributes name and value. These are what get sent to the server when the form is submitted. BUT it only sends the name and value pair for the checkboxes that are checked! For the checkboxes that are not checked, it sends nothing. So if every checkbox has a name and value you can think of it as a key-value pair. If the check box is checked, it will send key=value to the server. You are allowed to have more than one value for a single key if you designate the name as being the name of an array.
So imagine you have a form like this:
<input type="checkbox" name="disease[]" value="tuberculosis" checked>
<input type="checkbox" name="disease[]" value="chickenpox" checked>
<input type="checkbox" name="disease[]" value="smallpox">
<input type="checkbox" name="needs_medicine" value="true" checked>
<input type="checkbox" name="recovered" value="whatevervalue">
When that form is submitted, the server will receive something that looks like "disease=[tuberculosis,chickenpox]&needs_medicine=true"
Notice that smallpox and recovered are not mentioned because they are not checked. Also notice that it's not super important what you put as the value of a checkbox that is not a multiple choice checkbox (in this example, needs_medicine) because the value that gets sent to the server will always either be the value of the checkbox (in this case, the string "true").
Related
I'm trying to get a group of checkboxes as part of an overall form I created in the admin area of WordPress to validate. Basically, custom fields. Here's what the code looks like:
<div><label><input type="checkbox" value="0-2" name="_ecp_custom_5[]" /> 0-2</label></div>
<div><label><input type="checkbox" value="3-5" name="_ecp_custom_5[]" /> 3-5</label></div>
<div><label><input type="checkbox" value="6-8" name="_ecp_custom_5[]" /> 6-8</label></div>
and so on.....
So I have this in my JavaScript:
jQuery(document).ready(function($) {
$('[name="_ecp_custom_3"]').attr("required", true);
$('[name="_ecp_custom_5[]"]').prop("checked", true);
});
First line for a text field, works great. But the checked one underneath doesn't work at all. If I submit the form without checking a box, the form still publishes and when it comes back, all the fields are now checked even though I didn't check any of them.
Puzzled what to do in regards to that since there's going to be several rules in this validation function.
If you are using html:
An html element name and id cannot include special characters, such as [ ], and must begin with a letter (A-Z), (a-z).
Aside from that, your jQuery references an element with the name=_ecp_custom_5 and not name=_ecp_custom_5[]. Simply remove the [] in your names and your code will work.
Update
The $('[name=foo]').prop("checked", true) sets all checkboxes with name=foo to checked. I'm a bit confused about what you are asking at this point, since it seems like you are confused about why your form is submitting all checkbox inputs as checked?
You want to require that at least one checkbox is checked, right?
You can iterate all inputs with the name attribute value of "_ecp_custom_5[]" by using jQuery.each(). With that, you can create any flag variable that will be used on any condition.
Please refer to the snippet below if you can't visualize what I am trying to say.
If you want to require that at least one checkbox is checked, you can use this example as your basis
$(function() {
$('#btnValidate').click(function() {
var flag = false;
$.each($('[name="_ecp_custom_5[]"]'), function(index, value) {
var checkboxStatus = $(this).prop('checked');
if (checkboxStatus == true) {
flag = checkboxStatus;
}
});
if (flag == false) {
alert('No checkbox has been checked')
} else {
alert('Success!')
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label>
<input type="checkbox" value="0-2" name="_ecp_custom_5[]" /> 0-2
</label>
</div>
<div>
<label>
<input type="checkbox" value="3-5" name="_ecp_custom_5[]" /> 3-5
</label>
</div>
<div>
<label>
<input type="checkbox" value="6-8" name="_ecp_custom_5[]" /> 6-8
</label>
</div>
<button id="btnValidate" style="margin-top: 20px;">Validate</button>
How I did it?
I iterated all inputs with the name attribute value of "_ecp_custom_5[]".
Then I created a boolean variable named "flag" (default value is false) that is being changed to true only if a checkbox from the iteration has the prop('checked') value of true. If no checkbox has been checked, then the "flag" variable's value will remain false which will then be checked by my condition.
Trying to set a Checkbox via addEventListener in JS, I already tried with
element.checked = true;
element.setAttribute('checked', true);
element.setAttribute('checked', "checked");
I can see in the console that my checked is set to true (not sure if the issue is that the boolean value is shown as string "true" or if this is just a chrome representation) but the element is not getting the check mark.
input id="element" class="element" name="element" type="checkbox"
value="1" checked="true"
Onload the default checked box is correctly set but when I'm trying to uncheck and set the new one nothing is happening (visually).
Thanks for any help.
I'm not sure exactly what you're trying to do but I think you want to toggle one checkbox depending on the state of another.
Have a look at this:
/* get the checkboxes */
const checker1 = document.getElementById('checker');
const checker2 = document.getElementById('checker2');
/* now listen for change on checker1 and action */
/* change the selected state of checker two to be opposite of checker 1 */
checker1.addEventListener('change', () => checker2.checked = !checker1.checked);
<p>
<label for=checker>Click me to toggle the other</label>
<input type=checkbox id=checker>
</p>
<p>
<label>I will be toggled</label>
<input type=checkbox id=checker2 checked>
</p>
So the thing is that if you were supposed to do this manually, Your code would have been like this right:
<input id="element" checked>
In order to achieve the same thing using javascript. It would only happen if you set the checked value to an empty string. Like this:
element.setAttribute("checked","");
This will let your output be like that above.
HOPE IT WORKED OUT FOR YOU :)
I have problem to get input value with jQuery.
Final Edit:
problem solved.
damnnn, i missed
=
for value attribute in input tag,
i struggled a lot with this silly mistake.. laughing emoji..
If i use
$("input[name=xxx]:checked").attr("value");
it returns UNDEFINED
If i use
$("input[name=xxx]:checked").val();
it returns ON(an error, not value.)
Edit:
Input created dynamically with js.
<div id="ab">
<input type="checkbox" name="aaa" value="apple">apple
<input type="checkbox" name="aaa" value="banana">banana
<input type="checkbox" name="aaa" value="grapes">grapes
<input type="checkbox" name="aaa" value="pista">pista
<input type="checkbox" name="aaa" value="badam">badam
<input type="checkbox" name="aaa" value="fruit">fruit
</div>
<div id="abcd"></div>
and after checked some of above, then below one,
var data="";
$('input[name=aaa]:checked').each(function() {
data += $(this).attr('value')+": <label class=\"badge badge-secondary mx-1\"><input type=\"radio\" name=\"xxx\" value\""+$(this).attr('value')+"\">A</label><label class=\"badge badge-secondary rounded-circle mx-1\"><input type=\"radio\" name=\"yyy\" value\""+$(this).attr('value')+"\">B</label>";
});
$('#abcd').html(data);
that one created content well correctly, but finally have problem in getting value of that checked radios,(user can select only two among different items).
some jQuery functions doesn't work for dynamically generated content like,
$("#xxx").click(function(){});
that one doesn't work for content created with js after page load,
$("body").on("click", "#xxx", function(){});
this one works for content created with js after page load,
maybe, similarly, there will be another one to get Input values that are created with js after page load.
If a value isn't specified in the element, the default values of a checkbox are "on" and "off". If the checkbox is supposed to have some specific meaning, you can specify that in the value attribute.
For example, let's say we want the user to check the box if they're over 18 years old. We could do something like:
<input id="checkbox" type="checkbox" value="over 18"/>
Then, when you query its value, $("#checkbox").attr("value"), you'll get "over 18".
If you don't want to specify a value that way, and you are using a label for the text next to the checkbox, you could do something like this:
HTML:
<input type="checkbox" id="checkbox" name="checkbox"/>
<label for="checkbox">Over 18?</label>
JS:
let text = $("label[for=checkbox]").text();
That will give you the label text, which is "Over 18?".
Update
For OPs updated case, you might be able to use something like $(staticAncestors).on(eventName, dynamicChild, function() {}); via jQuery.
Example:
First, assign a class name to the class attribute when the checkboxes are created dynamically (e.g., class = "your_class_name").
Then, do something like:
$(document).on('click', '.your_class_name', function() {
console.log($(this).is(':checked'));
// Do something with selected element
});
See https://api.jquery.com/on/#on-events-selector-data-handler, especially the section on Direct and delegated event handlers
Hope this helps.
Use
$("input[name=xxx]:checked")[0].value
Because it may return array of inputs so you must select first from array
I am trying to set the checked value of a checkbox to incoming data from Mongo. It works fine if the value is true, but when the value is false, it still checks the box. Can anyone tell me what is wrong.
<input type="checkbox" id="chk" name="interested" value="{{inmate.interested}}" onclick="chkSet(this)">Not Interested <br/>
<input type="checkbox" id="chk" name="correspondence" value="{{inmate.correspondence}}" onclick="chkSet(this)">Req Correspondence<br/>
<input type="checkbox" id="chk" name="study" value="{{inmate.study}}" onclick="chkSet(this)">Request Study<br/>
<input type="checkbox" id="chk" name="specialtyItemsApproved" value="{{inmate.specialtyItemsApproved}}" onclick="chkSet(this)">Specialty Items
Approved<br/>
<br>
$(document).ready(function(){
document.getElementsByName("interested")[0].checked=document.getElementsByName("interested")[0].value;
document.getElementsByName("correspondence")[0].checked=document.getElementsByName("correspondence")[0].value;
document.getElementsByName("study")[0].checked=document.getElementsByName("study")[0].value;
document.getElementsByName("specialtyItemsApproved")[0].checked=document.getElementsByName("specialtyItemsApproved")[0].value;
});
document.getElementsByName("interested")[0].checked=document.getElementsByName("interested")[0].value; sets the checked property based on the value of the element, which is always a string. So it will coerce the string to a boolean. All non-blank strings are truthy, so both "true" and "false" will set checked to true.
If you use an == test, you can set the checked accordingly:
document.getElementsByName("interested")[0].checked =
document.getElementsByName("interested")[0].value == "true";
That said, the purpose of the value of a checkbox in HTML/DOM is not to indicate whether it's checked, so setting value to "true" or "false" in the first place is probably not what you really want to do. The purpose of value is to say what value should be sent with the form if the checkbox is checked. Example:
<input type="checkbox" name="roomoptions" value="non-smoking">
<input type="checkbox" name="roomoptions" value="with-kitchen">
<input type="checkbox" name="roomoptions" value="en-suite">
The form will have roomoptions=non-smoking if that checkbox is checked, and/or roomoptions=with-kitchen if that checkbox is checked, and/or roomoptions=en-suite if that checkbox is checked. If none of them is checked, the form won't have any roomoptions sent at all. All three are sent if all three checkboxes are checked.
Separately, you cannot use the same id on more than one element in an HTML/DOM document. ids must be unique. So you can't use id="chk" on all of your checkboxes.
So I suspect you really want something more like this:
<input type="checkbox" id="chk-interested" name="interested" {{#if inmate.interested}}checked{{/if}} onclick="chkSet(this)">Not Interested <br/>
<input type="checkbox" id="chk-correspondence" name="correspondence" {{#if inmate.correspondence}}checked{{/if}}" onclick="chkSet(this)">Req Correspondence<br/>
<input type="checkbox" id="chk-study" name="study" {{#if inmate.study}}checked{{/if}} onclick="chkSet(this)">Request Study<br/>
<input type="checkbox" id="chk-specialty-items-approved" name="specialtyItemsApproved" {{#if inmate.specialtyItemsApproved}}checked{{/if}} onclick="chkSet(this)">Specialty Items
Then you don't need your JavaScript at all.
I didn't put a value on those, which means that when the form is sent in (if you're sending in the form), the value for interested and such that the server will receive will be the default value "on". E.g., the form will either not have an interested field at all (the checkbox wasn't checked), or it will have interested=on.
Note that unless you use those ids for something, you can just leave them off; it's the name that the form will use when submitted. But I made them unique to demonstrate that you must do that.
I want a function/code which will return the value that the user submitted for the field whose name/id is passed on to it. It shouldn't matter whether the field is a textbox, textarea, radio, or select. For example, the field could be:
<input type='radio' name='a_21' value='test' id='a_21_0' />
<input type='radio' name='a_21' value='test2' id='a_21_1' />
Or
<textarea name="a_21" rows="30" cols="6"></textarea>
When I do the call:
function getVal('a_21');
It should return the selected value.
How can I do this? Will:
document.myForm.field.value
work for textareas, dropdowns and radios, too?
The problem is different widgets have different purposes. For example, a <select> box with multiple selection available, multiple checkboxes, or even single checkboxes (whose value would be just "on" or "off") wouldn't have a single value, so it's ok for them to behave differently from other widgets.
But if you want to have a single function, you could do something like:
function getVal(obj){
if(obj.value){
return obj.value;
}
if(obj.selectedIndex){
return obj.options[obj.selectedIndex];
}
if(obj.checked){
return obj.checked;
}
return null;
}
Using jQuery you can do:
$('[name="a_21"]').val();
This will give you the value on of the field with name a_21, so matter what the type of field.
Note: The quotes are not needed, but I've gotten in the the practice of adding them because of checkbox arrays:
<input type="checkbox" name="ids[]" value="1" />
<input type="checkbox" name="ids[]" value="2" />
I figure it's better to be safe than trying to figure out why it doesn't work.