Django Modelmultiplechoicefield Checkboxselectmultiple Problem Getting Selected Checkbox - javascript

I have been working all day to try and get the selected values on one set of checkboxes on my Django form and copy the selected ones only to an identical checkbox on my form. If a user clicks on a checkbox in form.author defined below, I want the same identical checkbox to automatically be checked on form.favorite_author defined below.
I've tried a JQuery approach as documented here...Copy Selected Checkbox Value From One Checkbox To Another Immediately Using JQUERY but no luck so far. I've recently begun exploring an avenue with the Modelmultiplechoicefield and the checkboxselectmultiple parameters within the form itself. From what I can tell, when I am using JQuery and trying to check a box on the form, the value is coming back as undefined which is most likely why it is not propagating the checkbox selection to the other checkbox.
Here is my form....
class ManagerUpdateNewAssociateForm(forms.ModelForm):
class Meta:
model = Library
self.fields['author'] = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple(),
queryset=Books.objects.all()
self.fields['favorite_author'] = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple(),
queryset=Books.objects.all()
My HTML...
<div class="spacer83">
{{ form.author }}
</div>
<div class="spacer83">
{{ form.favorite_author }}
</div>
When I tried to trace JQuery, it told me the checkbox selections are undefined. I did read a bit about how Modelmultiplechoicefield, since it uses a queryset it doesn't show the selections, but I can't figure out how to get it to.
Thanks in advance for any thoughts.

In combination with the other issue included in this one, I went back to the JQuery route and explored further. From what I can tell, I was not able to use the class for the input because of the way the HTML for Django forms is generated in this use case. I ultimately was able to leverage the input name and then used the code below to interrogate the checkboxes accordingly:
$(document).ready(function() {
$("[name=author]").change(function() {
let selectedValA = $(this).val();
let isAChecked = $(this).prop("checked");
$(`[name=favorite_author][value="${selectedValA}"]`).prop("checked", isAChecked);
});
});
});

Related

How to two-way bind a checkbox using Angular?

I currently have an accordion with a bunch of options in the form of checkboxes. The user can select the checkboxes as expected however, I want to already have some of those checkboxes checked depending on certain conditions. The issue is sometimes that is determined after the page has loaded. Below are simplified examples to demonstrate my code (my code is for work and would not be able to share due to confidentiality issues).
My HTML looks like this:
<div class="row">
<div "ngFor="let value of filteredPeople" >
<div>
<input type="checkbox" (click)="selectPeople(value)" [checked]="checkedPeople.get(value)">
{{ value }}
</div>
</div>
</div
My Javascript:
public checkPeople() {
this.selectedPeople.forEach(element => {
this.checkedPeople.set(element, true);
});
}
To explain some variables and methods:
Variables:
filterPeople - a string array of all possible people
checkedPeople - a map with a KVP of string (the people) and boolean (whether or not their checkbox is checked)
selectedPeople - a string array of people whose checkboxes I want already checked
Methods:
selectPeople - checks the corresponding checkbox when user clicks on it
checkPeople - a method called when I want the specific checkboxes checked (these specific checkboxes change based on other factors so I cannot hard code it)
For some reason my checkPeople method does not seem to select the expected checkboxes, I am not sure why but I have a feeling it is to do with the fact that I have used "[checked]" in the HTML and that it should be something else. Can someone clarify the issue for me and help me identify a fix? (Note: as the title suggests, I am using Angular)
Edit:
I have just debugged my code and added breakpoints, the checkedPeople map has the correct mapping of people to true for each of the elements in selectedPeople which shows that the checkPeople method is working as expected. Therefore the issue must be with the [checked] attribute if I'm not mistaken. I cannot see why it wouldn't work though.
You should use [ngModel]="checkedPeople.get(value)"
instead of [checked]="checkedPeople.get(value)"
to initialize the checkbox and
(change)="checkUncheckPeople(value, $event)"
to update the value when you check or uncheck it, where
checkUncheckPeople(value, e) {
this.checkedPeople.set(value, e.target.value);
}
So, in conclusion, your HTML input element will be:
<input
type="checkbox"
[ngModel]="checkedPeople.get(value)"
(change)="checkUncheckPeople(value, $event)"
/>
If you choose to use an object instead of a map then you can also directly use
[(ngModel)]="checkedPeople[value]"
to two-way bind the variable

