Check All Checkbox on SubCheckbox - javascript

I have WebGrid on MVC project with two WebGrid column. The first column collapses the sub-data and the other column is for checkbox.
This checkbox will check all checkbox on its subdata. The problem is I cannot select all the data on its sub-checkbox. This is my sample code:
//This colum will generate checkbox for the main data
wbclCol.Add(new WebGridColumn
{
ColumnName = "",
Header = "",
CanSort = false,
Format = (objChildItem) =>
{
StringBuilder strbHtml = new StringBuilder();
strbHtml.Append("<input class='obj-parmain' name='lngID' value='" + objChildItem.lngPARID + "' data-pardata='" + objChildItem.lngID+ "' data-show='True' type='checkbox' ></input>");
return new MvcHtmlString(strbHtml.ToString());
}
});
//This column will generate another column for the sub-data:
wbclCol.Add(new WebGridColumn
{
ColumnName = "",
Header = "",
CanSort = false,
Format = (objChildItem) =>
{
StringBuilder strbHtml = new StringBuilder();
strbHtml.Append("<input class='obj-parsub' name='lngID' value='" + objChildItem.lngPARID + "' data-pardata='" + objChildItem.lngID+ "' data-show='True' type='checkbox' ></input>");
return new MvcHtmlString(strbHtml.ToString());
}
});
This is my javascript to select all checkbox on class: obj-parsub when my checkbox with class: obj-parmain is check
function fncParMainCheck() {
$(document).off('click', '.obj-parmain');
$(document).on('click', '.obj-parmain', function (e) {
var blIsCheck = $(this).is(':checked');
if (blIsCheck) {
//var objNext = $('.obj-parsub').nextAll();
//var objNextMain = $(this).siblings().nextAll().find('.obj-parsub');
//var objNextMain = $(this).closest('.obj-parmain').find('.obj-parsub').prop('checked', this.checked);
$(this).closest('.obj-parmain').find('.obj-parsub').parent().parent().nextAll().prop('checked', this.checked);
//$(objNextMain).prop('checked', blIsCheck);
}
});
}

try with this code. first you check your checkbox is checked or not.
$(document).on('change', '.obj-parmain', function (e) {
if ($(this).is(':checked')){
$('input:checkbox.obj-parsub').prop('checked', $(this).prop('checked'));
}
else{
// uncheck logic
}
});

