how to select all checkbox in javascript? - javascript

Script:-
<script type="text/javascript">
$(document).ready(function () {
var x = document.getElementById("currentPage").value;
if (x == null || x == "")
GetPage(parseInt(1));
else
GetPage(parseInt(x));
$('#pager').on('click', 'input', function () {
GetPage(parseInt(this.id));
document.getElementById("currentPage").value = parseInt(this.id);
});
});
function GetPage(pageIndex) {
//debugger;
$.ajax({
cache: false,
//url: "/EmailScheduler/",
url: '#(Url.RouteUrl("EmailScheduler"))',
type: "POST",
data: { "selectValue": pageIndex },
traditional: true,
dataType: "json",
success: function (data) {
//debugger;
$('#GridRows').empty();
$('#pager').empty();
var trHTML = '';
var htmlPager = '';
$.each(data.Customers, function (i, item) {
trHTML += ' <tbody class="table-hover"><tr>'
+ '<td class="text-left"><div class="checkbox" style="padding-left:50px;"><label><input type="checkbox" id=" ' + item.CustomerID + '" class="checkBoxClass"/></label></div></td>'
+ '<td class="text-left" id="tblFirstName"> ' + item.FirstName + '</td>'
+ '<td class="text-left" id="tblLastName"> ' + item.LastName + '</td>'
+ '<td class="text-left" id="tblEmailID"> ' + item.EmailID + '</td>'
+ '<td class="text-left" id="tblCustomerType"> ' + item.CustomerType + '</td>'
+ '<td class="text-left" id="tblCustomerDesignation" style="padding-left:40px;padding-right:30px;"> ' + item.CustomerDesignation + '</td></tr></tbody>'
});
$('#GridRows').append(trHTML);
if (data.Pager.EndPage > 1) {
htmlPager += '<ul class="pagination">'
if (data.Pager.CurrentPage > 1) {
htmlPager += '<li><input class="myButton" style="width:25px;height:25px;" type="button" id="1" style="font-weight:bold;" value="<<" /></li><li><input type="button" class="myButton" id="' + (data.Pager.CurrentPage - 1) + '"value="<"></li>'
}
for (var page = data.Pager.StartPage; page <= data.Pager.EndPage; page++) {
htmlPager += '<li class="' + (page == data.Pager.CurrentPage ? "active" : "") + '"><input type="button" class="myButton" id="' + page + '" value="' + page + '"/></li>'
}
if (data.Pager.CurrentPage < data.Pager.TotalPages) {
htmlPager += '<li><input type="button" class="myButton" id="' + (data.Pager.CurrentPage + 1) + '" value=">"/></li><li><input type="button" class="myButton" id="' + (data.Pager.TotalPages) + '" value=">>"/></li>'
}
htmlPager += '</ul>'
}
$('#pager').append(htmlPager);
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
}
});
}
$(document).on('click', '#GridRows .checkBoxClass',
function () {
var cid = $(this).attr('id');
debugger;
var CustomerIDArray = [];
var hidCID = document.getElementById("hfCustomerID");
if (hidCID != null && hidCID != 'undefined') {
var CustID = hidCID.value;
CustomerIDArray = CustID.split("|");
var currentCheckboxValue = cid;
var index = CustomerIDArray.indexOf(currentCheckboxValue);
//debugger;
if (index >= 0) {
var a = CustomerIDArray.splice(index, 1);
//alert("a" + a);
}
else {
CustomerIDArray.push(currentCheckboxValue);
//alert('pushed value:' + CustomerIDArray);
}
hidCID.value = CustomerIDArray.join("|");
//alert('Final' + hidCID.value);
}
else {
alert('undefined');
}
});
$(document).on('click', '#cbSelectAll', function () {
if (this.checked) {
//$(':checkbox').each(function () {
$("#GridRows .checkBoxClass").each(function () {
//debugger;
this.checked = true;
var selectall = document.getElementsByClassName(".checkBoxClass");
var custid = $(this).attr('id');
console.log('custid' + custid);
var hidSelectAll = document.getElementById("hfSelectAll");
var hidCustomer = document.getElementById("hfCustomerID");
hidCustomer = '';
var str = 'Select All';
hidSelectAll.value = str;
console.log(hidSelectAll);
});
$("#GridRows .checkBoxClass").change(function () {
if (!$(this).prop("checked")) {
$("#cbSelectAll").prop("checked", false);
var cid = $(this).attr('id');
console.log('cid' + cid);
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'Select All + unselected values';
hidSelectAll.value = str;
console.log(hidSelectAll);
}
});
}
else {
$(':checkbox').each(function () {
this.checked = false;
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'UnSelect All';
hidSelectAll.value = str;
console.log(hidSelectAll);
});
$(".checkBoxClass").change(function () {
if (!$(this).prop("checked")) {
$("#cbSelectAll").prop("checked", false);
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'unSelect All + selected values';
hidSelectAll.value = str;
console.log(hidSelectAll);
}
});
}
});
</script>
HTML:-
<div class="table-responsive" style="padding-left:20%;">
<table id="tCustomer" class="table-fill" style="float:left;">
<thead>
<tr>
<th class="text-left">
Select All
<div class="checkbox">
<input style="margin-left:15px;" type="checkbox" id="cbSelectAll" class="checkBoxClass"/>
</div>
</th>
<th class="text-left" style="padding-left:27px;">
First Name
</th>
<th class="text-left" style="padding-left:32px;">
Last Name
</th>
<th class="text-left" style="padding-left:40px;padding-right: 60px;">
Email-ID
</th>
<th class="text-left" style="padding-left:30px;padding-right: 40px;">
Customer Type
</th>
<th class="text-left" style="padding-left:15px;">
Customer Designation
</th>
</tr>
</thead>
</table>
<div id="GridRows" style="width:65%;">
</div>
</div>
<div id="pager"></div>
<input type="hidden" id="currentPage">
<input type="hidden" id="hfCustomerID"/>
<input type="hidden" id="hfSelectAll" />
In this When click on Select all checkbox then all values from should
be checked but when select all checked box is checked then only value
from current pagination got selected.
table contain is generated from ajax to avoid loss of checked value
while page load.