Select field populated with multiple entries after one checkbox change

I have something in my mind, but I have no idea how to get it done, so I hope I can get some advise here.
I'm working on an activity registration app (using Laravel), where every activity will be registered. Very important is that we need to record who was invited and who actually attended. I already have this part running. My issue is more on the practical side.
I use jQuery Select2 for the multiple select fields for invitees and attendees. Imagine now that there's a group of users that need to be invited or attend virtually all activities, while the invitation or attendance of others depends on the type of activity. Using Select2, I can only select users one at a time and that sucks if you need to do that for, say, 50 users for virtually every activity.
What is the best way to have a "group" that can be selected, which selection fills in all the names of those in the group in the select field? Or is there a better way to get this done?
I'm seeing something in my head, where there are checkboxes next to the select field, representing the groups. When you tick a checkbox of a group, the select field is populated with all users who are part of that group.
I have no idea ow this can be done. I looked around and every search brings up select boxes populating select boxes. None handle checkboxes.
Any advise on how to get this done?
My PHP/MySql is intermediate, Javascript/Ajax is very basic.
One strategy would be to build a control (checkbox element) that will set or toggle the selection of your group of users whenever it's clicked. Say we have the following markup:
<select class="my-big-group-select" multiple="multiple">
<!-- assorted options here -->
</select>
<label>
<input type="checkbox" class="toggle-default-group" />
Use my default big group of users
</label>
The Select2 API allows you programmatic control over the component it generates.
You can read more about it here: https://select2.github.io/examples.html#programmatic
Here's one way to leverage this knowledge using jQuery with Select2:
<script>
var groupSelect = $('.my-big-group-select').select2();
var groupToggle = $('.toggle-default-group');
var myBigGroup = ["Aaron", "Beth", "Cindy"]; // assorted option values
groupToggle.on("click", function() {
if ($(this).is(':checked')) {
groupSelect.val(myBigGroup).trigger('change');
} else {
var currentlySelected = groupSelect.val();
if (currentlySelected) {
var filteredSelections = currentlySelected.filter(function(key) {
return myBigGroup.indexOf(key) < 0;
});
groupSelect.val(filteredSelections).trigger('change');
}
}
});
</script>
Here's a CodePen that shows it all in action: http://codepen.io/anon/pen/qNQKOd
Of course you can build on this to make additional enhancements (the ability to select multiple groups, for example).
As an alternative, you may consider other code libraries like Bootstrap Multiselect: https://davidstutz.github.io/bootstrap-multiselect/
Hope this points you in the right direction!

check box validation javascript

I need to validate the selection of at least one check box on a table. I am not using an alert because I already have a class on CSS that highlights in red the inputs, selects and other elements if they are not filled out.
This is my JS:
var btnRegister= document.querySelector('#btnRegisterRegObr');
btnRegister.addEventListener('click', function () {
var bError= false;
//I am initializing this boolean variable so that it also shows an error
//message on the screen if the user has not selected any option at all...
var elementCheckRegObr = document.querySelector('#checkRegObr');
if (elementCheckRegObr.checked==false){
bError=true;
elementCheckRegObr.classList.add('error');
//This part of the code brings the error I have
//previously created on CSs if the checkbox is not checked
}
else{
elementCheckRegObr.classList.remove('error');
}
});
The button on HTML has the right id on the HTML: id="btnRegisterRegObr.
I was looking at some codes here and people were validating using the .checked==false
However this does not seem to work for mine.
As a matter of fact, I first thought I needed to use the syntax of if (elementCheckRegObr.checked=="") but that one does not seem to work either.
I dont have problems validating inputs, selects nor radio buttons, but I am not sure if I am doing it on the right way with the check boxes. Any help or advice would be greatly apprecciate it :)
I suggest that you use getElementById to get your elements, and test if the checkbox is checked this way:
if(document.getElementById('idOfTheCheckBox').checked){
alert('hey, im checked!');
}

