Angular when checkbox is clicked show one element - javascript

If there is a element test-me for example which takes URL has attribute. That URL attribute should change depending on checkbox. If one checkbox is clicked then url1 should be displayed whereas if 2nd checkbox is clicked then 2nd url should be displayed.
Right now I do it this way,
<input type="checkbox" ng-model="chk1"> Check1
<input type="checkbox" ng-model="chk2"> Check2
<test-me url="url1" ng-show="chk1"></test-me>
<test-me url="url2" ng-show="chk2"></test-me>
The problem with above approach is that if I have 10 checkboxes then there will be 10 test-me elements. How can I do this the better way so that I supply the URLs in a way depending on the checkbox value or something but there will be more modularity.

You can use a controller variable to store all your checkboxes. So inside your controller use an array to store all models :
vm.controllers = [];
And on view add them into array :
<input type="checkbox" ng-model="ctrl.checkboxes[0]" />
<input type="checkbox" ng-model="ctrl.checkboxes[1]" />
<input type="checkbox" ng-model="ctrl.checkboxes[2]" />
So now on your controller you can access all of them and do any calculations you want and store them on another controller variable eg :
vm.url = "http://blablabla";
Use that on your view : {{ctrl.url}}

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

Have to click radio button twice for html element to change using AngularJS

I have a very simple form where I have Yes and No radio buttons. Each radio button is bound to the same item in the scope (I am using AngularJS). The Yes button's value gets set to true on being selected and the No button's value gets set to false when being selected.
When I click the Yes button once, both the model and the html element changes correctly. But when I click the No radio button, the model changes correctly but the html element does not become selected. If I click the No radio button again the html element then changes to it's correct selected state.
The example below is just part of a larger html page and controller but I have kept the Angular model structure the same because this may be where the issue is.
HTML:
<div ng-app="myApp">
<div ng-conroller="MyController">
<div>
<label>
<input type="radio" name="IsBeingPaid" ng-model="item.isBeingPaid" ng-checked="item.isBeingPaid" value="true"/>
Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="IsBeingPaid" ng-model="item.isBeingPaid" ng-checked="!item.isBeingPaid" value="false"/>
No
</label>
<p>{{item.isBeingPaid}}</p>
</div>
</div>
</div>
Controller:
var app = angular.module('myApp', [
'my.controllers'
]);
var controllers = angular.module('my.controllers', []);
controllers.controller('MyController', function($scope) {
$scope.item = {};
});
I have created this fiddle to demonstrate the issue.
http://jsfiddle.net/prajna78/Tdq9n/14/
What am I missing? It seems like such a simple thing.
There are a few problems with your code.
First, use ng-value instead of value in your radio button elements. This makes sure that the value you're binding to is a boolean (true) and not a string ("true"). Also, you don't need ng-checked (ng-model is sufficient).
<input type="radio" name="IsBeingPaidMinimumWage" ng-model="isBeingPaidMinimumWage" ng-value="true"/>
Also, you're binding to item.isBeingPaidMinimumWage, but your $scope variable is just isBeingPaidMinimumWage, so the initial value that you assign in your controller isn't reflected in the view.
Demo

Set Radio Button using value in jquery

How to set Radio button checked(select) using Attribute value
html :
<div class="controls">
<input type="radio" id="chairs_canadd" name="chairs_canadd" value="1" />
<input type="radio" id="chairs_canadd" name="chairs_canadd" value="0" />
</div>
now i m getting the value of chairs_canadd value from database via AJAX. if the value is 0 then the second have to get selected , if the value is 1 then first one has to be get selected.
Firstly, your IDs are not unique.
Second, a radio button group like this can only have one checked value at a time. So why not just use .val:
$('input:radio[name=chairs_canadd]').val([editValue.chairs_canadd]);
jsFiddle
You have value for option that needs to be set in variable chairs_canadd. you can get the radio button by value and then set it. Like this:
$(".controls input[value="+chairs_canadd+"]").prop("checked", true)

Need to have separate click event for two different set of checkboxes using jquery.

I have two sets of check box. One for categories and one For products.
For Categories i have this
<div id="category">
<input type="checkbox" id="cateogry1">
<input type="checkbox" id="cateogry2">
<input type="checkbox" id="cateogry3">
</div>
For Products i have this
<div id="product">
<input type="checkbox" id="product1">
<input type="checkbox" id="product2">
<input type="checkbox" id="product3">
</div>
What i did initially was looped through each checkbox and registered a click event for all like this
$("input:checkbox").each(function(){
var localCheckboxId = '#'+$(this).attr('id');
$(localCheckboxId).click(function() {
//did something
});
});
Now i want to separate the click events for both categories and products.
How to do that using jquery?
Use the containing div ID:
Products:
$("#product input:checkbox").click(...
Categories
$("#category input:checkbox").click(...
You can use a JQuery selector like this:
$("#category input").click(categoryFunction);
and like this:
$("#product input").click(productFunction);
What is happening is that the select first limits the selection to be based on the ID of each div. So the input part means "only input descendents that belong to the parent ID"
Because you only have checkbox input elements there is no need to specify the type. However, if you do actually use more input types then you can add the extra :checkbox part to limit the selector further:
$("#category input:checkbox").click(categoryFunction);
Here is a working example, it even shows how to get the id for the checkbox that is clicked.
You can keep your loop but add a test on the input parent :
if($(this).parent().attr('id') === "category") { ... }
else { ... }

Categories

Resources