In your case
$(".checkBoxClass").prop('checked', true);
should work too.
The .prop() method gets the property value for only the first element in the matched set. It returns undefined for the value of a property that has not been set, or if the matched set has no elements.
Read More: Here

In jquery you can achieve this by:
$('input[type="checkbox"]').prop('checked', true);
It will make all checkbox checked.

Related

How to pass an array data from controller to blade file Laravel

I'm trying to pass an array from Controller to Blade
My Controller:
public function socaucuachuong($id){
$socaucuachuong = CauHoi::groupBy('chuong')->select('chuong', CauHoi::raw('count(id) as Total'))->where('idmonthi','=', $id)->get()->toArray();
return view('DeThi::dethi')->with('socaucuachuong', $socaucuachuong);
}
My Blade file:
$('select').select();
function get_units(id) {
var list = $('#dschuong');
list.empty();
var url = "{{ route('dethi.socaucuachuong') }}"+'/'+ id;
var success = function (result) {
if (result.length <= 0) {
var item = '<div class="input-field"><input type="text" disabled value="Môn này hiện chưa có câu hỏi nào"></div>';
list.append(item);
} else {
for (i = 0; i < result.length; i++) {
var item = '<div class="input-field"><label for="unit-' + result[i].chuong + '">Nhập số câu hỏi chương ' + result[i].chuong + ' (có ' + result[i].Total + ' câu) <span class="failed">(*)</span></label><input type="number" max="' + result[i].Total + '" class="unit_input" onchange="set_sum(' + result[i].Total + ')" name="unit-' + result[i].chuong + '" id="unit-' + result[i].chuong + '" required></div>';
list.append(item);
}
}
};
$.get(url, success);
}
My Route file:
Route::post('socaucuachuong', 'DeThiController#socaucuachuong')->name('dethi.socaucuachuong');
You can get array values in blade like this.
<script>
var socaucuachuong = #JSON($socaucuachuong); // this will be array value.
</script>

Can't add more than 10 rows to my datatable