Show sections based on value of Check box in jQuery (SharePoint 2010)

I am trying to use jQuery to show section if a user selects a certain checkbox in a sharepoint form. I have had success doing this with a button and with a simple checkbox with one value to show all from this blog post http://akanoongo.blogspot.com/2008/04/how-to-hide-fields-in-sharepoint-list.html, but am struggling with if they select multiple values.
<script type="text/javascript" src="/SiteAssets/Libraries/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function(){
$("nobr:contains('Desk Calendars')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Calendar Refills')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Spiral Bound')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Wall Calendars')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Misc. Calendars')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Franklin Covey')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Comments')").parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Retention Policy')").parent('h3').parent('td').parent('tr').hide();
});
</script>
It would appear the value needs to be an if statement for contains VALUE not a click function. I am not sure what to do with this though.
$("input[title$='ShowFields']").click(function()
Basically if they select Wall Calendars it should show jsut wall calendar but if they do Wall and desk, it should toggle them both.
Any guidance would be fantastic. Thank you!
EDIT: I change my answer based on your comment below
To do what you want I'll use the library I created that is called SharepointPlus (please load jQuery and SharepointPlus in your page). Then the JavaScript code would be something like:
// hide all the rows by default
$SP().formfields("Desk Calendars,Calendar Refills,Spiral Bound,Wall Calendars,Misc. Calendars,Franklin Covey,Comments,Retention Policy").row().hide();
// add a trigger for when you click a checkbox
$SP().formfields("Calendar Type").elem().on('click', function(event) {
// the value of the checkbox is found with the "title" attribute from the parent
// if it's checked, then we show the row, if it's not then we hide it
$SP().formfields($(this).parent().attr("title")).row().toggle(this.checked)
})

cakephp - Javascript

We are working on an application using the CakePHP framework
Basically, its a questionnaire application and it has a few dependant questions, i.e. based on a response to a specific question, it needs to show or hide the next one
For e.g.
Question: Are you married? Yes/No
If the user selects Yes, then using javascript the next question gets displayed for user input
Question: Spouse's name
Saving this information is fine, but when editing, when populating the form, we would want to be able to display the fields for which user has inputted data - in this case, it needs to show the field that has the spouse's name
Since by default we are hiding the spouse name field, when editing, it doesn’t display the field, even though there is a value to it
Is there some way that CakePHP can handle this or does it require us to write some javascript to take care of this?
Thanks in advance.
CakePHP does not manage this for you. While CakePHP is very powerful and a great framework, it will not write this kind of logic for you. You must write it.
I would suggest making the EDIT screen different from the ADD screen. Build the list of values from the database and display the fields that have values (and include any empty fields that should require values).
Keep in mind reusable does not necessarily mean that all CRUD actions fit into the same view.
Like others I advise you use differents EDIT and ADD screens.
But you can try make it with Javascript like this:
<script>
function enableDisableField(targetFieldId){
var targetField = document.getElementById(targetFieldId);
var checkbox = event.target;
console.log(checkbox.checked);
if (checkbox.checked){
targetField.disabled = false;
targetField.value = "empyt";
}else{
targetField.disabled = true;
targetField.value = "empyt";
}
}
</script>
<label><input type="checkbox" onchange="enableDisableField('married')"/> Merried</label>
<?= $this->Form->input('married',['label' => false, 'disabled']); ?>
It works well for ADD, but if you and EDIT you have to change de disable value according a field value:
<label><input type="checkbox" onchange="enableDisableField('married')"/> Merried</label>
<?= $this->Form->input('married',['label' => false, !isset($user->married) ? 'disabled' : '' ]); ?>

Categories

Resources