Try like this
$(document).on('change', '.obj-parmain', function (e) {
$('.obj-parsub input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});

If you encounter the same problem, this works pretty well:
function fncParMainCheck() {
$(document).off('click', '.obj-parmain');
$(document).on('click', '.obj-parmain', function () {
var blIsCheck = $(this).is(':checked');
if (blIsCheck) {
//This will look for the sublist of checkbox that is under class name obj-parsub and checks everything
var objNext = $(this).parent().parent().find('.obj-parsub');
$(objNext).prop('checked', blIsCheck);
}
});
}

Related

localStorage returns wrong value for checkbox

I am using local storage to restore data incase a user accidentally reloads the page, but when they reload a checkbox is checked even when they did not check it.
Below is my code, the only wrong value that's being rendered is the checkbox. I have other fields which value the are being restored are accurate upon reload of the page.
I think I am missing one thing, or two, any help would be really appreciated. Thanks.
var remember_state = {
name: "rememberState",
clearOnSubmit: true,
_defaultNoticeDialog: function() {
return $("<p />", { "class": "remember_state" })
.html('Restore previously entered information? <a class="btn btn-sm btn-link" href="#"><i class="mrx far fa-history"></i>Restore</a>');
},
noticeConfirmSelector: "a",
noticeSelector: ".remember_state",
use_ids: false,
objName: false,
restoreState: function(e) {
var data = JSON.parse(localStorage.getItem(this.objName)),
$f = this.$el,
$e;
for (var i in data) {
$e = $f.find("[name=\"" + data[i].name + "\"]");
if ($e.is(":radio")) {
$e.filter("[value=\"" + data[i].value + "\"]").prop("checked", true);
}
else if ($e.is(":checkbox") && data[i].value) {
$e.prop("checked", true);
}
else if ($e.is("select")) {
$e.find("[value=\"" + data[i].value + "\"]").prop("selected", true);
}
else {
$e.val(data[i].value);
}
$e.change();
}
this.noticeDialog.remove();
e && e.preventDefault && e.preventDefault();
},
cancelNotice: function(e) {
e.preventDefault();
this.noticeDialog.remove();
},
chooseStorageProp: function() {
if (this.$el.length > 1) {
if (console && console.warn) {
console.warn("WARNING: Cannot process more than one form with the same" +
" object. Attempting to use form IDs instead.");
}
this.objName = this.$el.attr("id");
}
},
errorNoID: function() {
if (console && console.log) {
console.log("ERROR: No form ID or object name. Add an ID or pass" +
" in an object name");
}
},
saveState: function(e) {
var instance = e.data.instance;
var values = instance.$el.serializeArray();
// jQuery doesn't currently support datetime-local inputs despite a
// comment by dmethvin stating the contrary:
// http://bugs.jquery.com/ticket/5667
// Manually storing input type until jQuery is patched
instance.$el.find("input[type='datetime-local']").each(function() {
var $i = $(this);
values.push({ name: $i.attr("name"), value: $i.val() });
});
values = instance.removeIgnored(values);
values.length && internals.setObject(instance.objName, values);
},
save: function() {
var instance = this;
if (!this.saveState) {
instance = this.data(remember_state.name);
}
instance.saveState({ data: { instance: instance } });
},
bindNoticeDialog: function() {
if (!this.noticeDialog || !this.noticeDialog.length || !this.noticeDialog.jquery) {
this.noticeDialog = this._defaultNoticeDialog();
}
this.noticeDialog.on("click." + this.name, this.noticeConfirmSelector, $.proxy(this.restoreState, this));
this.noticeDialog.on("click." + this.name, this.noticeCancelSelector, $.proxy(this.cancelNotice, this));
},
setName: function() {
this.objName = this.objName || this.$el.attr("id");
if (!this.objName) { this.errorNoID(); }
},
init: function() {
this.bindNoticeDialog();
this.setName();
if (!this.objName) { return; }
this.bindResetEvents();
this.createNoticeDialog();
$(window).bind("unload." + this.name, { instance: this }, this.saveState);
}
};
EDIT:
I did a console.log on the in the for loop and the value of console.log(data.value[i]) at $e.is(":checkbox") is 0
We are using the jquery library jquery_remember_state and my problem was a bug they had where similar names of checkboxes would return the same value even if they had different values. We are using simple_form and it adds a hidden value for checkbox so it would give us the bug when trying to restore state.
The change I had to make was this:
if ($e.is(":checkbox") && data[i].value) {
$e = $e.filter("[value=\"" + data[i].value + "\"]");
if ($e.length) {
$e.prop("checked", true);
}
}
Here's the file with the full code incase anyone ever experiences this problem:
https://github.com/RepairShopr/jquery_remember_state/blob/multiple-checkboxes/source/javascripts/jquery.remember-state.js

Get Multiple Values with comma separated Using PHP and JavaScript

Hello I am new in PHP and JavaScript. I have a code of Dropdown Checkbox. I want to try get out values of checked options with comma separate like 1,2,3
My problem is that when i run my code my output have one extra comma at the end like 1,2,3, and my desired output is 1,2,3
Here is my code
HTML Part
<select id="agency" multiple="multiple">
<?php
if (is_array($rating_agencies) && !empty($rating_agencies)) {
foreach ($rating_agencies as $rating_agencie) {
echo '<option value="'.$rating_agencie->ID.'"';
echo '>';
echo $rating_agencie->name;
echo '</option>';
}
}
?>
</select>
<input type="button" id="btnSelected" value="Get Selected" />
Java Script
<script type="text/javascript">
$(function () {
$('#agency').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#agency option:selected");
var message = "";
selected.each(function () {
message += $(this).val() + ",";
});
alert(message);
});
});
</script>
Use jQuery.map with Array#join
.get() will return basic-array instead of array-of-objects
$(function() {
$('#agency').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function() {
var message = $("#agency option:selected").map(function() {
return this.value;
}).get();
alert(message.join(','));
});
});
Use slice to remove the last comma.
$('#btnSelected').click(function () {
var selected = $("#agency option:selected");
var message = "";
selected.each(function () {
message += $(this).val() + ",";
});
message = message.slice(0, -1);
alert(message);
});
This is your question solution, OR you can go with #Rayon.
Use slice function :
<script type="text/javascript">
$(function () {
$('#agency').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#agency option:selected");
var message = "";
selected.each(function () {
message += $(this).val() + ",";
});
message = message.slice(0, -1);
alert(message);
});
});
</script>
Try to get the value instead of option:selected, It may work for you
var selected = $("#agency").val();
use rtrim method in php
// $commaString = "1,2,3,";
$string = rtrim($commaString,",");
// output
// 1,2,3
in Javascript
var comma_string = "1,2,3,";
string = comma_string.replace(/,+$/,'');
You can use in either side as your logic.
Just use $rating_agencies = array_filter($rating_agencies) before your "if" statement.

