Three buttons change the data-table content - javascript

I have three buttons for each data-table button, I want to filter these buttons, I mean when I press the button today brings me only data-table for the day as well as the button week and also month. Here is a picture showing what I mean
Here is my HTML code:
<div class="row">
<div class="col-sm-9 m-b-xs">
<div data-toggle="buttons" class="btn-group btn-group-toggle">
<label class="btn btn-sm btn-white"> <input type="radio" id="option1" name="options"> Day </label>
<label class="btn btn-sm btn-white active"> <input type="radio" id="option2" name="options"> Week </label>
<label class="btn btn-sm btn-white"> <input type="radio" id="option3" name="options"> Month </label>
</div>
</div>
</div>
and here is my JS code:
var empList = [];
var filter_expired = 'all';
function generateTable() {
var html = '';
console.log("ok", empList);
$.each(empList, function (key, item) {
if (filter_expired == 'all' || (filter_expired == "expired" && item.isExpired == true) || (filter_expired == "notExpired" && item.isExpired == false)) {
html += '<tr>';
html += '<td style="vertical-align: middle;">' + item.anything + '</td>';
html += '<td style="vertical-align: middle;">' + (item.anything1 !== undefined ? item.anything1 : "-") + '</td>';
html += '<td style="vertical-align: middle;">' + (item.anything2 !== undefined ? item.anything2 : "-") + '</td>';
html += '<td style="vertical-align: middle;">' + (item.anything3 !== undefined ? item.anything3 : "-") + '</td>';
html += '<td style="vertical-align: middle;">' + (item.anything4 !== undefined ? item.anything4 : "-") + '</td>';
html += '</td></tr>';
html += '</tr>';
}
});
$('#myTable').append('<tbody class="tbody">' + html + '</tbody><tfoot><tr class="footable-paging"><td colspan="9"><div class="footable-pagination-wrapper"><ul class="pagination pull-right"><li id="arrowFirst" class="footable-page-arrow disabled"><a data-page="first" href="#first">«</a></li><li class="footable-page-arrow disabled"><a data-page="prev" href="#prev">‹</a></li><li class="footable-page active"><a data-page="0" href="#">1</a></li><li class="footable-page"><a data-page="1" href="#">2</a></li><li class="footable-page-arrow"><a data-page="next" href="#next">›</a></li><li id="arrowLast" class="footable-page-arrow"><a data-page="last" href="#last">»</a></li></ul></div></td></tr></tfoot>');
$('#myTable').footable({
"paging": {
"enabled": true,
"data-page-size": "15",
"data-limit-navigation": "3"
},
"sorting": {
"enabled": true
}
});
clientRefresh();
$('.ibox').children('.ibox-content').toggleClass('sk-loading'); $('.ibox').addClass('bounce');
$("#search").val("");
}

You just need to create an event for button, call your function from that event so you can identify which button is pressed.
<div class="row">
<div class="col-sm-9 m-b-xs">
<div data-toggle="buttons" class="btn-group btn-group-toggle">
<label class="btn btn-sm btn-white"> <input type="radio" value="day" id="option1" name="options" > Day </label>
<label class="btn btn-sm btn-white active"> <input type="radio" value="week" id="option2" name="options"> Week </label>
<label class="btn btn-sm btn-white"> <input type="radio" value="month" id="option3" name="options"> Month </label>
</div>
</div>
</div>
Now you need to handle common change event
<script src="~/Scripts/jquery-3.3.1.js"></script>
<script>
$(document).ready(function () {
$('input:radio[name=options]').change(function () {
var filterType = $(this).val();
generateTable(filterType)
});
});
function generateTable(filterType) {
//do filter in your code using above param
}
</script>

Related

Disable select option when it already selected

