Combines table filters in jquery - javascript

I have a table with different places, and implemented some simple buttons that allow you to filter the list. First filter is location (north, east, central, south, west) which is based on postcode. Another filter is on "impress". This shows you only the places that have have 4 or higher value in the column. Filters work great separately, but not together. The result that I am after is when I press "West" is shows me the places in "West, when I then click impress, I expect to see the places in west with a 4 or 5 score for impress.
JSFiddle here
$('.table td.postcode').each(function() {
var cellText = $(this).html();
var locationString = cellText.substring(0,2);
if (locationString.indexOf('W') > -1){
$(this).parent().addClass('west');
}
if (locationString.indexOf('C') > -1){
$(this).parent().addClass('central');
}
if (locationString.indexOf('E') > -1){
$(this).parent().addClass('east');
}
if (locationString.indexOf('S') > -1){
$(this).parent().addClass('south');
}
if (locationString.indexOf('N') > -1){
$(this).parent().addClass('north');
}
});
$("input[name='filterStatus'], select.filter").change(function () {
var classes = [];
$("input[name='filterStatus']").each(function() {
if ($(this).is(":checked")) {
classes.push('.'+$(this).val());
}
});
if (classes == "") {
// if no filters selected, show all items
$("#StatusTable tbody tr").show();
} else {
// otherwise, hide everything...
$("#StatusTable tbody tr").hide();
// then show only the matching items
rows = $("#StatusTable tr").filter(classes.length ? classes.join(',') : '*');
if (rows.size() > 0) {
rows.show();
}
}
});
$("input[name='impressStatus']").change(function(){
var classes = [];
$("input[name='impressStatus']").each(function() {
if ($(this).is(":checked")) {
classes.push('.'+$(this).val());
}
});
if(classes == ""){
$("#StatusTable tbody tr").show();
}
else{
$(".table td.impress").each(function(){
if($(this).data("impress") >= 4){
$(this).parent().show();
}
else{
$(this).parent().hide();
}
});
}
});
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--BUTTON FILTERS -->
<div class="btn-toolbar" role="toolbar" aria-label="...">
<div class="btn-group" style="" data-toggle="buttons">
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="north" autocomplete="off">North
</label>
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="east" autocomplete="off" class="radio">East
</label>
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="central" autocomplete="off" class="radio">Central
</label>
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="south"autocomplete="off" class="radio">South </label>
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="west" autocomplete="off" class="radio">West
</label>
</div><!-- button group -->
<label class="btn btn-primary outline">
<input type="checkbox" name="impressStatus" class="radio" aria-pressed="true" autocomplete="off">Impress her
</label>
</div><!-- btn toolbar-->
<!--TABLE -->
<table class="table" id="StatusTable">
<thead>
<tr>
<th data-sort="string" style="cursor:pointer">name</th>
<!-- <th>Description</th> -->
<th data-sort="string" style="cursor:pointer;">postcode</th>
<th data-sort="int" style="cursor:pointer;">price</th>
<th data-sort="int" style="cursor:pointer;">total</th>
<th data-sort="int" style="cursor:pointer;">impress</th>
<th colspan="4"></th>
</tr>
</thead>
<tbody>
<tr data-link="/places/1">
<td>Name of place 1</td>
<td class="postcode">NW1</td>
<td class="price" data-price='3'>3</td>
<td class="rating" data-rating='69'>69</td>
<td class="impress" data-impress='4'>4</td>
</tr>
<tr data-link="/places/2">
<td>Name of place 2</td>
<td class="postcode">E3</td>
<td class="price" data-price='4'>4</span></td>
<td class="rating" data-rating='89'>89</td>
<td class="impress" data-impress='5'>5</td>
</tr>
<tr data-link="/places/3">
<td>Name of place 3</td>
<td class="postcode">SW3</td>
<td class="price" data-price='2'>2</td>
<td class="rating" data-rating='51'>51</td>
<td class="impress" data-impress='3'>3</td>
</tr>
</tbody>
</table>
Code is probably not the most efficient, but it works :). Once I got this working, I want to add more filters.

