getting class name of check box when it checked - javascript

I have html code like this having a class name:
<input type="checkbox" value="Yes" id="ques11" name="radiobutton" class="option_1" />
and I also have another line
<input type="checkbox" value="Yes" id="ques12" name="radiobutton" class="option_2" />
If I check the first check box, I want to get the class name of that check box as the output, and to store it in a script variable. How do I get this class name?

From within a click handler attached using jQuery (or several other ways), this is a reference to the input, you don't need closest.
That isn't your problem, though, your problem is trying to call val on an array. If you want the second entry in the array from split, just use [1]:
var quesNo = this.className.split("_")[1];
Note that this assumes there is only a single class on the input.
Rather than using a class name for this, though, I suggest using a data-* attribute:
<input type="checkbox" value="Yes" id="ques11" name="radiobutton" data-quesno="" />
then
var quesNo = $(this).attr("data-quesno");
(You'll get people telling you to use .data("quesno") instead. Only do that if you need the features data provides. It is not an accessor for data-* attributes, that's a common misconception.)

Related

django auto check if i save it to database

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").

jQuery returns UNDEFINED or ON as Input Value

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

Is order of resulting array of document.querySelectorAll("input[type=checkbox") guaranteed?

I have the following HTML in the page body - these are the only input's of type checkbox on this HTML page:
<fieldset>
<legend>North Face</legend>
N-A1:
<input type="checkbox" name="NorthFace" value="N-A1" id="NA1">
N-B2:
<input type="checkbox" name="NorthFace" value="N-B2" id="NB2">
N-C3:
<input type="checkbox" name="NorthFace" value="N-C3" id="NC3">
N-D4:
<input type="checkbox" name="NorthFace" value="N-D4" id="ND4">
N-E5:
<input type="checkbox" name="NorthFace" value="N-E5" id="NE5">
N-F6:
<input type="checkbox" name="NorthFace" value="N-F6" id="NF6">
N-G7:
<input type="checkbox" name="NorthFace" value="N-G7" id="NG7">
N-H8:
<input type="checkbox" name="NorthFace" value="N-H8" id="NH8">
</fieldset>
<br />
<fieldset>
<legend>South Face</legend>
S-A1:
<input type="checkbox" name="SouthFace" value="S-A1" id="SA1">
S-B2:
<input type="checkbox" name="SouthFace" value="S-B2" id="SB2">
S-C3:
<input type="checkbox" name="SouthFace" value="S-C3" id="SC3">
S-D4:
<input type="checkbox" name="SouthFace" value="S-D4" id="SD4">
S-E5:
<input type="checkbox" name="SouthFace" value="S-E5" id="SE5">
S-F6:
<input type="checkbox" name="SouthFace" value="S-F6" id="SF6">
S-G7:
<input type="checkbox" name="SouthFace" value="S-G7" id="SG7">
S-H8:
<input type="checkbox" name="SouthFace" value="S-H8" id="SH8">
</fieldset>
I have a SUBMIT button on this HTML page that when clicked by the user runs some javascript that needs to evaluate these checkboxes - so I do the following:
var checkboxes = document.querySelectorAll("input[type=checkbox");
so far every time I have checked the array checkboxes indexes 0-7 of checkboxes are N-A1 through N-H8 and indexes 8-15 are S-A1 through S-H8.
Question 1: as long as these remain the only checkbox type on this HTML page and they are always in this order on the page is this order in checkboxes array always guaranteed? (that is will the first 8 always be N-xx and the second 8 always be S-xx?)
Question 2: if a checkbox get's added somewhere else on this HTML page I'm hosed so what would be the best way to get only this set of checkboxes? Put sometype of div with an id around these 2 fieldset's or put some type of id on each of these fieldsets like "north" and "south". Give quick example of how to fetch the checkboxes in this case.
Question 3: what I really want in the end is to send only the checkboxes that are checked to my PHP backend - currently I am using a for loop in javascript on checkboxes to find which boxes are checked in javascript then send those that are checked in the POST to my PHP code. Is there a better way - best way to do this maybe just sent the whole checkboxes array in the POST and process in PHP to find who's checked?
Thanks in advance for ideas/suggestions...
1
Yes, the order is guaranteed.
The specification states
The querySelectorAll() methods on the Document, DocumentFragment, and
Element interfaces must return a NodeList containing all of the
matching Element nodes within the subtrees of the context node, in
document order. If there are no matching nodes, the method must return
an empty NodeList.
meaning the elements will be returned in the order they appear in the document
2
If checkboxes are added, the best way to get those elements would be to keep track of them when inserting.
Other than that, wrapping them in another element with an ID or class would work as well, or just giving the new checkboxes a class
var new_boxes = document.querySelectorAll('.new_boxes');
3
Generally you'd just submit the form, and the checked boxes will be sent automatically.
If you're sending the data with ajax, you can get the checked boxes with an attribute selector
var boxes = document.querySelector('input[type="checkbox"][checked]');

