Jquery validation plugin rule - javascript

I need help in writing the jquery validation rule (i am using Jquery Validation Plugin) for following scenario.
Below is scenario...
Based on first dropdown value, second dropdown will be enabled. And we need to make selection from second dropdown and add it to table using Add button.
Validation rule should be like below.
If first dropdown selection enabled the second dropdown, but non of the value from second dropdown is added to table (i mean table is empty), then we need to show error message against second dropdown while hitting submit button in the form.
I tried adding attr like "data-rule-{addmethod_rulename}" to second dropdown and wrote custom addmethod rule using first dropdown value and table size, but it is not working.
JSP code:
<form ....>
:
:
:
<b:form-group label="${firstdropdown}" labelFor="firstdropdown" cssBody="col-sm-2" cssClass="required">
<form:select path="firstdropdown" name="firstdropdown" class="form-control" required="required">
<form:option value="" label=""/>
<form:options items="${firstdropdownvalues}"/> {This items has two values - One will disable below dropdown and another will enable}.
</form:select>
</b:form-group>
:
:
:
<b:form-group label="${seconddropdown}" labelFor="seconddropdown" cssBody="col-sm-4" cssClass="required">
<div class="form-inline">
<select name="seconddropdown" class="form-control" disabled>
<option value=""></option>
<c:forEach items="${values}" var="dropdown">
<option value="${dropdown.name}">${dropdown.name}</option> {This items will have several values - we can select one by one and add it to below table using this addsite button}.
</c:forEach>
</select>
<button id="addbtn" type="button" class="btn btn-primary" disabled><spring:message code="form.button.platform.addbtn"/></button>
</div>
</b:form-group>
:
:
:
<b:form-group cssBody="col-sm-6">
<table id="pfmtable" class="table table-striped table-bordered dt-responsive">
<thead>
<tr>
<th><input name="select_all" type="checkbox"/></th>
<th>Sites</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</b:form-group>
:
:
:
</form>
Javascript code:
jQuery.validator.addMethod("isadded", function(value, element) {
return $('#firstdropdown').val() == 'Enable_Value' && $("#pfmtabletr").length > 0;
}, "* Atleast one site should be selected");
$('button:submit').click(function(){
var name = $('#name').val();
var $form = $('form');
$form.validate({
rules:{
seconddropdown: {isadded: true}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},

Related

jquery datatable edit table row data using form

var tb = $('#example').DataTable();
$('#addRow').on('click', function() {
var typeName = $("#type option:selected").val();
var amount = $("#amount").val();
tb.row.add([typeName, amount]).draw();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<label>Type</label>
<select id="type">
<option> Type 01</option>
<option> Type 02</option>
</select>
<label>Amount</label>
<input type="text" id="amount" />
<button id="addRow"> Add </button>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Type</th>
<th>Amount</th>
</tr>
</thead>
</table>
i need to append edit and delete button for every row. when click the edit button, row data should load to dropdown and textbox. can u guide me to do this ?
With certain changes to the architecture of your app, I would suggest the following approach that employs native DataTables options and API methods:
//initialize DataTable
const tb = $('#example').DataTable({
//remove non-essential controls for the sake of cleaner view
dom: 't',
//use columns option to setup header titles
columns: [
{title: 'Type'},
{
title: 'Amount',
//user 'render' to append Edit/Delete buttons for each entry
render: data => `${data}<button action="delete">Delete</button><button action="edit">Edit</button>`
}
]
});
//click handler for dual purpose 'Submit' button that adds new rows and submits edits
$('#submit').on('click', function() {
//when submit button acts to append new row to the table (default)
if($(this).attr('action') == 'addRow'){
tb.row.add([$("#type").val(), $("#amount").val()]).draw();
}
//when submit button acts to submit edits
if($(this).attr('action') == 'confirmEdit'){
//change affected row data and re-draw the table
tb.row($(this).attr('rowindex')).data([$("#type").val(), $("#amount").val()]).draw();
}
//clean up form, switch it to default state
$('#type').val("");
$('#amount').val("");
$('#submit').attr('action', 'addRow');
});
//'Delete' button click handler
$('#example').on('click', 'tbody tr button[action="delete"]', function(event){
tb.row($(event.target).closest('tr')).remove().draw();
});
//'Edit' button click handler
$('#example').on('click', 'tbody tr button[action="edit"]', function(){
//get affected row entry
const row = tb.row($(event.target).closest('tr'));
//get affected row().index() and append that to 'Submit' button attributes
//you may use global variable for that purpose if you prefer
$('#submit').attr('rowindex', row.index());
//switch 'Submit' button role to 'confirmEdit'
$('#submit').attr('action', 'confirmEdit');
//set up 'Type' and 'Amount' values according to the selected entry
$('#type').val(row.data()[0]);
$('#amount').val(row.data()[1]);
});
tbody tr button {
display: block;
float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<label>Type</label>
<select id="type">
<option value="" selected></option>
<option value="Type 01">Type 01</option>
<option value="Type 02">Type 02</option>
</select>
<label>Amount</label>
<input type="text" id="amount" />
<button id="submit" action="addRow">Submit</button>
<table id="example" class="display" cellspacing="0" width="100%"></table>
Add your HTML directly. I've added button, you can similarly add a drop down too. Consider the following:
var tb = $('#example').DataTable();
$('#addRow').on('click', function() {
var typeName = $("#type option:selected").val();
var amount = $("#amount").val();
var row = tb.row.add([typeName, amount, "<span><button>Edit</button><button>Delete</button></span>"]).draw();
var edit = row.node().getElementsByTagName("button")[0];
edit.onclick = function() {
document.getElementById('typeEdit').value = row.data()[0];
document.getElementById('amtEdit').value = row.data()[1];
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<label>Type</label>
<select id="type">
<option> Type 01</option>
<option> Type 02</option>
</select>
<label>Amount</label>
<input type="text" id="amount" />
<button id="addRow"> Add </button>
<br/ >
<br/ >
Edit Type
<select id="typeEdit">
<option> Type 01</option>
<option> Type 02</option>
</select>
Edit Amount
<input id="amtEdit" />
<br/ >
<br/ >
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Type</th>
<th>Amount</th>
<th>Ops</th>
</tr>
</thead>
</table>
RowEditor.js
I had a similiar issue and wrote a tiny JS tool, that targets editing of rows inline. The repo can be found here. I think its functionality is best described by the picture below, but you can also find a running example here.
Setting it up
What you have to do to integrate it, is
Download and integrate the file
<script type="text/javascript" charset="utf8" src="/js/RowEditor.js"></script>
Set up a configuration about which columns shall be editable and if they should be editable as dropdown or input (compare it to the example picture, you will quickly figure out what it does):
"1":{"type":"input"},
"2":{"type":"input"},
"3":{"type":"select",
"options":{
"1":{"value":'Sales Assistant', "title":'Sales Assistant'},
"2":{"value":'Tech Lead', "title":'Tech Lead'},
"3":{"value":'Secretary', "title":'Secretary'},
"4":{"value":'Developer', "title":'Developer'},
"5":{"value":'Trainee', "title":'Trainee'}
}
}
}
Call the editor, after you have initialized your DataTable:
$(document).ready( function () {
table = $('#table').DataTable();
rowEditor = new RowEditor('#table', table, editRowSettings);
});
Call the function editRow of rowEditor (or however you have named it above) with the index of the row you want to edit. I have the button placed in a sepperate column of the datatable, but you can call it anyway you want it.
<button onclick="rowEditor.editRow(1)">Edit</button>
If you have questions, feel free to ask or issue a pull request :)

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

Trouble cloning a set of selects dependent on each other

I am trying to create a dynamic table that allows the user to select from around 100 variables. These variables have been split into categories and I have been displaying them in a second select that depends on the user selecting a value in the first select. I have been searching the web for answers and have come up blank. I realize that the clone() call will duplicate all data and for that reason id's are a poor choice for the rows.
Here is what I currently have for HTML:
<body>
<table name='myTable' class="dynatable">
<thead>
<tr>
<th class='idCol' >ID</th>
<th>Category</th>
<th>Metric</th>
<th>Conditional</th>
<th><button class="add">Add</button></th>
</tr>
</thead>
<tbody>
<form name='myForm'>
<tr class="first">
<td class="id idCol"><input type="text" name="id[]" value="0" /></td>
<td><select name='categories' onChange='updatemetrics(this.selectedIndex)' style="width: 260px">
<option selected>--Select Category--</option>
<option value='1'>Customer Experience</option>
<option value='2'>Key Satisfaction Identifiers</option>
<option value='3'>Personnel Costs</option>
<!-- I have cut the rest out for the sake of brevity. -->
</select></td>
<!-- This is the select that populates based on the user's choice. -->
<td><select style="width: 310px"name='metrics'></select></td>
</tr>
</form>
</tbody>
</table>
</body>
The Javascript that I am working with is as follows.
$(document).ready(function() {
var id = 0;
// Add button functionality
$("table.dynatable button.add").click(function() {
id++;
var master = $(this).parents("table.dynatable");
// Get a new row based on the prototype row
var prot = master.find(".prototype").clone(true);
prot.attr("class", "")
prot.find(".id").attr("value", id);
master.find("tbody").append(prot);
});
// Remove button functionality
$("table.dynatable button.remove").live("click", function() {
$(this).parents("tr").remove();
});
});
//script for dynamically populating the metrics select
var metricCategories=document.myForm.categories;
var metricList=document.myForm.metrics;
var metrics=new Array()
metrics[0]=" "
metrics[1]=['Wait time average|waitInLine','Mystery Shopper Scores|mysteryScores']
metrics[2]=['Referral Rate|ref_rate','Facebook Shares|facebook_shares','Twitter Followers|twit_followers','Customer Complaint Calls|comp_calls']
metrics[3]=['Pension Payouts|pension_pay', 'Full Time Employees|ftes', 'Part Time Employees|ptes', 'Contractor Costs|contract_costs']
function updatemetrics(selectedMetricGroup){
metricList.options.length=0
if (selectedMetricGroup>0) {
for (i=0; i<metrics[selectedMetricGroup].length; i++)
metricList.options[metricList.options.length]=new Option(metrics[selectedMetricGroup][i].split("|")[0], metrics[selectedMetricGroup][i].split("|")[i])
}
}
Any help would be appreciated. To reiterate the reason I am asking for help, I need to add/ remove rows that hold select nodes that interact with each other. Thanks in advance.

Can't filter datatable by selected value in dropdown

I am using the jQuery plugin DataTables. I have a table of data that has HTML inputs and selects. When I use the DataTable search filter to filter the results and I search for all dropdowns that have the selected value of 'Open', nothing changes.
I believe this is happening because every dropdown in the table has the same options and the filter is searching on them and returning all results, since they all match.
How can I get the filter to search on only the selected value and not all options of the dropdown?
I have tried to find a solution, but all I can find are results like these :
Dropdown filter jquery datatables
CustomFilter
These all deal with adding custom filters for each column, I just want to use the existing DataTable filter.
Example
Live example of the problem, Search for 'Open' or 'Closed'
Code
<table>
<thead>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td><input name="name" type="text" value="Need more memory" id="name1"></td>
<td><select name="status" id="status1">
<option value="2">Closed</option>
<option selected="selected" value="1">Open</option>
</select>
</td>
</tr>
<tr>
<td><input name="name" type="text" value="Can't connect" id="name2"></td>
<td><select name="status" id="status2">
<option selected="selected" value="2">Closed</option>
<option value="1">Open</option>
</select>
</td>
</tr>
</tbody>
</table>
Now, you can use a data-search attribute on the <td>-element with data-tables. ref
<tr>
<td>
<input name="name" type="text" value="Need more memory" id="name1">
</td>
<td data-search="Open">
<select name="status" id="status1">
<option value="2">Closed</option>
<option selected="selected" value="1">Open</option>
</select>
</td>
</tr>
<tr>
fiddle
my similar question on datatables.net
There is a better way to put a drop-down list into your cells. Of course this is searchable. You can watch the offical tutorial about this technique.
Client side
Drop-down list creation
When you initialize the plugin you can do this:
<script type="text/javascript">
$(document).ready(function () {
$('#datatable').dataTable().makeEditable({
sUpdateURL: "UpdateData.php",//Server side file accepting AJAX call.
"aoColumns": [//Column settings.
{},//1st column with default settings.
{//2nd column to a drop-down list.
indicator: 'Saving...',
loadtext: 'Loading...',
type: 'select',//This will make it a drop-down list.
onblur: 'submit',
data: "{'open':'Open','closed':'Closed'}"
}]
});
});
</script>
The key is the data part. Here you can define the options of your list. You can also add this part dinamically via PHP. The syntax is the following for one option.
'variable_sent_to_UpdateData.php':'Text that will be displayed'
Every option should be separated by a comma.
Column names
You can also rename your columns as shown in the offical tutorial so when they passed to the server, DataTables won't name them after the <th> tag:
<script type="text/javascript">
$(document).ready(function () {
$('#datatable').dataTable(
aoColumns: [//Rename columns contained by AJAX call.
{sName: "name"},
{sName: "status"}
]
).makeEditable({
//Previous stuff...
});
});
</script>
Server side
After all, you just have to update your database in UpdateData.php:
$id = $_REQUEST['id'];//The id tag of your table's row.
$column = $_REQUEST['columnName'];//Column where the cell was edited.
$value = $_REQUEST['value'];//The new value.
$columnPosition = $_REQUEST['columnPosition'];
$columnId = $_REQUEST['columnId'];
$rowId = $_REQUEST['rowId'];
switch ($column)
{
case 'name':
//Do SQL update...
echo $value;
break;
case 'status':
//Do SQL update...
echo $value;
break;
default: echo 'Error';
}
It's important to echo (return) the $value variable because:
Indicates that the updating was successful.
This value will be the new value in the table.
If you return something else, it will count as an error message that will be displayed in a pop-up window and no changes will be shown in the table.

Jquery: Enable/Disable based on value of dropdown is not working for dynamically generated inputs

I have a form where I can add new rows to increase the form elements using jquery. In that form I have two dropdown options (Name:type and accounts) and two text inputs (Name:debit_amount and credit_amount).
Problem:
I have developed a jquery code to enable/disable text inputs based on the selected values from dropdown options. But the code works fine only if I don't add new rows. If I add a new row it only works for the very first row, I mean it disables/enables inputs of the first row only.
For the sake of clarity I have not provided the code for adding new rows below, but to get a live picture of all my codes please check this link, jsfiddle.net
Could you please tell me what change should I bring in my code to be able to make all the inputs (including inputs of generated rows ) disable/enable based on the selected values?
My HTML
<h2>Add Another Input Box</h2>
<table class="dynatable">
<thead>
<tr>
<th>Type</th>
<th>Account Name</th>
<th>Debit</th>
<th>Credit</th>
</tr>
</thead>
<tbody id="p_scents">
<tr>
<td>
<select name="type" id="type">
<option value="Debit">Debit</option>
<option value="Credit">Credit</option>
</select>
</td>
<td>
<select name="accounts" id="accounts">
<option value="">SELECT</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
</td>
<td>
<input type="text" name="debit_amount" id="debit_amount" />
</td>
<td>
<input type="text" name="credit_amount" id="credit_amount"/>
</td>
</tr>
</tbody>
Conditions for disabling/Enabling
1. If type selected == Debit and a value from accounts is selected then enable debit_amount input and disable credit_amount input
2. If type selected == Credit and a value from accounts is selected then enable credit_amount input and disable debit_amount input
3. If any of the values of type and accounts is not selected disable both
My Jquery Code for disabling/enabling inputs based on dropdown value
//ON the change of accounts(dropdown select)
$("#accounts").change(function() {
var type = $("select#type").val();
var accounts = $("select#accounts").val();
if (type == "Debit") {
$('#credit_amount').attr("disabled", true);
$('#debit_amount').removeAttr("disabled", true);
}
if (type == "Credit") {
$('#debit_amount').attr("disabled", true);
$('#credit_amount').removeAttr("disabled", true);
}
if (accounts == "") {
$('input[name=credit_amount]').val('');
$('input[name=debit_amount]').val('');
$('#debit_amount').attr("disabled", true);
$('#credit_amount').attr("disabled", true);
}
});
//ON the change of type(dropdown select)
$("#type").change(function() {
var accounts = $("select#accounts").val();
var type = $("select#type").val();
if (type == "Debit" && accounts != '') {
$('input[name=credit_amount]').val('');
$('#credit_amount').attr("disabled", true);
$('#debit_amount').removeAttr("disabled", true);
}
if (type == "Credit" && accounts != '') {
$('input[name=debit_amount]').val('');
$('#debit_amount').attr("disabled", true);
$('#credit_amount').removeAttr("disabled", true);
}
});
The problem is that your input elements all have the same id attribute values, ie: "debit_amount" and "credit_amount", so jQuery doesn't know which ones the "#debit_amount" and "#credit_amount" selectors refer to.
Element ids should be unique in the page, so you should append a sequence number to the end of each eg:
<select name="accounts_1" id="accounts_1">
....
<input type="text" name="debit_amount_1" id="debit_amount_1" />
<input type="text" name="credit_amount_1" id="credit_amount_1" />
Two solutions:
use the jQuery traversal API to find the input elements relative to the select element that triggered the onChange event. This is brittle and will break if you change your markup too much
parse the sequence number out of the <select> id attribute and use it to find the <input>s you want to modify

Categories

Resources