(sorry for my bad english)
if these are the only filters you need, you can use two different type of filter:
hide via Javascript
hide via Css
if you use 2 types of filters the filters can work correctly without use a complex javascript code to manage a big number of different cases and combination:
I add a initial (on document load) control that check if a tr has the value impress cell >4, if has it add a new class: is_impress else add an other: no_impress.
$('.table td.impress').each(function(){
var _class = ($(this).data("impress") >= 4) ? "is_impress" : "no_impress";
$(this).parent().addClass(_class);
});
The code of filter by position is the same... but... I edit the filter by impress to add a class to table () when is active and take it off when isn't:
$("input[name='impressStatus']").change(function(){
(!$(this).is(":checked"))
? $("#StatusTable").removeClass("active_impress")
: $("#StatusTable").addClass("active_impress");
});
if the table has the class active_impress a css rules override the inline code of dispaly to hide all the row that haven't an impress >4:
#StatusTable.active_impress tr.no_impress{
display:none !important;
}
This type of filter override any other display modification until the checkbox stay checked.
I edit your fiddle:
https://jsfiddle.net/Frogmouth/gkba343L/1/
USE CSS to more filter
First change on load check, add price:
$('.table tbody tr').each(function(){
var _class = "";
_class += ($(this).find(".price").data("price") >= 2) ? "is_price " : "no_price ";
_class += ($(this).find(".impress").data("impress") >= 4) ? "is_impress " : "no_impress ";
console.log(_class);
$(this).addClass(_class);
});
Add an other handler to new filter:
$("input[name='priceStatus']").change(function(){
(!$(this).is(":checked"))
? $("#StatusTable").removeClass("active_price")
: $("#StatusTable").addClass("active_price");
});
add new selector to the css rule:
#StatusTable.active_impress tr.no_impress,
#StatusTable.active_price tr.no_price{
display:none !important;
}
This is the result:
https://jsfiddle.net/Frogmouth/gkba343L/3/
Optimize code to add more filter:
HTML filter button:
<label class="btn btn-primary outline">
<input type="checkbox" name="impress" class="cssFilter radio" aria-pressed="true" autocomplete="off">Impress her
</label>
use cssFilter to indicate that is a css filter button and use name attribute to define the name of the filter, than use this namespace into the css class:
.active_{name} .no_{name} .is_{name}
And use a generic handler:
$("input.cssFilter").change(function(){
var _name = $(this).attr("name");
console.log(_name);
(!$(this).is(":checked"))
? $("#StatusTable").removeClass("active_"+_name)
: $("#StatusTable").addClass("active_"+_name);
});
With this you can manage all the filter with an unique handler, remember to add the filter to onload check and the new selector for each new filter.
Fiddle:
https://jsfiddle.net/Frogmouth/gkba343L/4/

Related

get all td names associated with checked checkboxes and show in html input field

i am developing a quote generator. what i am trying to do is when the user select a feature it should display associated tfeature name in html input field with id features
here is what i have tried
html
<table class="table" id="table">
<thead class="thead-dark">
<tr>
<th scope="col"></th>
<th scope="col">Features</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="form-check">
<input class="form-check-input" name="product" value="300" type="checkbox" onclick="totalIt()">
<label class="form-check-label" for="exampleCheck1"></label>
</div>
</td>
<td>Homepage</td>
<td>Simplistic design with standard element</td>
</tr>
<tr>
<td>
<div class="form-check">
<input class="form-check-input" name="product" value="200" type="checkbox" onclick="totalIt()">
<label class="form-check-label" for="exampleCheck1"></label>
</div>
</td>
<td>Login</td>
<td>Standard Login with forgot password functionality</td>
</tr>
</tbody>
</table>
<div class="form-group">
input type="text" class="form-control" placeholder="Feature 1, Feature 2, ..." value="" id="features">
</div>
<input type="button" value="Get Selected" class="tble_submit" onclick="GetSelected()" />
so here when user select a checkbox the feature field like homepage, login should be displayed in html input field
here is updated jquery code
<script src="../js/checkbox-total.js"></script>
<script type="text/javascript">
$(".tble_submit").click(function() {
$('.table tr input[type="checkbox"]:checked').each(function() {
var abc = [];
var $row = $(this).closest('tr');
//used :not(:first-child) to skip first element (the checkbox td)
$('td:not(:first-child)', $row).each(function(i) {
abc.push($row.find('td:nth-child(2)').text());
})
$.each(abc, function(i, v) {
document.getElementById("features").value += v
})
});
});
</script>
but it is not working.
here when i select 2 features it should display homepage,login in input field but it shows description of login in input field
output - homepage,homepage,login,login
expected output - Homepage, Login
$(".tble_submit, input[name ='product']").click(function() {
var abc = []; //move the array to here
$('.table tr input[type="checkbox"]:checked').each(function() {
var $row = $(this).closest('tr');
//used :not(:first-child) to skip first element (the checkbox td)
$('td:nth-child(2)', $row).each(function(i) {
abc.push($(this).text());
});
});
document.getElementById("features").value = abc.join(',');
});