I want to add dynamically rows to my DataTable to save them, but when I achieve 10 rows I can't get more than that, and it can't even save it.
// Add row into table
var addRowTable = {
options: {
addButton: "#addToTable",
table: "#addrowExample",
dialog: {}
},
initialize: function() {
this.setVars().build().events()
},
setVars: function() {
return this.$table = $(this.options.table), this.$addButton = $(this.options.addButton), this.dialog = {}, this.dialog.$wrapper = $(this.options.dialog.wrapper), this.dialog.$cancel = $(this.options.dialog.cancelButton), this.dialog.$confirm = $(this.options.dialog.confirmButton), this
},
build: function() {
//var window.table = this.datatable;
return this.datatable = this.$table.DataTable({
aoColumns: [null, null, null, null, null, null, {
bSortable: !1
}],
"sDom": 't'
}), window.dt = this.datatable, this
},
events: function() {
var object = this;
return this.$table.on("click", "button.button-save", function(e) {
e.preventDefault(), object.rowSave($(this).closest("tr"))
}).on("click", "button.button-discard", function(e) {
e.preventDefault(), object.rowCancel($(this).closest("tr"))
}).on("click", "button.button-remove", function(e) {
e.preventDefault();
var $row = $(this).closest("tr");
var sumToRemove = $(this).closest('tr').find('td:eq(5)').text();
//Update sum value
Application.sumCharge -= parseFloat(sumToRemove);
$("#lb-sum").html(Application.sumCharge.toFixed(2));
object.rowRemove($row)
}), this.$addButton.on("click", function(e) {
e.preventDefault(), object.rowAdd()
}), this.dialog.$cancel.on("click", function(e) {
e.preventDefault(), $.magnificPopup.close()
}), this
},
rowAdd: function() {
this.$addButton.attr({
disabled: "disabled"
});
var actions, data, $row;
actions = ['<button class="btn btn-sm btn-icon btn-pure btn-default on-editing button-save" data-toggle="tooltip" data-original-title="Save" hidden><i class="icon-drawer" aria-hidden="true"></i></button>', '<button class="btn btn-sm btn-icon btn-pure btn-default on-editing button-discard" data-toggle="tooltip" data-original-title="Discard" hidden><i class="icon-close" aria-hidden="true"></i></button>', '<button class="btn btn-sm btn-icon btn-pure btn-default on-default button-remove"><i class="icon-trash" aria-hidden="true"></i></button>'].join(" "), data = this.datatable.row.add(["", "", "", "", "", "", actions]), ($row = this.datatable.row(data[0]).nodes().to$()).addClass("adding").find("td:last").addClass("actions"), this.rowEdit($row), this.datatable.order([0, "asc"]).draw()
},
rowCancel: function($row) {
var $actions, data;
$row.hasClass("adding") ? this.rowRemove($row) : (($actions = $row.find("td.actions")).find(".button-discard").tooltip("hide"), $actions.get(0) && this.rowSetActionsDefault($row), data = this.datatable.row($row.get(0)).data(), this.datatable.row($row.get(0)).data(data), this.handleTooltip($row), this.datatable.draw())
},
rowEdit: function($row) {
var counter = 0;
var data, object = this;
data = this.datatable.row($row.get(0)).data(), $row.children("td").each(function(i) {
var $this = $(this);
if (counter == 0) {
Application.tableLength++;
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<label style="font-weight: 400 !important">' + Application.tableLength + '</label>');
} else if (counter > 0 && counter < 5) {
if (counter == 1) {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}" data-provide="datepicker" data-date-autoclose="true" class="form-control input-date" value="' + data[i] + '" required>');
} else if (counter == 2) {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input type="text" class="form-control" value="' + data[i] + '" required>');
} else if (counter == 3) {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input type="text" class="form-control" value="' + data[i] + '" required>');
} else if (counter == 4) {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input type="text" class="form-control" value="' + data[i] + '" required>');
}
} else {
$this.hasClass("actions") ? object.rowSetActionsEditing($row) : $this.html('<input type="number" step="0.01" class="form-control" value="' + data[i] + '" required>');
}
counter++;
})
},
rowSave: function($row) {
if ($('#form').get(0).reportValidity()) {
var $actions, object = this,
values = [],
counter = 0;
$row.hasClass("adding") && (this.$addButton.removeAttr("disabled"), $row.removeClass("adding")), values = $row.find("td").map(function() {
var $this = $(this),
input = '',
input_value = $this.find("label,input,textarea").val();
if ($this.hasClass("actions")) {
return object.rowSetActionsDefault($row), object.datatable.cell(this).data();
} else {
if (counter == 0) {
input = $this.find("label").text();
} else if (counter > 0 && counter < 5) {
if (counter == 1) {
input = "<input type='hidden' name='date[]' value='" + input_value + "'>";
}
if (counter == 2) {
input = "<input type='hidden' name='description[]' value='" + input_value + "'>";
} else if (counter == 3) {
input = "<input type='hidden' name='details[]' value='" + input_value + "'>";
} else if (counter == 4) {
input = "<input type='hidden' name='charge_observation[]' value='" + input_value + "'>";
}
} else {
input = "<input type='hidden' name='sum[]' value='" + input_value + "'>";
Application.sumCharge += parseFloat(input_value);
$("#lb-sum").html(Application.sumCharge.toFixed(2));
}
counter++;
return $.trim($this.find("label,input,textarea").val()) + input;
}
}), ($actions = $row.find("td.actions")).find(".button-save").tooltip("hide"), $actions.get(0) && this.rowSetActionsDefault($row), this.datatable.row($row.get(0)).data(values), this.handleTooltip($row), this.datatable.draw()
}
},
rowRemove: function($row) {
$row.hasClass("adding") && this.$addButton.removeAttr("disabled"), this.datatable.row($row.get(0)).remove().draw()
},
rowSetActionsEditing: function($row) {
$row.find(".on-editing").removeAttr("hidden"), $row.find(".on-default").attr("hidden", !0)
},
rowSetActionsDefault: function($row) {
$row.find(".on-editing").attr("hidden", !0), $row.find(".on-default").removeAttr("hidden")
},
handleTooltip: function($row) {
$row.find('[data-toggle="tooltip"]').tooltip()
}
};
$(function() {
addRowTable.initialize()
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped fixed" cellspacing="0" id="addrowExample">
<thead>
<tr>
<th style="width: 5%">#</th>
<th>{{ __('all.date')}}</th>
<th>{{ __('all.description')}}</th>
<th>{{ __('all.details')}}</th>
<th style="width: 25%">{{ __('all.observation')}}</th>
<th>{{ __('all.sum')}}</th>
<th style="width: 10%">{{ __('all.action')}}</th>
</tr>
</thead>
<tbody>
</tbody>
<tbody>
</tbody>
</table>
<h6 class="p-10 bg-primary text-light text-right">{{ __('all.total sum')}} : <b id="lb-sum">0.00</b> <small>MAD</small></h6>
</div>

my input return me undefined even though the data is catch. using CRUD js

<body>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-name" placeholder="New country ">
<input type="number" id="add-popu" placeholder="New population">
<input type="submit" value="Add">
</form>
<div id="spoiler" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-popu">
<input type="submit" value="Ok" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tbody id="countries"></tbody>
<tbody id="popultns"></tbody>
</table>
<script type="text/javascript" src="main.js"></script>
<script>
var app = new function()
{ this.el = document.getElementById('countries');
this.el = document.getElementById('popultns');
let loadTableData = data2;
this.Count = function(data)
{ var el = document.getElementById('counter');
var name = 'country2';
var pop = 'popu2'
if (data)
{ if (data > 1)
{ name = 'countries' ;
pop = "popultns" ;
}
el.innerHTML = data + ' ' + name + ' ' + pop ;
}
else
{ el.innerHTML = 'No ' + name + ' ' + pop ; }
};
this.FetchAll = function()
{ var data = '';
if (loadTableData.length > 0)
{ for (i = 0; i < loadTableData.length; i++)
{ data += '<tr>';
data += '<td>' + loadTableData[i].country + '</td>';
data += '<td>' + loadTableData[i].population + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(loadTableData.length);
return this.el.innerHTML = data;
};
this.Add = function ()
{ el = document.getElementById('add-name');
el2 = document.getElementById('add-popu');
// Get the value
var country2 = el.value;
var pop = el2.value;
if (country2)
{ // Add the new value
loadTableData.push(country2.trim() );
// Reset input value
el.value = '';
//el2.value = '';
// Dislay the new list
this.FetchAll();
}
};
the image is the ui tht im working for the function
I'm supposed to auto-generate the table based on the data available from my main.js script which is in JSon format. There is no problem with the data loading since the data can be display in my html file. However, the problem comes whn my data is returned undefined on my auto generated table whn i click the 'add' button to update the data in the table. Whn i click in the edit button, the data is get correctly. only whn the display, it returns me undefined.
i know how alrdy.
here i attach the code & sample of the data i hv done.
hopefully this would help fresh grad like me who hv trouble in undrsntdng CRUD
<html>
<head>
<meta charset="UTF-8">
<title>Countries CRUD</title>
<style>
input[type='submit'], button, [aria-label]{
cursor: pointer;
}
#spoiler{
display: none;
}
</style>
</head>
<body>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-name" placeholder="New country ">
<input type="number" id="add-popu" placeholder="New population">
<input type="submit" value="Add">
</form>
<div id="spoiler" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-popu">
<input type="submit" value="Ok" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tbody id="countries"></tbody>
<tbody id="popultns"></tbody>
</table>
<script type="text/javascript" src="main.js"></script>
<script>
var app = new function()
{ this.el = document.getElementById('countries' && 'popultns');
//this.el = document.getElementById('popultns');
let loadTableData = data2;
this.Count = function(data)
{ var el = document.getElementById('counter');
var name = 'country2';
var pop = 'popu2'
if (data)
{ if (data > 1)
{ name = 'countries' ;
pop = "populations" ;
}
el.innerHTML = data + ' ' + name + ' ' + pop ;
}
else
{ el.innerHTML = 'No ' + name + ' ' + pop ; }
};
this.FetchAll = function()
{ var data = '';
if (loadTableData.length > 0)
{ for (i = 0; i < loadTableData.length; i++)
{ data += '<tr>';
data += '<td>' + loadTableData[i].country + '</td>';
data += '<td>' + loadTableData[i].population + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(loadTableData.length);
return this.el.innerHTML = data;
};
this.Add = function ()
{ el = document.getElementById('add-name');
el2 = document.getElementById('add-popu');
// Get the value
var country2 = el.value;
var popltn = el2.value;
if (country2 && popltn )
{ // Add the new value
//loadTableData.push(country2.trim() );
loadTableData.push({country: country2, population:popltn});
// Reset input value
el.value = '';
el2.value = '';
// Dislay the new list
this.FetchAll();
}
};
this.Edit = function (item)
{ var el3 = document.getElementById('edit-name');
var el4 = document.getElementById('edit-popu');
// Display value in the field
let index = item;
el3.value = loadTableData[index].country;
el4.value = loadTableData[index].population;
// Display fields
document.getElementById('spoiler').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function()
{
// Get value
var country2 = el3.value;
var popltn = el4.value;
//console.log({country2, pop});
if (country2 || pop)
//console.log(country2);
{ // Edit value (strt,del,replace)
console.log(country2,popltn);
console.log(index, 1,({country2,popltn}));
//update array
loadTableData[index].country = el3.value;
loadTableData[index].population = el4.value;
//self.loadTableData.splice(index, 1,({country2,popltn}));
//console.log(index, 1, pop.trim());
//self.loadTableData.splice(index, 1, pop.trim());
// Display the new list
self.FetchAll();
// Hide fields
CloseInput();
}
}
};
this.Delete = function (item)
{
// Delete the current row
loadTableData.splice(item, 1);
// Display the new list
this.FetchAll();
};
}
app.FetchAll();
function CloseInput()
{ document.getElementById('spoiler').style.display = 'none';}
</script>
</body>
</html>

Weird JS Behavior With Bootstrap Sliders

So I recieved help from an internet saint to vastly improve my code to create a bootstrap slider per list item within a JS for loop, but now it is behaving erratically.
Sometimes it works perfectly, others it creates new items but not sliders (just a text input field), and others it only creates one item per list.
Any great minds see where I'm going wrong?
var proArray = [];
function addPro() {
var val = document.getElementById("proInput").value.trim();
document.getElementById("proForm").reset();
if (val.length == 0) {
return;
}
if (document.getElementById('proInput' + val) == null) {
proArray.push({id: val, slider: null});
} else {
return;
}
for (var i = 0; i < proArray.length; i++) {
var ele = document.getElementById('proInput' + proArray[i].id);
if (ele == null) {
var newItem = "<li><p>" + proArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='proInput" +
proArray[i].id + "' data-slider-id='SIDproInput" + proArray[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById("proList").innerHTML += newItem;
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function(value) {
return 'Current value: ' + value;
}
});
} else {
(function(i) {
setTimeout(function() {
var val = proArray[i].slider.getValue();
proArray[i].slider.destroy();
document.getElementById('SIDproInput' + proArray[i].id).remove();
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function (value) {
return 'Current value: ' + value;
}
});
proArray[i].slider.setValue(val);
}, 100);
})(i);
}
}
}
var conArray = [];
function addCon() {
var valCon = document.getElementById("conInput").value.trim();
document.getElementById("conForm").reset();
if (valCon.length == 0) {
return;
}
if (document.getElementById('conInput' + valCon) == null) {
conArray.push({id: valCon, slider: null});
} else {
return;
}
for (var i = 0; i < conArray.length; i++) {
var ele = document.getElementById('conInput' + conArray[i].id);
if (ele == null) {
var newItem = "<li><p>" + conArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='conInput" +
conArray[i].id + "' data-slider-id='SIDconInput" + conArray[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById("conList").innerHTML += newItem;
conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
formatter: function(value) {
return 'Current value: ' + value;
}
});
} else {
(function(i) {
setTimeout(function() {
var valCon = conArray[i].slider.getValue();
conArray[i].slider.destroy();
document.getElementById('SIDconInput' + conArray[i].id).remove();
conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
formatter: function (value) {
return 'Current value: ' + value;
}
});
conArray[i].slider.setValue(valCon);
}, 100);
})(i);
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>
<div class="col-sm-6">
<h2>Pros</h2>
<p>The Good Stuff</p>
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
<div onclick="addPro()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
</div> <!-- pros -->
<div class="col-sm-6">
<h2>Cons</h2>
<p>The Bad Stuff</p>
<form id="conForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
<div onclick="addCon()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Costs</h3>
<ul class="text-left" id="conList">
</ul>
</div> <!-- cons -->
Because you have two lists you can use two arrays:
var proArray = [];
var conArray = [];
The inline functions can be changed in order to pass the list prefix as parameter:
newAdd('pro')
newAdd('con')
And so you can adjust the addPro function to these changes.
From comment:
If I type in "#" or "?" as an item in your snippet above it shows the error. Not for you?
In order to solve such an issue you need to escape those chars when creating the slider:
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' +
arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').....
The snippet:
var proArray = [];
var conArray = [];
function newAdd(listIdPrefix) {
var val = document.getElementById(listIdPrefix + "Input").value.trim();
document.getElementById(listIdPrefix + "Form").reset();
if (val.length == 0) {
return;
}
var arr;
if (document.getElementById(listIdPrefix + 'Input' + val) == null) {
if (listIdPrefix == 'pro') {
proArray.push({id: val, slider: null});
arr = proArray;
} else {
conArray.push({id: val, slider: null});
arr = conArray;
}
} else {
return;
}
for (var i = 0; i < arr.length; i++) {
var ele = document.getElementById(listIdPrefix + 'Input' + arr[i].id);
if (ele == null) {
var newItem = "<li><p>" + arr[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='" + listIdPrefix + "Input" +
arr[i].id + "' data-slider-id='SID" + listIdPrefix + "Input" + arr[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById(listIdPrefix + "List").innerHTML += newItem;
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
formatter: function (value) {
return 'Current value: ' + value;
}
});
} else {
(function (i, arr) {
setTimeout(function () {
var val = arr[i].slider.getValue();
arr[i].slider.destroy();
document.getElementById('SID' + listIdPrefix + 'Input' + arr[i].id).remove();
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
formatter: function (value) {
return 'Current value: ' + value;
}
});
arr[i].slider.setValue(val);
}, 100);
})(i, arr);
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>
<div class="col-sm-6">
<h2>Pros</h2>
<p>The Good Stuff</p>
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
<div onclick="newAdd('pro')" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
</div> <!-- pros -->
<div class="col-sm-6">
<h2>Cons</h2>
<p>The Bad Stuff</p>
<form id="conForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
<div onclick="newAdd('con')" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Costs</h3>
<ul class="text-left" id="conList">
</ul>
</div>

Javascript display problems with dynamic dropdowns

experts! I have some problems with two dynamic dropdown menus. Here is my fiddle:
Demo
Here is my jQuery and Javascript:
var num_rows = 1;
var num_tests = 1;
var myArray = new Array();
function firstSelection(id) {
var index = id.replace( /\D+/g, '');
var item = $("#select" + index + "").val();
var object = item.replace(/\d/g, "");
var table = $("#test");
if(object == 'analize') {
table.find('tr').each(function(i) {
$("#selectTest" + i + "").empty();
$("#selectTest" + i + "").append("<option value=''/><option value='analizetest1'>AnalizeTest1</option><option value='analizetest2'>AnalizeTest2</option><option value='analizetest3'>AnalizeTest3</option>");
});
}
else if(object == 'create') {
table.find('tr').each(function(i) {
$("#selectTest" + i + "").empty();
$("#selectTest" + i + "").append("<option value=''/><option value='createtest1'>CreateTest1</option><option value='createtest2'>CreateTest2</option>");
});
}
else if(object == 'draft') {
table.find('tr').each(function(i) {
$("#selectTest" + i + "").empty();
$("#selectTest" + i + "").append("<option value=''/><option value='drafttest1'>DraftTest1</option><option value='drafttest2'>DraftTest2</option><option value='drafttest3'>DraftTest3</option>");
});
}
else {
table.find('tr').each(function(i) {
$("#selectTest" + i + "").empty();
});
}
}
$(document).ready(function() {
$("#addObjekt").click(function() {
num_rows = $("#objectTable tr").length;
$("#objectTable").append("<tr id='objectRow" + num_rows + "'><td><input class='text' type='text' id='pbz" + num_rows + "' name='pbz" + num_rows + "' value='" + num_rows + "' readonly/></td><td><select id='select" + num_rows + "'><option/><option value='analize" + num_rows + "'>Analize</option><option value='create" + num_rows + "'>Create</option><option value='draft" + num_rows + "'>Draft</option></select></td><td><button type='button' id='selectButton" + num_rows + "' onclick='firstSelection(id);'>Select</button></td><td><button type='button' id='copy" + num_rows + "'>Copy</button></td></tr>");
});
$("#deleteObjekt").click(function() {
var row = $("#objectTable tr").length - 1;
if(row > 1) {
$("#objectRow" + row + "").remove();
return false;
}
else {
// do nothing
}
});
$("#addTest").click(function() {
num_tests = $("#test tr").length;
$("#test").append("<tr id='testRow" + num_tests + "'><td><input class='text' type='text' id='zaehler" + num_tests + "' name='zaehler" + num_tests + "' value='" + num_rows + "-" + num_tests + "' readonly/></td><td><select id='selectTest" + num_tests + "'></select></td><td><button type='button' id='parameter" + num_tests + "'>Parameter</button></td><td></td><td></td></tr>");
});
$("#deleteTest").click(function() {
var test_row = $("#test tr").length - 1;
if(test_row > 1) {
$("#testRow" + test_row + "").remove();
return false;
}
else {
// do nothing
}
});
});
function showMatrix() {
num_rows = $("#objectTable tr").length - 1;
num_tests = $("#test tr").length;
for(var x = 0; x < num_rows; x++) {
myArray[x] = new Array();
myArray[x] = $("#select" + (x + 1) + "").val();
for(var z = 0; z < num_tests; z++) {
myArray[x][z] = firstSelection.item + firstSelection.index;
}
}
alert(myArray);
}
The problems are:
The second dropdown list doesn't get populated based on the selection of the first one yet. For some reason it is not working properly in the fiddle, it is running fine in the environment I use.
How can I change the code, so that I see the second dropdown populated also for the new rows added later, not only for the already existing ones?
Last, I want the rows on the right side to be "attached" only to the single object they are linked to on the left side. Which means that selecting an object on the left side should only display its respective tests. I am not fluent in Javascript, I started with the idea of creating a two-dimensional array, but got stuck.
I know this might be a bit too much to ask, but I would deeply appreciate any advice. Thanks!
Method showMatrix can not access local variables of method firstSelection like that.
To make a variable in function showMatrix visible in function firstSelection, you have three choices:
make it a global,
make it an object property, or
pass it as a parameter when calling firstSelection from showMatrix.
The third option is probably the best options, globals are not recommended to work with and even though project properties are very optimal it's maybe not the best fit for your case.
Just make sure that firstSelection returns the variables you need from it and access them within showMatrix. You can also make it return an object which holds the values of the variables that you need.
function firstSelection(id) {
var index = id.replace( /\D+/g, '');
var item = $("#select" + index + "").val();
// ... some code
var vars = {index: index, item: item};
return vars;
Ensure that the function firstSelection is in the scope. Move that function inside
$(document).ready(function()
{
//...
});;
It will work if your code is correct.
I suggest this because I got the following error while running your code:
Uncaught ReferenceError: firstSelection is not defined
Ok Try this. It is working. Before that edit the HTML and JS like the following:
HTML:
<table id="panel" class="panel">
<tr>
<td>
<table id="objectTable" class="objectTable">
<tr id="initial">
<td width="20px">Number</td>
<td>Object</td>
<td align="right"><button type="button" id="addObjekt" href="#">+</button><button type="button" id="deleteObjekt" href="#">-</button></td>
<td></td>
</tr>
<tr id="objectRow1">
<td><input class="text" type="text" id="pbz1" name="pbz1" value="1" readonly/></td>
<td><select id="select1">
<option/>
<option value="analize1">Analize</option>
<option value="create1">Create</option>
<option value="draft1">Draft</option>
</select></td>
<td><button type="button" id="selectButton1">Select</button></td>
<td><button type="button" id="copy1">Copy</button></td>
</tr>
</table>
</td>
<td>
<table id="test" class="test">
<tr>
<td>Subnumber</td>
<td>Test <button type="button" id="addTest" href="#">+</button><button type="button" id="deleteTest" href="#">-</button></td>
<td></td>
<td></td>
</tr>
<tr id="testRow1">
<td><input class="text" type="text" id="zaehler1" name="zaehler1" value="1-1" readonly/></td>
<td><select id="selectTest1">
</select></td>
<td><button type="button" id="parameter1">Parameter</button></td>
<td></td>
</tr>
</table>
</td>
</tr>
</table>
JS:
var num_rows = 1;
var num_tests = 1;
var myArray = new Array();
var globalIndex = 0;
var globalObject = '';
$(document).ready(function() {
$('#selectButton1').click(function(){
firstSelection(this.id);
});
function firstSelection(id) {
var index = id.replace( /\D+/g, '');
var item = $("#select" + index + "").val();
var object = item.replace(/\d/g, "");
globalIndex = index;
globalObject = object;
var vars = {index: index, item: item};
//var table = $("#test");
document.getElementById("zaehler1").value = index + '-1';
if(object == 'analize') {
$("#selectTest1").empty();
$("#selectTest1").append("<option value=''/><option value='analizetest1'>AnalizeTest1</option><option value='analizetest2'>AnalizeTest2</option><option value='analizetest3'>AnalizeTest3</option>");
}
else if(object == 'create') {
$("#selectTest1").empty();
$("#selectTest1").append("<option value=''/><option value='createtest1'>CreateTest1</option><option value='createtest2'>CreateTest2</option>");
}
else if(object == 'draft') {
$("#selectTest1").empty();
$("#selectTest1").append("<option value=''/><option value='drafttest1'>DraftTest1</option><option value='drafttest2'>DraftTest2</option><option value='drafttest3'>DraftTest3</option>");
}
else {
$("#selectTest1").empty();
}
return vars;
}
$("#addObjekt").click(function() {
num_rows = $("#objectTable tr").length;
$("#objectTable").append("<tr id='objectRow" + num_rows + "'><td><input class='text' type='text' id='pbz" + num_rows + "' name='pbz" + num_rows + "' value='" + num_rows + "' readonly/></td><td><select id='select" + num_rows + "'><option/><option value='analize" + num_rows + "'>Analize</option><option value='create" + num_rows + "'>Create</option><option value='draft" + num_rows + "'>Draft</option></select></td><td><button type='button' id='selectButton" + num_rows + "' onclick='firstSelection(id);'>Select</button></td><td><button type='button' id='copy" + num_rows + "'>Copy</button></td></tr>");
});
$("#deleteObjekt").click(function() {
var row = $("#objectTable tr").length - 1;
if(row > 1) {
$("#objectRow" + row + "").remove();
return false;
}
else {
// do nothing
}
});
$("#addTest").click(function() {
num_tests = $("#test tr").length;
$("#test").append("<tr id='testRow" + num_tests + "'><td><input class='text' type='text' id='zaehler" + num_tests + "' name='zaehler" + num_tests + "' value='" + globalIndex + "-" + num_tests + "' readonly/></td><td><select id='selectTest" + num_tests + "'></select></td><td><button type='button' id='parameter" + num_tests + "'>Parameter</button></td><td></td><td></td></tr>");
$("#test").find('tr').each(function(i) {
if(globalObject == 'analize') {
$("#selectTest" + i + "").append("<option value=''/><option value='analizetest1'>AnalizeTest1</option><option value='analizetest2'>AnalizeTest2</option><option value='analizetest3'>AnalizeTest3</option>");
}
else if(globalObject == 'create') {
$("#selectTest" + i + "").append("<option value=''/><option value='createtest1'>CreateTest1</option><option value='createtest2'>CreateTest2</option>");
}
else if(globalObject == 'draft') {
$("#selectTest" + i + "").append("<option value=''/><option value='drafttest1'>DraftTest1</option><option value='drafttest2'>DraftTest2</option><option value='drafttest3'>DraftTest3</option>");
}
else {
//nothing
}
});
});
$("#deleteTest").click(function() {
var test_row = $("#test tr").length - 1;
if(test_row > 1) {
$("#testRow" + test_row + "").remove();
return false;
}
else {
// do nothing
}
});
});
function showMatrix() {
num_rows = $("#objectTable tr").length - 1;
num_tests = $("#test tr").length;
for(var x = 0; x < num_rows; x++) {
myArray[x] = new Array();
myArray[x] = $("#select" + (x + 1) + "").val();
for(var z = 0; z < num_tests; z++) {
myArray[x][z] = firstSelection.item + firstSelection.index;
}
}
alert(myArray);
}
Demo

Categories