I have tried to disable the option on select when it already selected. But it didn't disable when it already selected.
Below is the query for select option, it can be created dynamically.
var count = 0;
$(document).on('click', '#add', function () {
count++;
var html = '';
html += '<tr id="trrows">';
html += '<td id="medicinename"> <select name="med_name[]" id="med_name[]" class="form-control med_name" ><option value=""> Select Medicine</option> <?php echo fill_select_box($conn, "0"); ?></select></td>';
html += '<td id="mor"> <input type="text" name="morning[]" id="morning[]" class="form-control morning" /> </td>';
html += '<td id="noo"> <input type="text" name="noon[]" id="noon[]" class="form-control noon" /> </td>';
html += '<td id="nigh"> <input type="text" name="night[]" id="night[]" class="form-control night" /> </td>';
html += '<td id="period"> <input type="text" name="period[]" id="period[]" class="form-control period" /> </td>';
html += '<td> <button type="button" name="remove" id="remove" class="btn btn-danger btn-xs remove" > - </button> </td>';
html += '</tr>';
$('#rows').append(html);
});
$(document).on('click', '.remove', function () {
$(this).closest("#trrows").remove();
});
Below is the query for disable the select option on for (med_name[]),
$('select[name*="med_name[]"]').change(function(){
$('select[name*="med_name[]"] option').attr('disabled',false);
$('select[name*="med_name[]"]').each(function(){
var $this = $(this);
$('select[name*="med_name[]"]').not($this).find('option').each(function(){
if($(this).attr('value') == $this.val())
$(this).attr('disabled',true);
});
});
});
Below is the HTML,
<table class="table table-bordered mb-0" id="medical">
<thead>
<tr>
<th>Medicine Name</th>
<th>Morning</th>
<th>Noon</th>
<th>Night</th>
<th>Period</th>
</tr>
</thead>
<tbody id="rows">
</tbody>
</table>
<br><br>
<div align="right">
<button type="button" name="add" id="add" class="btn btn-success btn xs"> + </button>
</div>
I don't know where I went wrong. How can I achieve that? Any help may highly appreciated.
This is a working example, please check
I have updated some js code to make it work.
var count = 0;
$(document).on('click', '#add', function () {
count++;
var html = '';
html += '<tr id="trrows">';
html += '<td id="medicinename"> <select name="med_name[]" id="med_name[]" class="form-control med_name" ><option value=""> Select Medicine</option> <option value="1"> Option 1 </option><option value="2"> Option 2 </option><option value="3"> Option 3 </option><option value="4"> Option 4 </option><option value="5"> Option 5 </option></select></td>';
html += '<td id="mor"> <input type="text" name="morning[]" id="morning[]" class="form-control morning" /> </td>';
html += '<td id="noo"> <input type="text" name="noon[]" id="noon[]" class="form-control noon" /> </td>';
html += '<td id="nigh"> <input type="text" name="night[]" id="night[]" class="form-control night" /> </td>';
html += '<td id="period"> <input type="text" name="period[]" id="period[]" class="form-control period" /> </td>';
html += '<td> <button type="button" name="remove" id="remove" class="btn btn-danger btn-xs remove" > - </button> </td>';
html += '</tr>';
$('#rows').append(html);
});
$(document).on('click', '.remove', function () {
$(this).closest("#trrows").remove();
});
$(document).on('click', 'select.med_name', function () {
$('select[name*="med_name[]"] option').attr('disabled',false);
$('select[name*="med_name[]"]').each(function(){
var $this = $(this);
$('select[name*="med_name[]"]').not($this).find('option').each(function(){
if($(this).attr('value') == $this.val())
$(this).attr('disabled',true);
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title of the document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table class="table table-bordered mb-0" id="medical">
<thead>
<tr>
<th>Medicine Name</th>
<th>Morning</th>
<th>Noon</th>
<th>Night</th>
<th>Period</th>
</tr>
</thead>
<tbody id="rows">
</tbody>
</table>
<br><br>
<div align="right">
<button type="button" name="add" id="add" class="btn btn-success btn xs"> + </button>
</div>
</body>
</html>
Here's very basic implementation
$('select').change(function() {
var value = $(this).val();
$(this).children('option').each(function() {
if ( $(this).val() === value ) {
$(this).attr('disabled', true).siblings().removeAttr('disabled');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value=1> Option 1 </option>
<option value=2> Option 1 </option>
<option value=3> Option 1 </option>
</select>
Edit: Here is your sample
var count = 0;
$(document).on('click', '#add', function () {
count++;
var html = '';
html += '<tr id="trrows">';
html += '<td id="medicinename"> <select name="med_name[]" id="med_name[]" class="form-control med_name" ><option value=""> Select Medicine</option> <?php echo fill_select_box($conn, "0"); ?></select></td>';
html += '<td id="mor"> <input type="text" name="morning[]" id="morning[]" class="form-control morning" /> </td>';
html += '<td id="noo"> <input type="text" name="noon[]" id="noon[]" class="form-control noon" /> </td>';
html += '<td id="nigh"> <input type="text" name="night[]" id="night[]" class="form-control night" /> </td>';
html += '<td id="period"> <input type="text" name="period[]" id="period[]" class="form-control period" /> </td>';
html += '<td> <button type="button" name="remove" id="remove" class="btn btn-danger btn-xs remove" > - </button> </td>';
html += '</tr>';
$('#rows').append(html);
});
function addRow(rowIndex) {
count++;
var html = '';
html += '<tr id="trrows">';
html += '<td id="medicinename"> <select name="med_name[' + rowIndex + ']" id="med_name[]" class="form-control med_name" ><option value=""> Select Medicine</option><option value="1"> Select Medicine1</option><option value="2"> Select Medicine2</option> </select></td>';
html += '<td id="mor"> <input type="text" name="morning[]" id="morning[]" class="form-control morning" /> </td>';
html += '<td id="noo"> <input type="text" name="noon[]" id="noon[]" class="form-control noon" /> </td>';
html += '<td id="nigh"> <input type="text" name="night[]" id="night[]" class="form-control night" /> </td>';
html += '<td id="period"> <input type="text" name="period[]" id="period[]" class="form-control period" /> </td>';
html += '<td> <button type="button" name="remove" id="remove" class="btn btn-danger btn-xs remove" > - </button> </td>';
html += '</tr>';
$('#rows').append(html);
}
addRow(1);
addRow(2);
addRow(3);
$('select[name*="med_name"]').change(function() {
var value = $(this).val();
$(this).children('option').each(function() {
if ( $(this).val() === value ) {
$(this).attr('disabled', true).siblings().removeAttr('disabled');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id=rows>
</table>

Creating inputs from array size not working with Jquery

I'm trying to populate a list of n inputs from an array I have in localStorage. The issue is that I can see in console.log() that the for is getting executed but I only see two inputs.
javascript:
App.prefillWords = function() {
var arrayWords = JSON.parse(localStorage.getItem("event-data")).selected_word;
for (var i = 0; i < arrayWords.length; i++) {
var addto = "#field" + i;
var addRemove = "#field" + (i);
console.log(addto);
console.log(addRemove);
var newIn = '<input placeholder="Word" class="input form-control wordData" id="field' + i + '" name="field' + i + '" type="text">';
var newInput = $(newIn);
var removeBtn = '<button id="remove' + (i - 1) + '" class="btn btn-danger remove-me" >-</button></div><div id="field">';
var removeButton = $(removeBtn);
$(addto).after(newInput);
$(addRemove).after(removeButton);
$("#field" + i).attr('data-source', $(addto).attr('data-source'));
$("#count").val(i);
$('.remove-me').click(function (e) {
e.preventDefault();
var fieldNum = this.id.charAt(this.id.length - 1);
var fieldID = "#field" + fieldNum;
$(this).remove();
$(fieldID).remove();
});
}
}
html
<div class="panel-body">
<input type="hidden" name="count" value="1" />
<form class="wordsForm">
<div id="field" class="form-group row">
<label class="col-12 col-sm-3 col-form-label text-sm-right" for="wordScore">New Word</label>
<div class="col-12 col-sm-8 col-lg-6" id="fill">
<input autocomplete="off" class="wordData form-control" id="field1" name="prof1" type="text" placeholder="Word"/>
<button id="b1" class="btn add-more" type="button">+</button>
</div>
</div>
<div class="col-sm-6">
<p class="text-right">
<button class="btn btn-space btn-primary" id="updateEvent">Submit</button>
<button class="btn btn-space btn-secondary" id="cancelEvent">Cancel</button>
</p>
</div>
</form>
</div>
interface:
Any advice is highly appreciated, thanks

JQuery .on works on first html but doesn't work on the second(same form)

So, I have this form that I used on both my html page and .on works on the first one but doesn't work on the second one even though all properties are same.
First HTML:
<div id="page1" class="row" style="text-align: center;">
<h2 style="text-align: center;">Category</h2>
<div class="btn-group" data-toggle="buttons" >
<label class="btn btn-primary <?php echo $_SESSION['editEntry'][0]['category']=='Food'?'active':''; ?>">
<input type="radio" name="category" id="food" autocomplete="off" <?php echo $_SESSION['editEntry'][0]['category']=='Food'?'checked':''; ?> value="Food"> Food
</label>
<label class="btn btn-primary <?php echo $_SESSION['editEntry'][0]['category']=='Non-Food'?'active':''; ?>">
<input type="radio" name="category" id="non-food" autocomplete="off" <?php echo $_SESSION['editEntry'][0]['category']=='Non-Food'?'checked':''; ?> value="Non-Food"> Non-Food
</label>
<label class="btn btn-primary <?php echo $_SESSION['editEntry'][0]['category']=='Services'?'active':''; ?>">
<input type="radio" name="category" id="services" autocomplete="off" <?php echo $_SESSION['editEntry'][0]['category']=='Services'?'checked':''; ?> value="Services"> Services
</label>
<label class="btn btn-primary <?php echo $_SESSION['editEntry'][0]['category']=='Technology'?'active':''; ?>">
<input type="radio" name="category" id="technology" autocomplete="off" <?php echo $_SESSION['editEntry'][0]['category']=='Technology'?'checked':''; ?> value="Technology"> Technology
</label>
</div>
<div class="box-footer">
<div class="pull-right">
<button type="button" id="next1" class="btn btn-primary"><i class="glyphicon glyphicon-chevron-right"></i> Next</button>
</div>
</div>
<!-- /.box-footer -->
</div>
Second HTML:
<div id="page1" class="row" style="text-align: center;">
<h2 style="text-align: center;">Category</h2>
<div class="btn-group" data-toggle="buttons" >
<label class="btn btn-primary active">
<input type="radio" name="category" id="food" autocomplete="off" checked value="Food"> Food
</label>
<label class="btn btn-primary">
<input type="radio" name="category" id="non-food" autocomplete="off" value="Non-Food"> Non-Food
</label>
<label class="btn btn-primary">
<input type="radio" name="category" id="services" autocomplete="off" value="Services"> Services
</label>
<label class="btn btn-primary">
<input type="radio" name="category" id="technology" autocomplete="off" value="Technology"> Technology
</label>
</div>
<div class="box-footer">
<div class="pull-right">
<button type="button" id="next1" class="btn btn-primary"><i class="glyphicon glyphicon-chevron-right"></i> Next</button>
</div>
</div>
<!-- /.box-footer -->
</div>
JS:
$("#page1").on('click', '#next1, #next2, #next3, #next4, #next5', function(e){
e.preventDefault();
nextPage($(this).attr('id'));
});
function nextPage(selector){
switch(selector){
case 'next1':
$("#page1").attr("hidden", "hidden");
$("#page2").removeAttr("hidden");
break;
case 'next2':
if($("input[name='title']").val() == '' || $("textarea[name='description']").val() == ''){
alert("Fill up the fields to continue..");
}else{
$("#page2").attr("hidden", "hidden");
$("#page3").removeAttr("hidden");
$(".certTitle").html($('#page2 input[name="title"]').val());
}
break;
case 'next3':
if($("input[name='college']").val() == '' || $("input[name='collegeAddress']").val() == '' || $("input[name='collegeDean']").val() == '' || $("input[name='coach']").val() == '' || $("input[name='contactPerson']").val() == '' || $("input[name='landline']").val() == '' || $("input[name='mobile']").val() == '' || $("input[name='email']").val() == ''){
alert("Fill up the fields to continue..");
}else{
$("#page3").attr("hidden", "hidden");
$("#page4").removeAttr("hidden");
$("#certDean").html($("input[name='collegeDean']").val().toUpperCase());
$("#certCoach").html($("input[name='coach']").val());
}
break;
case 'next4':
var empty = $("#students").find("input").filter(function() {
if($(".setContact").val() == ""){
return this.value = 1;
}else{
return this.value === "";
}
});
if(contactPersonCount < 2){
alert("Please select at least 2 alternative contact persons..");
}else if($("input[name='firstname']").val() == '' || $("input[name='lastname']").val() == '' || $("input[name='email']").val() == '' || $("input[name='studentMobile']").val() == '' || $("input[name='dob']").val() == '' || empty.length){
alert("Fill up the fields to continue..");
}else{
$("#page4").attr("hidden", "hidden");
$("#page5").removeAttr("hidden");
var currentCount = $("#students div").length;
var studentsList = [];
console.log(currentCount);
for(var i = 1; i <= currentCount; i++){
studentsList[i] = $("#students input[name='firstname"+i+"']").val() + " " + $("#students input[name='lastname"+i+"']").val();
}
$("#studentsList").children().remove();
for(var i = 1; i <= currentCount; i++){
$("#studentsList").append("<li>"+ studentsList[i] +"</li>");
}
}
break;
case 'next5':
if($("input[name='presentationUpload']").val() == '' || $("input[name='documentUpload']").val() == ''){
alert("Fill up the fields to continue..");
}else{
$("#page5").attr("hidden", "hidden");
$("#page6").removeAttr("hidden");
}
break;
default:
console.log("Invalid Selector: " + selector);
break;
}
}
I'm not sure why it doesn't trigger on the second one even if both of them have the same attributes.
NOTE: Those HTML codes resides on different HTML files but uses the same JS.
If you replace the whole <div id="page1"> then you lose the event listener attached to $("#page1") because that element is removed...even though it is replaced with a new one with same ID
Move the delegation higher to an asset that is permanent
Try:
$(document).on('click', '#next1, #next2, #next3, #next4, #next5', function(e){
e.preventDefault();
nextPage($(this).attr('id'));
});

Jquery validation for dynamically adding rows-

I am using Jquery validate plugin for doing my form validation.
In my form, I had an usecase of adding rows dynamically upon clicking an add button.
Adding new row, will result in generating a new name for the row (new name is appending a number to the original name).
I have written the validation logic, which will validate the first standard row itself, but the subsequent addition of rows will not be getting validated.
Need help in making validation for these dynamic Names w.r.t added rows.
Below is my html code, where standard row was mentioned with the class and Names to the elements in the row.
The js file contains the logic to add the rows dynamically and the validation logic.
Html:
<tbody>
<tr>
<td>
<div class="uriDiv input-group">
<input type="text" name="uriName" class="common form-control authUrl"
id="uriName" placeholder="URL for the Policy" />
</div>
</td>
<td>
<div class="uriDiv input-group">
<select class="common authSelect form-control" name="authType" id="authType">
<option value="">
<spring:message
code="newPolicy.selectAuthType"></spring:message>
</option>
<option value="DB">DB</option>
<option value="LDAP">LDAP</option>
</select>
</div>
</td>
<td>
<div class="auth-permission-rd">
<div class="uriDiv radio radio-left">
<label> <input type="radio" class="common anyuser authPermission"
value="anyUser" name="authPermission" id="anyUser" disabled="disabled">Any
User
</label>
</div>
<div class="uriDiv radio radio-input">
<label> <input type="radio" class="common groupuser authPermission"
value="groupUser" name="authPermission" id="groupUser" disabled="disabled">
<input type="text" name="authPermissionValue" disabled="disabled"
class="common form-control-placeHolder" id="authPermissionValue" placeholder="Enter custom Permissions - Comma separated" />
</label>
</div>
</div>
</td>
<td><button type="button"
class="btn btn-primary delete-but-grid">
<span class="glyphicon glyphicon-remove"></span>
</button>
</td>
</tr>
<tr>
<td colspan="4">
<button type="button" id="addBtn"
class="btn add-but-grid glyphicon glyphicon-plus-sign"></button>
</td>
</tr>
</tbody>
js:adding new rows
$("#addBtn").click(function() {
var divAdd = '
<tr id=' + dynamicCount + '>
<td>
<div class="uriDiv input-group"><input type="text" name="uriName' + dynamicCount + '" class="common form-control" id="uriName' + dynamicCount + '" placeholder="URL for the Policy"/></div>
</td>
'
divAdd = divAdd + '
<td>
<div class="uriDiv input-group">
<select class="common authSelect form-control" id="authType' + dynamicCount + '" name="authType' + dynamicCount + '">
<option value="">Select Auth Type </option>
<option value="DB">DB</option>
<option value="LDAP">LDAP</option>
</select>
</div>
</td>
'
divAdd = divAdd + '
<td>
<div class="auth-permission-rd">
<div class="uriDiv radio radio-left"><label> <input type="radio" class="common anyuser authPermission" value="anyUser" disabled="disabled" name="authPermission' + dynamicCount + '" id="anyUser">Any User</label></div>
'
divAdd = divAdd + '
<div class="uriDiv radio radio-input"> <label> <input type="radio" class="common groupuser authPermission" value="groupUser" disabled="disabled" name="authPermission' + dynamicCount + '"id="groupUser"><input type="text" disabled="disabled" name="authPermissionValue' + dynamicCount + '" class="common form-control-placeHolder" id="authPermissionValue' + dynamicCount + '" placeholder="Enter custom Permissions - Comma separated" /></label></div>
</div>
</td>
'
divAdd = divAdd + '
<td><button type="submit" id=' + dynamicCount + ' class="uriDelte btn btn-primary delete-but-grid"><span class="glyphicon glyphicon-remove"></span></button></td>
</tr>
'
$('#uriInfo tr:last').before(divAdd);
dynamicCount++;
});
js validation: some part of it.
$("#policy-form").validate({
rules:{
uriName:{
required: true
},
authType:{
required: true
},
authPermission:{
required: true
},
},
Need help in getting the validation for dynamic rows.
Thanks.
Normally Jquery validation works by input 'Name'..here in this case as my input rows can be dynamically added,i created a custom class validation method, which does the validation based on the class name, instead of the row name..so by making these changes, my Jquery validation is working fine..below is my new code...
validation :
$.validator.addClassRules({
authUrl:{ // here authUrl is one of the class Name for the input row..
crequiredUrl:true
},
authSelect:{
crequiredSelect:true
},
authPermission:{
crequiredPermission:true
},
authPermissionMulti:{
crequiredPermCust:true
}
});
$.validator.addMethod('crequiredUrl', $.validator.methods.required,
'Please enter the Url');
$.validator.addMethod('crequiredSelect', $.validator.methods.required,
' Auth Type for policy is required');
$.validator.addMethod('crequiredPermission', $.validator.methods.required,
' AuthPermission for policy is required');
$.validator.addMethod('crequiredPermCust', $.validator.methods.required,
' Custom AuthPermissions cannot be empty');
$("#policy-form").validate({
rules:{
targetEnv:{
required:true
},
domainName: {
required:true
},
authSchemaType: {
required: true
},
headersRequired: {
required: true
},
headersReqEle: {
required: true
// other form validation rules..
my dynamic row add/delete code:
$('#headerCheck').hide();
var dynamicCount=0;
// var validateArray=new Array('uriName','authType','authPermission','authPermissionValue');
$("#addBtn").click(function() {
var divAdd = '<tr id=' + dynamicCount + '><td><div class="uriDiv input-group"><input type="text" name="uriName' + dynamicCount + '" class="common form-control authUrl" id="uriName' + dynamicCount + '" placeholder="URL for the Policy"/></div></td>'
divAdd = divAdd + '<td><div class="uriDiv input-group"><select class="common authSelect form-control" id="authType' + dynamicCount + '" name="authType' + dynamicCount + '"><option value="">Select Auth Type </option><option value="RACF">RACF</option><option value="LDAP">LDAP</option></select></div></td>'
divAdd = divAdd + '<td><div class="auth-permission-rd"><div class="uriDiv radio radio-left"><label> <input type="radio" class="common anyuser authPermission" value="anyUser" disabled="disabled" name="authPermission' + dynamicCount + '" id="anyUser">Any User</label></div>'
divAdd = divAdd + '<div class="uriDiv radio radio-input"> <label> <input type="radio" class="common groupuser authPermission" value="groupUser" disabled="disabled" name="authPermission' + dynamicCount + '"id="groupUser"><input type="text" disabled="disabled" name="authPermissionValue' + dynamicCount + '" class="common form-control-placeHolder authPermissionMulti" id="authPermissionValue' + dynamicCount + '" placeholder="Enter custom Permissions - Comma separated" /></label></div></div></td>'
divAdd = divAdd + '<td><button type="submit" id=' + dynamicCount + ' class="uriDelte btn btn-primary delete-but-grid"><span class="glyphicon glyphicon-remove"></span></button></td></tr>'
$('#uriInfo tr:last').before(divAdd);
dynamicCount++;
});
for my jsp page, pls refer to my question..
cheers :)

How to set option value dynamically using jquery/javascript

I want to set option value dynamically using Jquery/Javascript.I am explaining my work flow with code below.
index.html:
<Ol>
<div class="totalaligndiv" id="TextBoxContainer">
<li>
<div class="col-md-4 bmargindiv1">
<label for="qualification" accesskey="Q"><span class="required">*</span> Qualification</label>
<input name = "txtQualification" id="txtQualification" type="text" />
</div>
<div class="col-md-5 bmargindiv1">
<label for="college" accesskey="C"><span class="required">*</span> College</label>
<input type="text" ID="txtCollege" name="college"/>
</div>
<div class="col-md-2 bmargindiv1">
<label for="passingyear" accesskey="Q"><span class="required">*</span> Passing Year</label>
<select ID="txtPassingYear" name="passingyear">
<option>Year</option>
</select>
</div>
<div class="col-md-1 bmargindiv1">
<label for="action" accesskey="C"> </label>
<button type="button" class="btn btn-success btn-sm addbtn" id="Button1" onclick="AddTextBox(this)">+</button>
<button type="button" class="btn btn-danger btn-sm minusbtn " id="Button2" style="display:none;" onclick = "RemoveTextBox(this)">-</button>
</div>
</li>
</div>
</Ol>
<script type="text/javascript">
window.onload=function(){
getYears();
}
function getYears() {
var dropdown = document.getElementById("txtPassingYear");
var currentTime = new Date();
var year = currentTime.getFullYear();
for (var i = year; i >= 1960; i--) {
var newOption = document.createElement('option');
newOption.value = i;
newOption.innerHTML = i;
dropdown.add(newOption);
}
}
</script>
<script type="text/javascript">
function GetDynamicTextBox(value, value1, value2) {
return '<div class="col-md-4 bmargindiv1"><label for="qualification" accesskey="Q"><span class="required">*</span> Qualification</label>' +
'<input name = "txtQualification" id="txtQualification" type="text" value = "' + value + '" />' +
'</div>' +
'<div class="col-md-5 bmargindiv1">' +
'<label for="college" accesskey="C"><span class="required">*</span> College</label>' +
'<input type="text" ID="txtCollege" name="college" value = "' + value1 + '" />' +
'</div>' +
'<div class="col-md-2 bmargindiv1">' +
'<label for="passingyear" accesskey="Q"><span class="required">*</span> Passing Year</label>' +
'<select ID="txtPassingYear" name="passingyear">' +
'</select>' +
'</div>' +
'<div class="col-md-1 bmargindiv1">' +
'<label for="action" accesskey="C"> </label>' +
'<button type="button" class="btn btn-success btn-sm addbtn" id="Button1" onclick="AddTextBox(this)">+</button>' +
'<button type="button" class="btn btn-danger btn-sm minusbtn " id="Button2" style="display:none;" onclick = "RemoveTextBox(this)">-</button>'
}
function AddTextBox(objId) {
var div = document.createElement('li');
div.innerHTML = GetDynamicTextBox("", "", "");
document.getElementById("TextBoxContainer").appendChild(div);
$(objId).css('display', 'none');
$(objId).siblings("button.btn-danger").css('display', 'block');
var id=$(objId).closest('select');
console.log('id is',id);
getYears();
}
function RemoveTextBox(div) {
$(div).closest("li").remove();
}
</script>
In this above code first time after page load user is getting 3 fields i.e-Qualification,College,Passing year fields and the the years in drop down list is coming properly.When user is clicking on + button again another set of 3 fields is generating and in this section user is not getting any year in drop down list.Please help me to add years dynamically in dropdown list which is coming after clicked on + button.Please help me.
We have implemented the code for you. Id for the element is unique and for this we have created a dynamic id counter. Whenever you add the textboxes it will assign new id to select drop down and assign the year option to it.
<Ol>
<div class="totalaligndiv" id="TextBoxContainer">
<li>
<div class="col-md-4 bmargindiv1">
<label for="qualification" accesskey="Q"><span class="required">*</span> Qualification</label>
<input name = "txtQualification" id="txtQualification" type="text" />
</div>
<div class="col-md-5 bmargindiv1">
<label for="college" accesskey="C"><span class="required">*</span> College</label>
<input type="text" ID="txtCollege" name="college"/>
</div>
<div class="col-md-2 bmargindiv1">
<label for="passingyear" accesskey="Q"><span class="required">*</span> Passing Year</label>
<select ID="txtPassingYear" name="passingyear">
<option>Year</option>
</select>
</div>
<div class="col-md-1 bmargindiv1">
<label for="action" accesskey="C"> </label>
<button type="button" class="btn btn-success btn-sm addbtn" id="Button1" onclick="AddTextBox(this)">+</button>
<button type="button" class="btn btn-danger btn-sm minusbtn " id="Button2" style="display:none;" onclick = "RemoveTextBox(this)">-</button>
</div>
</li>
</div>
</Ol>
<script type="text/javascript">
window.onload=function(){
getYears();
}
function getYears() {
var dropdown = document.getElementById("txtPassingYear");
var currentTime = new Date();
var year = currentTime.getFullYear();
for (var i = year; i >= 1960; i--) {
var newOption = document.createElement('option');
newOption.value = i;
newOption.innerHTML = i;
dropdown.add(newOption);
}
}
function getYearsOther() {
var dropdown = document.getElementById("txtPassingYear" + counter);
var currentTime = new Date();
var year = currentTime.getFullYear();
for (var i = year; i >= 1960; i--) {
var newOption = document.createElement('option');
newOption.value = i;
newOption.innerHTML = i;
dropdown.add(newOption);
}
}
</script>
<script type="text/javascript">
var counter = 0;
function GetDynamicTextBox(value, value1, value2) {
counter++;
return '<div class="col-md-4 bmargindiv1"><label for="qualification" accesskey="Q"><span class="required">*</span> Qualification</label>' +
'<input name = "txtQualification" id="txtQualification" type="text" value = "' + value + '" />' +
'</div>' +
'<div class="col-md-5 bmargindiv1">' +
'<label for="college" accesskey="C"><span class="required">*</span> College</label>' +
'<input type="text" ID="txtCollege" name="college" value = "' + value1 + '" />' +
'</div>' +
'<div class="col-md-2 bmargindiv1">' +
'<label for="passingyear" accesskey="Q"><span class="required">*</span> Passing Year</label>' +
'<select ID="txtPassingYear' + counter + '" name="passingyear">' +
'</select>' +
'</div>' +
'<div class="col-md-1 bmargindiv1">' +
'<label for="action" accesskey="C"> </label>' +
'<button type="button" class="btn btn-success btn-sm addbtn" id="Button1" onclick="AddTextBox(this)">+</button>' +
'<button type="button" class="btn btn-danger btn-sm minusbtn " id="Button2" style="display:none;" onclick = "RemoveTextBox(this)">-</button>'
}
function AddTextBox(objId) {
var div = document.createElement('li');
div.innerHTML = GetDynamicTextBox("", "", "");
document.getElementById("TextBoxContainer").appendChild(div);
$(objId).css('display', 'none');
$(objId).siblings("button.btn-danger").css('display', 'block');
var id=$(objId).closest('select');
console.log('id is',id);
getYearsOther();
}
function RemoveTextBox(div) {
$(div).closest("li").remove();
}
</script>
You could try this code
function getYears() {
var $dropdown =$('#txtPassingYear');
var currentTime = new Date();
var year = currentTime.getFullYear();
for (var i = year; i >= 1960; i--) {
$dropdown.append($('<option>', {
value: i,
text: i
}));
}
}
CODE AFTER EDIT**
<Ol>
<div class="totalaligndiv" id="TextBoxContainer">
<li>
<div class="col-md-4 bmargindiv1">
<label for="qualification" accesskey="Q"><span class="required">*</span> Qualification</label>
<input name = "txtQualification" id="txtQualification" type="text" />
</div>
<div class="col-md-5 bmargindiv1">
<label for="college" accesskey="C"><span class="required">*</span> College</label>
<input type="text" ID="txtCollege" name="college"/>
</div>
<div class="col-md-2 bmargindiv1">
<label for="passingyear" accesskey="Q"><span class="required">*</span> Passing Year</label>
<select ID="txtPassingYear" name="passingyear">
<option>Year</option>
</select>
</div>
<div class="col-md-1 bmargindiv1">
<label for="action" accesskey="C"> </label>
<button type="button" class="btn btn-success btn-sm addbtn" id="Button1" onclick="AddTextBox(this)">+</button>
<button type="button" class="btn btn-danger btn-sm minusbtn " id="Button2" style="display:none;" onclick = "RemoveTextBox(this)">-</button>
</div>
</li>
</div>
</Ol>
<script type="text/javascript">
window.onload = function () {
var $dropdown = $('#txtPassingYear');
getYears($dropdown);
}
function getYears(element) {
var currentTime = new Date();
var year = currentTime.getFullYear();
for (var i = year; i >= 1960; i--) {
element.append($('<option>', {
value: i,
text: i
}));
}
}
</script>
<script type="text/javascript">
var selectId=1;
function GetDynamicTextBox(value, value1, value2) {
return '<div class="col-md-4 bmargindiv1"><label for="qualification" accesskey="Q"><span class="required">*</span> Qualification</label>' +
'<input name = "txtQualification" id="txtQualification" type="text" value = "' + value + '" />' +
'</div>' +
'<div class="col-md-5 bmargindiv1">' +
'<label for="college" accesskey="C"><span class="required">*</span> College</label>' +
'<input type="text" ID="txtCollege" name="college" value = "' + value1 + '" />' +
'</div>' +
'<div class="col-md-2 bmargindiv1">' +
'<label for="passingyear" accesskey="Q"><span class="required">*</span> Passing Year</label>' +
'<select ID="txtPassingYear' + selectId + '" name="passingyear">' +
'</select>' +
'</div>' +
'<div class="col-md-1 bmargindiv1">' +
'<label for="action" accesskey="C"> </label>' +
'<button type="button" class="btn btn-success btn-sm addbtn" id="Button1" onclick="AddTextBox(this)">+</button>' +
'<button type="button" class="btn btn-danger btn-sm minusbtn " id="Button2" style="display:none;" onclick = "RemoveTextBox(this)">-</button>'
}
function AddTextBox(objId) {
var div = document.createElement('li');
selectId++;
div.innerHTML = GetDynamicTextBox("", "", "");
document.getElementById("TextBoxContainer").appendChild(div);
$(objId).css('display', 'none');
$(objId).siblings("button.btn-danger").css('display', 'block');
var id = $(objId).closest('select');
console.log('id is', id);
var $dropdown = $('#txtPassingYear' + selectId);
getYears($dropdown);
}
function RemoveTextBox(div) {
$(div).closest("li").remove();
}
</script>

Categories