AngularJs: How to set radio button checked based on model

I have a model returning in the storeLocations object with a isDefault value. if isDefault returns true, I wan't to set that radio button in the group as checked.
Not sure if I need to do a $each(data, function(index,value) and iterate through each object returned or if there's an easier way to do this using angular constructs.
Object:
storeLocations = [
{
... more values,
isDefault: true
}
]
Markup:
<tr ng-repeat="location in merchant.storeLocations">
<td>{{location.name}}</td>
<td>{{location.address.address1}}</td>
<td>{{location.address.address2}}</td>
<td>{{location.address.city}}</td>
<td>{{location.address.stateProvince}}</td>
<td>{{location.address.postalCode}}</td>
<td>{{location.address.country}}</td>
<td>{{location.website}}</td>
<td>{{location.zone}}</td>
<td><input type="radio" ng-model="location.isDefault" value="{{location.isDefault}}" name="isDefault_group"></td>
Use ng-value instead of value.
ng-value="true"
Version with ng-checked is worse because of the code duplication.
If you have a group of radio button and you want to set radio button checked based on model, then radio button which has same value and ng-model, is checked automatically.
<input type="radio" value="1" ng-model="myRating" name="rating" class="radio">
<input type="radio" value="2" ng-model="myRating" name="rating" class="radio">
<input type="radio" value="3" ng-model="myRating" name="rating" class="radio">
<input type="radio" value="4" ng-model="myRating" name="rating" class="radio">
If the value of myRating is "2" then second radio button is selected.
One way that I see more powerful and avoid having a isDefault in all the models is by using the ng-attributes ng-model, ng-value and ng-checked.
ng-model: binds the value to your model.
ng-value: the value to pass to the ng-model binding.
ng-checked: value or expression that is evaluated. Useful for radio-button and check-boxes.
Example of use:
In the following example, I have my model and a list of languages that my site supports. To display the different languages supported and updating the model with the selecting language we can do it in this way.
<!-- Radio -->
<div ng-repeat="language in languages">
<div>
<label>
<input ng-model="site.lang"
ng-value="language"
ng-checked="(site.lang == language)"
name="localizationOptions"
type="radio">
<span> {{language}} </span>
</label>
</div>
</div>
<!-- end of Radio -->
Our model site.lang will get a language value whenever the expression under evaluation (site.lang == language) is true. This will allow you to sync it with server easily since your model already has the change.
Ended up just using the built-in angular attribute ng-checked="model"
As discussed somewhat in the question comments, this is one way you could do it:
When you first retrieve the data, loop through all locations and set storeDefault to the store that is currently the default.
In the markup: <input ... ng-model="$parent.storeDefault" value="{{location.id}}">
Before you save the data, loop through all the merchant.storeLocations and set isDefault to false except for the store where location.id compares equal to storeDefault.
The above assumes that each location has a field (e.g., id) that holds a unique value.
Note that $parent.storeDefault is used because ng-repeat creates a child scope, and we want to manipulate the storeDefault parameter on the parent scope.
Fiddle.
Just do something like this,<input type="radio" ng-disabled="loading" name="dateRange" ng-model="filter.DateRange" value="1" ng-checked="(filter.DateRange == 1)"/>

getting class attribute of radio button in IE

I need to get the class attribute of checked radio button, with name="radio".
Used the code that's working fine in Firefox, but fails in IE.
val = $('input:radio[name=radio]:checked').attr('class');
How can i accomplish this?
There is no psuedo-class :radio. I think you meant [type=radio].
As comments says, I think you should use type instead of name. But i think you have named your input as radio because you can find this specific input. If you just use type selector you will catch every single selected radio input on page.
<input type="radio" name="radio" class="ey" /> Male<br />
So, if your page have more forms, you should specify a parent or form to avoid conflicts. Set a id for your form and try to find it by form id and radio type like this:
<form id="myForm">
<input type="radio" name="radio" class="ey" /> Male<br />
</form>
val = $("#myform input[type='radio']:checked").attr('class');
I hope it can help you :)

Categories

Resources