Cascading DropDownList is not Populating MVC

I have two drop down lists setup in an MVC view as follows:
#Html.DropDownListFor(model => model.Market,
new SelectList(ListInfo.Markets(), "Name", "Name"), "Markets..."
, new { #class = "form-control", #id = "MarketSelect" })
<select id="StationSelect" name="SelectedStations" class="chosen-select form-control" multiple></select>
The form beings with:
#using (Html.BeginForm("CreateEvent", "Event", FormMethod.Post, new { role = "form", id = "EventForm", data_stationListAction = #Url.Action("StationList") }))
The following script is called at the bottom of the view with:
<script src="#Url.Content("~/Scripts/marketStation.js")"></script>
$(function () {
$('#MarketSelect').change(function () {
var URL = $('#EventForm').data('stationListAction');
$.getJSON(URL + '/' + $('#MarketSelect').val(), function (data) {
var items = '<option>Stations</option>';
$.each(data, function (i, station) {
items += "<option value='" + station.Value + "'>" + station.Text + "</option>";
});
$('#StationSelect').html(items);
$("#StationSelect").trigger("liszt:updated");
$("#StationSelect").change();
});
});
});
Finally, I have a Controller Action as follows:
public ActionResult StationList(string market) {
string Market = market;
var stations = from s in ListInfo.Stations()
where s.MarketName == Market
select s;
if(HttpContext.Request.IsAjaxRequest())
{
return Json(new MultiSelectList(
stations.ToArray(),
"SalemOrgObjID",
"Name"),
JsonRequestBehavior.AllowGet);
}
return RedirectToAction("CreateEvent");
}
ListInfo.Stations looks like this:
public static IQueryable<StationData> Stations(){
return db.Stations.ToList().AsQueryable();
}
The first Drop Down List is Populating Fine (MarketSelect), but once a Market is selected, the Station List is not populated.
Any help is greatly appreciated.
.trigger() needed to be changed to .trigger("chosen:updated");

How to get system properties __CreatedAt, __Version in javascript backend of Azure Mobile services?

I am trying to explicitly get the system properties from my table but it is not working. I can see that the URL is returning all the data including these fields if I use https://myservice.azure-mobile.net/tables/todoitem?__systemProperties=* but on the code I cannot get it as item.__version or item.version. I have tried adding todoitemtable = WindowsAzure.MobileServiceTable.SystemProperties.All; but no success! I have also looked at http://azure.microsoft.com/en-us/documentation/articles/mobile-services-html-validate-modify-data-server-scripts/ but this is adding a new column instead of using the existing system columns.
$(function() {
var client = new WindowsAzure.MobileServiceClient('https://ib-svc-01.azure-mobile.net/', 'key');
var todoItemTable = client.getTable('todoitem');
// = WindowsAzure.MobileServiceTable.SystemProperties.All;
// Read current data and rebuild UI.
// If you plan to generate complex UIs like this, consider using a JavaScript templating library.
function refreshTodoItems() {
var query = todoItemTable.where({ complete: false });
query.read().then(function(todoItems) {
var listItems = $.map(todoItems, function(item) {
return $('<li>')
.attr('data-todoitem-id', item.id)
.append($('<button class="item-delete">Delete</button>'))
.append($('<input type="checkbox" class="item-complete">').prop('checked', item.complete))
.append($('<div>').append($('<input class="item-text">').val(item.id))
.append($('<span class="timestamp">'
+ (item.createdAt && item.createdAt.toDateString() + ' '
+ item.createdAt.toLocaleTimeString() || '')
+ '</span>')));
});
$('#todo-items').empty().append(listItems).toggle(listItems.length > 0);
$('#summary').html('<strong>' + todoItems.length + '</strong> item(s)');
}, handleError);
}
function handleError(error) {
var text = error + (error.request ? ' - ' + error.request.status : '');
$('#errorlog').append($('<li>').text(text));
}
function getTodoItemId(formElement) {
return $(formElement).closest('li').attr('data-todoitem-id');
}
// Handle insert
$('#add-item').submit(function(evt) {
var textbox = $('#new-item-text'),
itemText = textbox.val();
if (itemText !== '') {
todoItemTable.insert({ text: itemText, complete: false }).then(refreshTodoItems, handleError);
}
textbox.val('').focus();
evt.preventDefault();
});
// Handle update
$(document.body).on('change', '.item-text', function() {
var newText = $(this).val();
todoItemTable.update({ id: getTodoItemId(this), text: newText }).then(null, handleError);
});
$(document.body).on('change', '.item-complete', function() {
var isComplete = $(this).prop('checked');
todoItemTable.update({ id: getTodoItemId(this), complete: isComplete }).then(refreshTodoItems, handleError);
});
// Handle delete
$(document.body).on('click', '.item-delete', function () {
todoItemTable.del({ id: getTodoItemId(this) }).then(refreshTodoItems, handleError);
});
// On initial load, start by fetching the current data
refreshTodoItems();
});
I was trying to access the system properties from within the API scripts and found this and thought it was useful and relevant: http://www.brandonmartinez.com/2014/10/22/retrieve-system-properties-in-azure-mobile-services-javascript-backend/
Basically you can do this (example from the post):
myTable.read({
systemProperties: ['__createdAt', '__updatedAt'],
success: function(tableEntries) {
// So on and so forth
}
}

perform a search of database with multiple textboxes

I'm trying to perform a search of database when user enters a persons name into textbox. The texboxes are dynamic, so whenever the user enters a number into the "No. of firemen on scene" textbox as seen in the snap shot below, the same amount of textboxes appear in the fieldset below under("List of firemen on scene").
However, my problem is that whenever I'm trying to perform the search, the search is only performed on the first textbox and not on the others. Could anyone assist me as to highlighting and/or explaining what the problem(s) may be?
occurrence.php
<label>List of Firemen On Scene</label><br>
<div class="NewlyCreatedSelectBoxes" name="firemen_list"></div>
search.php
<?php
require('connectdb.php');
if(isset($_POST['search_term']))
{
$search_term = mysql_real_escape_string(htmlentities($_POST['search_term']));
if(!empty($search_term))
{
$search = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName` FROM `firefighterinfo` WHERE `firstName` LIKE '%$search_term%'");
$result_count = mysql_num_rows($search);
$suffix = ($result_count != 1) ? 's' : '';
echo '<p>Your search for ', $search_term, ' returned ', $result_count, ' result', $suffix, '</p>';
while($results_row = mysql_fetch_assoc($search))
{
echo '<p>', $results_row['firstName'], ' ', $results_row['middleName'], ' ', $results_row['lastName'], '</p>';
}
}
}
?>
search.js
function firemanAddingTextBoxes() {
var NumOfText = $("#NumOfTextBoxes").val();
$('.NewlyCreatedSelectBoxes').empty();
var txtBox = "";
for (i = 0; i < NumOfText; i++) {
txtBox += '<input type="text" name="fireman[]" id="search" required/><br>';
}
$('.NewlyCreatedSelectBoxes').append(txtBox);
$('#search').keyup(function () {
var search_term = $(this).val();
$('#search_results').html('Searching database...');
if (search_term !== '') {
$.post('php/fireman_search.php', { search_term: search_term }, function (data) {
$('#search_results').html(data);
});
} else {
$('#search_results').html('Not Found');
}
});
return false;
}
Since the other field is dynamic, you'll need to use event delegation on the search inputs. Also, you're adding elements with duplicate ID's, which is bad. ID's have to be unique, just use classes for this:
for (i = 0; i < NumOfText; i++) {
txtBox += '<input type="text" name="fireman[]" class="search" required/><br>';
}
Change:
$('#search').keyup(function () {
To:
$(".NewlyCreatedSelectBoxes").on("keyup", ".search", function() {

Categories

Resources