How to check if select all option is checked in sumoselect - javascript

I have just come across SumoSelect.js for dropdowns in my MVC project.
I just wanted to know if there is way to know if the select all option of the sumoselect dropdown is checked or not.
This is my sumoslect drop down code.
<div>
#Html.LabelFor(m => m.Territory)
#Html.DropDownListFor(m => m.Territory, Model.Territories, new { #class = "form-control", id = "ddlTerritory", multiple = "multiple", placeholder = "Select Territory" })
#Html.ValidationMessageFor(m => m.Territory)
</div>
JavaScript Code
$(document).ready(function ()
{
$('#ddlTerritory').SumoSelect({ selectAll: true });
if ($('#ddlTerritory')[0].sumo.selectAll())
{
some code
}
}
There is no mention of such method in the documentation of sumoselect.
It would be great if some one can guide me in the right direction.
Edit: As Suggested by #stephen
$(document).ready(function ()
{
$('#ddlTerritory').SumoSelect({ selectAll: true });
var isChecked = $('#ddlTerritory').closest('.SumoSelect').find('.select-all')‌​.hasClass('.select')‌​;
if (isChecked)
{
some code
}
}

this quite tricky, that I count selected items with total options:
function isMultipleSelectAll(id) {
var ids = $(id).val();
let options = $(id + " option");
let totalSelected = ids.length;
let totalOptions = options.length;
if (totalSelected >= totalOptions) {
return true;
} else {
return false;
}
}

Related

Create a Dynamic Checkbox Validation in Angular With Data from API

So I have a function that displays a list from an API:
displayEventTicketDetails() {
this.Service
.getEventTicketDetails().subscribe((data: any) => {
this.eventTicketDetails = data.map(ticket => ticket.ticket_name);
console.log(this.eventTicketDetails);
});
}
This is the result from the function above:
["Regular", "VIP", "Table", "Testing", "Cabana"]
Here is how the form array is declared:
ngOnInit() {
this.composeMessage = this.fb.group({
ticket: new FormArray([])
});
Then I use this function below to track if the check boxes are checked
onChange(event: any, isChecked: boolean){
const control = <FormArray>this.composeMessage.controls.ticket;
if(isChecked){
control.push(new FormControl(event))
} else{
const index = control.controls.findIndex(x => x.value === event);
control.removeAt(index)
}
}
Then finally in my ts file, here is my onsubmit function that submits the data on the form:
submitComposeMessage() {
this.submitted = true;
if (this.composeMessage.invalid) {
return;
}
const ticket = this.f.ticket.value;
this.Service
.createMessage(
ticket)
.subscribe(
(res: any) => {
if (res.err) {
this.toaster.errorToastr(res.message, null, { toastTimeout: 5000 });
return false;
}
this.toaster.successToastr(res.message, null, { toastTimeout: 5000 });
console.log("Message successfully created");
},
err => {
console.log(err);
}
);
}
So in my Html file here is my input field:
<ng-container *ngFor="let event of eventTicketDetails; let i = index" >
<label class="w-checkbox checkbox-field" >
<input
type="checkbox"
id="{{i}}"
name="checkbox-9"
class="w-checkbox-input checkbox"
(change)="onChange(event, $event.target.checked)"
[checked]="composeMessage.controls.ticket.value.indexOf(event)>=0">
<span class="no-margin w-form-label">{{event}}</span>
</label>
</ng-container>
With that loop, I'm able to get this result
So, I need help with two things:
1). I want all the checkbox to be checked by default when the page loads at first instance.
2). I want to validate the checkbox to ensure at least one checkbox is checked on submission.
I'll appreciate any help I can get.
If you want to only show validation message after submit, I would suggest the following, where we instead iterate the formarray in template, initially set all checked (as that is what you wish). We would listen to valueChanges of the formarray, but filter out as long as form is not submitted. We would introduce a new variable, for example isEmpty, which based on we would show/hide validation message. So all in all....
TS:
isEmpty = false;
submitted = false;
constructor(private fb: FormBuilder) {
const ctrls = this.eventTicketDetails.map(control => this.fb.control(true));
this.composeMessage = this.fb.group({
ticket: this.fb.array(ctrls)
});
this.tickets.valueChanges.pipe(
filter(() => !!this.submitted)
).subscribe((value) => {
value.some(x => x === true) ? this.isEmpty = false : this.isEmpty = true;
})
}
get tickets() {
return this.composeMessage.get("ticket") as FormArray;
}
onSubmit() {
this.submitted = true;
const selectedTickets = this.tickets.value
.map((checked, i) => (checked ? this.eventTicketDetails[i] : null))
.filter(value => !!value);
selectedTickets.length ? this.isEmpty = false : this.isEmpty = true
}
HTML:
<label formArrayName="ticket" *ngFor="let t of tickets.controls; index as i">
<input type="checkbox" [formControlName]="i">
{{eventTicketDetails[i]}}
</label>
<small *ngIf="isEmpty">Choose at least one checkbox</small>
STACKBLITZ
change Id to something like this
id="ticket{{i}}"
In this method write like this and call displayEventTicketDetails on ngOnit. This will check all the values:
displayEventTicketDetails() {
this.Service
.getEventTicketDetails().subscribe((data: any) => {
this.eventTicketDetails = data.map(ticket =>ticket.ticket_name);
setTimeout(() => {
for(var i= 0;i < this.evenTicketDetails.length ; i++){
var id = "ticket" + i;
(<HTMLInputElement>document.getElementById(id)).checked = true;
console.log(this.eventTicketDetails);
}, 500);
});
}
2. In submit method write something like this
submitComposeMessage() {
for(var i= 0;i < this.evenTicketDetails.length ; i++){
var id = "ticket" + i;
var resval = (<HTMLInputElement>document.getElementById(id)).value;
if(resval){
// this will check atleast one value is checked and if it true we are coming
out of the loop and performing other operations..
i = this.evenTicketDetails.length;
}
else{
// show error message or block from going forward..
}
});
}
This will solve your issues.

CheckBoxFor inside a loop -- On client, discover which box changed, and if it was checked or unchecked

I have a CheckBoxFor inside a loop....
#for (int i = 0; i < Model.Roles.Count; i++)
{
... Some hidden fields ...
<div>
<label class="control-label">
#Html.CheckBoxFor(m => Model.Roles[i].Selected, new { #class = "ModelCheckBox" })
#Model.Roles[i].Name
</label>
</div>
}
And then this:
$('.ModelCheckBox').change(function (e) {
alert("you changed a role");
});
The alert pops up just fine, but what I need to know is what box changed, and if it was checked or unchecked.
In Chrome debug I put a breakpoint so I could look at the contents of e, but it doesn't seem to contain any data about which box was checked.
you can get which checkbox change simply use e.target or this.
Example
$('.ModelCheckBox').change(function (e) {
var target=this;
//var target=e.target; // both are same.
if ($(target).is(':checked')) {
alert("checked");
}else{
alert("unchecked");
}
});
Got it. In the view, change this:
#Html.CheckBoxFor(m => Model.Roles[i].Selected, new { #class = "ModelCheckBox" })
to this:
#Html.CheckBoxFor(m => Model.Roles[i].Selected, new { #class = "ModelCheckBox", #data_role = Model.Roles[i].Name })
And then once we have the data attribute:
$('.ModelCheckBox').change(function (e, data) {
alert($(this).data('role') + " " + e.target.checked);
});

Preserve the hidden or visible state of initially hidden textbox on postback in mvc application

Given below is my script.My problem is I have a textbox which is hidden and is diplayed only when we select "other" from dropdownlist.On display when we enter a value after post back that value gets preserved but that textbox becomes invisible.on postback dropdown list value is however preserved and shown as "others" and only when I select someother value of dropdown and then again change it to "other" then textbox along with text gets displayed..how can I preserve that hidden or visible state of it on postback?
<script type="text/javascript">
$(document).ready(function () {
$('#SelectedCategoryId').change(function () {
if ($('#SelectedCategoryId').val() === '5') {
$('#other').show(1000);
$('#other').change(function () {
var SelectedCategory = $('#other').val().toString();
$('#hiddenId').val(SelectedCategory);
});
}
else {
$('#other').hide(1000);
var SelectedCategory = $('#SelectedCategoryId option:selected').text();
$('#hiddenId').val(SelectedCategory);
}
});
});
</script>
My View
<div id="dropdown" class="form-control dropdown">
#Html.ValidationMessageFor(m => m.SelectedCategoryId, "*")
#Html.LabelFor(m => m.Category, "Department :", new { style = "display:inline;" })
#Html.DropDownListFor(m => m.SelectedCategoryId, new SelectList(Model.Category, "Value", "Text"), "SelectCategory", new { id = "SelectedCategoryId"})
#Html.ValidationMessageFor(m => m.Other, "*")
#Html.TextBoxFor(m => m.Other, new { id = "other", #class = "other" ,style = "display: none;" })
#Html.HiddenFor(m => m.SelectedCategory, new { id = "hiddenId" })
</div>
that's becaue you only check for the value of the select on "change" event. That doesn't happen when you load the page. Do it like that:
function toggleHidden() { //that's your code in a function
if ($('#SelectedCategoryId').val() === '5') {
$('#other').show(1000);
$('#other').change(function () {
var SelectedCategory = $('#other').val().toString();
$('#hiddenId').val(SelectedCategory);
});
}
else {
$('#other').hide(1000);
var SelectedCategory = $('#SelectedCategoryId option:selected').text();
$('#hiddenId').val(SelectedCategory);
}
}
$(document).ready(function () {
toggleHidden(); //execute the toggle on load
$('#SelectedCategoryId').change(toggleHidden); //execute the toggle on change
});

Dropdownlist Change event with javascript, when using an EditorTemplate

I have an EditorTemplate - which works great. Inside it, I have a dropdownlist which i decorate with a Class, and 2 divs
<div>
#Html.DropDownListFor(m => m.Type, (SelectList)ViewData["TypeList"], "-- Select --", new { #class = "TypeSelector" })
#Html.ValidationMessageFor(m => m.Type)
</div>
<div class="EmailDiv">EmailStuffHere</div>
<div class="CalendarDiv">CalendarStuffHere</div>
Im trying to show the 1 of the 2 divs based on the selection of the dropdown list
the dropdownlist populates fine, as is shown as a dropdown list with 2 items "Calendar" and "Email"
I have the following Javascript:
function checkSelection() {
$(".EmailDiv").hide();
$(".CalendarDiv").hide();
var selectedItem = $(this).val();
if (selectedItem == "Email") {
$(".EmailDiv").show();
} else if (selectedItem == "Calendar") {
$(".CalendarDiv").show();
}
};
var myobject = new checkSelection();
$(document).ready(function () {
checkSelection();
$(".TypeSelector").change(checkSelection);
checkSelection.apply($(".TypeSelector"));
});
The javascript file loads (I can see it in my firefox debugger)
But doesn't get hit for some reason.
Either of the divs do not show.
What am i doing wrong?
Enclose the html for each item in a container to make it easier to select relative elements
<div class="container"> // add this or similar
<div>
#Html.DropDownListFor(m => m.Type, (SelectList)ViewData["TypeList"], "-- Select --", new { #class = "TypeSelector" })
#Html.ValidationMessageFor(m => m.Type)
</div>
<div class="EmailDiv">EmailStuffHere</div>
<div class="CalendarDiv">CalendarStuffHere</div>
</div>
and the css
.EmailDiv, .CalendarDiv {
display:none;
}
Then the script (in the main view)
$(document).ready(function () {
// Set initial visibility
$('.TypeSelector').each(function(index, item) {
var container = $(this).closest('.container');
if ($(this).val() == 'Calendar') {
container.find('.CalendarDiv').show();
} else if ($(this).val() == 'Email') {
container.find('.EmailDiv').show();
}
});
// Update visibiity on selection
$('.TypeSelector').change(function() {
var container = $(this).closest('.container');
if ($(this).val() == 'Calendar') {
container.find('.CalendarDiv').show();
container.find('.EmailDiv').hide();
} else if ($(this).val() == 'Email') {
container.find('.EmailDiv').show();
container.find('.CalendarDiv').hide();
} else { // this may or may not be necessary
container.find('.EmailDiv').hide();
container.find('.CalendarDiv').hide();
}
});
}

Select element has selected value -1

Select element has selected value 4 (for example), I send form data to the server. The controller return partial view.
<script>
$(document).ready(function () {
var objSel = document.getElementById("IDVacationApplicationType");
checkVacationType(objSel);
$("select#IDVacationApplicationType").change(function () {
checkVacationType(this);
});
});
function checkVacationType(elem) {
var item = $(elem).val();
alert(item);
}
</script>
html:
<div class="form-position">
<div class="form-label">
#Html.LabelFor(model => model.VacationApplicationTypes)
</div>
<div class="form-value">
#Html.DropDownListFor(model => model.IDVacationApplicationType, Model.VacationApplicationTypes)
#Html.ValidationMessageFor(model => model.VacationApplicationTypes)
</div>
</div>
alert shows -1. After that form has select element with selected value = 4. How can I get this 4?
Answer: I had two the same ID in the page.
You can use this
$('#IDVacationApplicationType').find(":selected").val();
So change your function as checkVacationType as
function checkVacationType(elem) {
var item = $(elem).find(":selected").val();
alert(item);
}
Fiddle Demo
I had two the same ID in the page.
I need add class to the element:
#Html.DropDownListFor(model => model.IDVacationApplicationType, Model.VacationApplicationTypes, new { #class = "IDVacationApplicationType" })
<script>
$(document).ready(function () {
var objSel = $(".IDVacationApplicationType");
checkVacationType(objSel);
$(".IDVacationApplicationType").change(function () {
checkVacationType(this);
});
});
function checkVacationType(elem) {
var item = $(elem).val();
alert(item);
}
</script>

Categories