Display icon when at least one checkbox is checked

I display checkboxes in my table. Now when i check at least one checkbox, the icon must appear if not, it should be hidden. My icon is not hidden.
What am i doing wrong?
This is my code
<div class="row">
<div class="col-sm-12 ">
<a data-toggle="modal" id="btnAdd" data-target="#myModal" class="btn"> Add Items </a>
<i type="icon" class="fa fa-trash " ></i>
<div>
</div>
<table class="table" id="table">
<thead>
<tr>
<th><input type="checkbox" id="master"></th>
</tr>
</thead>
<tbody>
<td><input type="checkbox"></td>
//table data here
</tr>
#endforeach
</tbody>
</table>
var checkboxes = $("input[type='checkbox']"),
hideIcon = $("i[type='icon']");
checkboxes.click(function() {
hideIcon.attr("disabled", !checkboxes.is(":checked"));
});
You'll need to iterate through all your checkboxes on each click. Also, I would recommend using the prop function to check for the "checked" status. Then, to hide it, either use the hide function, or set the display property to hidden:
$("input[type='checkbox']").click(function() {
var atLeastOneChecked = false;
$("input[type='checkbox']").each(function(index) {
if ($(this).prop('checked'))
atLeastOneChecked = true;
});
if (atLeastOneChecked) {
$("i[type='icon']").show(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','inline-block'); //or set style explicitly
} else {
$("i[type='icon']").hide(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','none'); //set style explicitly
}
});

Checkboxes don't stay checked after pagination

Whenever I check a checkbox on a listing page, save it then go to page eg 2 (using pagination) and check something there and save it the checkbox on my first page is unchecked. I thought about using AJAX to save checked checkboxes to grails session but don't know how to do that - I'm beginner with JS and using views. Could someone help me out?
Here is the part with listing all companies and checkboxes in my gsp:
<g:form name="company-list-form" action="listCompany">
<div>
<g:textField id="search-field" name="query" value="${params.query}"/>
<span>
<g:checkBox id="only-blockades-box" name="onlyBlockades" class="submit-on-change" value="${params.onlyBlockades}" title="Pokaż tylko blokady"/>
<label for="only-blockades-box">Tylko blokady</label>
</span>
<g:actionSubmit value="${message(code: 'default.buttons.search', default: 'Szukaj')}" action="listCompany" class="button_orange"/>
<g:link action="listCompany" class="button_gray"><g:message code="default.buttons.clean" default="Wyczyść"/></g:link>
</div>
<div class="padding-top">
<table class="table_td company-list-table">
<tbody>
<tr class="gray2">
<th class="first">Id</th>
<th style="max-width: 100px;">Nazwa</th>
<th>Id Kontrahenta</th>
<th title="Dostęp do TPO">TPO</th>
<th style="width: 20px;" title="Dostawa bezpośrednio do magazynu">Dostawa bezpośrednio</th>
<th style="width: 20px;" title="Możliwość potwierdzania zamówień">Potwierdzanie zamówień</th>
<th style="width: 20px;" title="Możliwość importowania awizacji z XLS">Import z Excel</th>
<th style="width: 20px;" title="Możliwość awizowania zamówionych indeksów">Awizacja zam. indeksów</th>
<th style="width: 20px;" title="Możliwość awizowania tygodniowego">Awizacja tyg.</th>
<th style="width: 20px;" title="Dostęp jedynie do awizowania tygodniowego">Tylko awizacja tyg.</th>
<th title="Limit AGD przypadający na każdą kratkę okna prywatnego">AGD</th>
<th title="Limit rowerów przypadający na każdą kratkę okna prywatnego">Rowery</th>
<th>Blokady</th>
<th class="is-blocked-th">Zablokowany?</th>
</tr>
<g:each in="${companyInstanceList}" var="company" status="i">
<tr class="${(i % 2) == 0 ? 'even' : 'odd'} table_td_gray2 ${i + 1 == companyInstanceList?.size() ? 'last' : ''}">
<td class="first" style="text-decoration: underline;">
<g:link action="editCompany" id="${company?.id}">${company?.id}</g:link>
</td>
<td>
${company?.name}
</td>
<td>
${company?.idKontrahenta}
</td>
<td>
<g:checkBox name="tpoAccess.${company?.id}" id="tpo-access-${company?.id}"
checked="${company?.tpoAccess}"/>
</td>
<td>
<g:checkBox name="directDeliveryAvailable.${company?.id}"
id="direct-delivery-available-${company?.id}"
checked="${company?.directDeliveryAvailable}"/>
</td>
<td>
<g:checkBox name="accessToOrderConfirmation.${company?.id}"
id="access-to-order-confirmation-${company?.id}"
checked="${company?.accessToOrderConfirmation}"/>
</td>
<td>
<g:checkBox name="accessToXlsImport.${company?.id}"
id="access-to-xls-import-${company?.id}"
checked="${company?.accessToXlsImport}"/>
</td>
<td>
<g:checkBox name="accessToOrderedProductsAvisation.${company?.id}"
id="access-to-ordered-products-confirmation-${company?.id}"
checked="${company?.accessToOrderedProductsAvisation}"/>
</td>
<td>
<g:checkBox name="accessToLimitedAvisation.${company?.id}"
id="access-to-limited-avisation-${company?.id}"
checked="${company?.accessToLimitedAvisation}"/>
</td>
<td>
<g:checkBox name="accessOnlyToLimitedAvisation.${company?.id}"
id="access-only-to-limited-avisation-${company?.id}"
checked="${company?.accessOnlyToLimitedAvisation}"/>
</td>
<td>
<input type="text" name="agdPrivateWindowLimit.${company?.id}"
value="${company?.agdPrivateWindowLimit}"
class="shortText" id="agd-private-window-limit-${company?.id}"
onchange="validateLimits('agdPrivateWindowLimit.${company?.id}')">
</td>
<td>
<input type="text" name="bicyclePrivateWindowLimit.${company?.id}"
value="${company?.bicyclePrivateWindowLimit}"
class="shortText" id="bicycle-private-window-limit-${company?.id}"
onchange="validateLimits('bicyclePrivateWindowLimit.${company.id}')">
</td>
<td>
<g:link class="button_gray" controller="productGroup" action="list" params="[companyId: company?.id, query: params.query ?: '']">
Blokady
</g:link>
</td>
<td>
<g:if test="${company?.findBlockades()}">
<span title="Dostawca ma aktywne blokady grup towarowych." class="bold large">
✓
</span>
</g:if>
</td>
</tr>
</g:each>
</tbody>
</table>
</div>
<div class="paginateButtons">
<g:paginate controller="company" action="listCompany" total="${companyInstanceTotal}"
params="[query: params.query ?: '']"/>
</div>
<div style="float:right;">
<g:link action="createCompany" class="button_orange">
<g:message code="default.button.create.label" default="Utwórz"/>
</g:link>
<g:actionSubmit action="updateCompanies" name="companyListSubmit" class="button_orange" value="Zapisz"/>
</div>
</g:form>
Here is my javascript file associated with that view:
function validateLimits(name) {
document.getElementsByName(name)[0].value = document.getElementsByName(name)[0].value.replace(/[A-Za-z!##$%^&*" "]/g, "");
var quantity = document.getElementsByName(name)[0].value;
var toBeAvised = 9999;
if (quantity.indexOf(',') > -1 || quantity.indexOf('.') > -1 || /*quantity == "" ||*/ isNaN(quantity)) {
alert("Limit musi być liczbą całkowitą");
document.getElementsByName(name)[0].value = '';
} else if (parseInt(quantity) > toBeAvised) {
alert("Podana liczba jest większa niż maksymalny limit równy " +toBeAvised + ".");
document.getElementsByName(name)[0].value = '';
} else if (parseInt(quantity) < 0) {
alert("Limit musi być liczbą dodatnią!");
document.getElementsByName(name)[0].value = '';
}
}
And here is controller method (listCompany):
def listCompany(Integer max) {
Person person = Person.read(springSecurityService.principal.id)
Company comp = person?.company
params.max = Math.min(max ?: 25, 100)
params.offset = params.offset ?: 0
params.readOnly = true
String q = (params.query as String)?.toLowerCase() ?: ""
def query = Company.where {
id != comp?.id
name =~ "%$q%" || idKontrahenta as String =~ "%$q%"
if (params.onlyBlockades == "on") {
id in ProductGroupBlockade.findAllByCompanyIsNotNullAndEnabled(true)*.companyId
}
}
List<Company> companyInstanceList = query.list([max: params.int("max"), offset: params.int("offset"), sort: "name"])
Integer count = query.count()
if (flash.message) {
params.errors = flash.message
}
[companyInstanceList: companyInstanceList, companyInstanceTotal: count, companySaved: params.companySaved, errors: params.errors]
}
How I could fix that so my checkboxes stay checked after saving? Right now they become unchecked whenever I go to next page and save some checkboxes there.
I tend to use DataTables for situations like this but it depends on the amount of data you're dealing with to how you go about it.
If you have a relatively small data set, say 1000 rows or fewer you can use a plain DataTable, if you have more than this then you may want to use a server side processing DataTable.
Using a DataTable you would do away with all the Grails pagination, give your table an ID and just create the table in javascript like:
<script type="text/javascript">
$(document).ready( function() {
$( '#companyListTable' ).DataTable();
} );
</script>
All the pagination is handled in javascript and check boxes are preserved when navigating through the table pagination.
The reason is that you need to build your own search parameters to be sent with pagination:
<g:paginate total="${instanceTotal}" params="${search}" />
a similar post can be found here with more details of how you build this search params included as links as a form of comment within it.
Edited to add if you wantd to actually ammend pagination yourself by checking additional stuff through jquery i.e.
var something = $('#somFIeld').val()
and adding something through javascript to current pagination instead then take a read of this answer

radio button in a table checked and unchecked

I have a radio button in table and I want to implement select all functionality for radio button based on name. This is my code:
var checked = false;
$scope.acceptOrRejectAllOrders = function(selectedVal) {
if (selectedVal == 'Accept all') {
jQuery("#bundleAcceptAll").attr('checked', 'checked');
// $("#bundleAcceptAll").prop("checked", true);
//$("#bundleAcceptAll").attr('checked', 'checked');
var aa = document.getElementsByName("bundleAcceptAll");
for (var i = 0; i < aa.length; i++) {
document.getElementsByName(bundleAcceptAll).checked = true;
}
//$scope.quoteRequest.quotationRequestItems[0].quotes.length
} else {
}
};
<div style="border:1px #f5f4f4 solid;background: #f9f9f9;" ng-repeat="(key,quoteAndOrder) in getQuotesAndOrders()">
<div style="background: #fff;">
<table border="0" style="width: 100%;" class="table table-striped">
<thead>
<tr style="background: #ff7900;color: #fff;">
<th>Quote ID</th>
<th>{{key}}</th>
</tr>
<tr>
<th>Accept or Reject Orders:</th>
<th>
<span style="float: left;background: #f9f9f9;">
<input type="radio" name ="bundleAcceptAll" ng-change="" class="radioSignatory" value="Approve Order" ng-disabled="">
<p class="labelRadioSignatory">Approve Order</p>
<input type="radio" name ="bundleRejectAll" ng-change="" class="radioSignatory" value="Reject Order" ng-disabled="">
<p class="labelRadioSignatory">Reject Order</p>
</span>
</th>
</tr>
</thead>
<tr ng-repeat="odr in quoteAndOrder">
<td> {{odr.id}} </td>
<td>{{odr.status}}</td>
</tr>
</table>
<hr>
</div>
</div>
I am not able to select all radio buttons with name bundleAcceptAll. It is basically a list in which each row will have a radio button. I want all radio buttons in the list to be selected. Only one button gets selected
AFAIK if you choose radio button and use the same name it will treated as group that will only one item selected. Perhaps you could just change it into checkbox.
function oncheckClick()
{
$('input[name=chkBox]').prop('checked',true)
}
function onUnCheckClick()
{
$('input[name=chkBox]').prop('checked',false)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="chkBox">
<button id="check" onclick="oncheckClick()" value="Check">Check</button>
<button id="check" onclick="onUnCheckClick()" value="UnCheck">UnCheck</button>
if it is list, you can loop through the list and check or uncheck
$("input[type=radio][name='" + name + "']").each(function() {
//code here
});
As was mentioned above, it's not radio button functionality to have multiple items checked, it's checkboxes. But you can style checkboxes so they would look like radiobuttons. See for example: How to make a checkbox in circle shape with custom css?

Conditional validation for a form inputs

Starting off there is a append button that generates a row with 1 select box, 1 inputbox, and 4 checkboxes. The limit of adding this would be 1-10 rows at max. I have no idea how to make a jquery validation using for example http://formvalidation.io/ - or a standalone jquery code. The rules I would like to apply:
If the role chosen is user (not an admin) , I must validate that there is at least one checkbox checked and the user doesn't appears twice in the selections
The thing is I don't even know where to start from, can you point me any hints?
Live example :: http://jsfiddle.net/Yy2gB/131/
Append method onClick
$(document).ready(function(){
var obj = {"1":"Admin istrator","2":"User2"};
//$('.selectpicker').selectpicker();
$(".addCF").click(function(){
count = $('#customFields tr').length + 1;
var sel = $('<select name="user'+count+'">');
for(key in obj){
// The key is key
// The value is obj[key]
sel.append($("<option>").attr('value',key).text(obj[key]));
}
$('.selectpicker').selectpicker();
$("#customFields").append('<tr><td>'+sel[0].outerHTML
+'</td><td><input class="form-control" class="valid_role"'
+' data-fv-field="emails" type="text" name="role'+count
+'" /></td><td><input type="checkbox" class="mycheckbox"'
+' name="can_edit'+count+'"></td><td><input type="checkbox" '
+'class="mycheckbox" name="can_read'+count+'"></td><td><input '
+'type="checkbox" class="mycheckbox" name="can_execute'+count+'">'
+'</td><td><input type="checkbox" class="mycheckbox" '
+'name="is_admin'+count+'"></td><td><a href="javascript:void(0);"'
+'class="remCF">Remove</a></td></tr>');
$('.mycheckbox').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue'
});
$('.selectpicker').selectpicker();
});
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});
HTML Form
<div class="col-md-12 col-lg-12">
<table class="table table-user-information" id="customFields">
<thead>
<tr>
<th class="standardTable_Header">User</th>
<th class="standardTable_Header">Role</th>
<th class="standardTable_Header">
<span title="administrator projektu">Can read</span>
</th>
<th class="standardTable_Header">
<span title="uprawnienie do edycji danych projektu">
edit
</span>
</th>
<th class="standardTable_Header">
<span title="uprawnienie do odczytu danych projektu oraz przypisanych do niego zadań">
excute
</span>
</th>
<th class="standardTable_Header">
<span title="uprawnienie do edycji danych projektu">
admin
</span>
</th>
</tr>
</thead>
<tbody>
<button type="button" class="btn btn-default addCF">
Append
</button>
</div>
</tbody>
</table>
Using this jQuery Validation Plugin and through this demo, We could do the following:
Assumption: Roles check boxes must have at least one checked if - and only if - the select tag have the value User2
1- wrap your table with form tag that has a submit button:
<div class="col-md-12 col-lg-12">
<form id="myform">
<table class="table table-user-information" id="customFields">
...
</table>
<input type="submit" value="submit" />
</form>
</div>
2- We need to edit the checkboxes html to make them all have the same name but with different values, for example:
<input type="checkbox" class="mycheckbox" name="ourRoles" value="can_edit' ...>
<input type="checkbox" class="mycheckbox" name="ourRoles" value="can_read' ...>
and so on.
3- Add the following script:
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("#myform").validate({
rules: {
ourRoles: {
required: function () {
if ($("select[name=user2]").val() == 2) {
return true;
} else {
return false;
}
}
}
}
});
See all together with this fiddle

Categories

Resources