jQuery for removing rows of a table - javascript

I have some javascript for checking if the table has the same number of rows as that in the select option, if not then delete those rows, so I wrote the following:
$(document).ready(function() {
$("#noOfSegments").change(function() {
var counter = $("#noOfSegments").val();
for (i = 0; i < counter; i++) {
var row = $("<tr><td>" + i + "</td><td>" + i + "</td><td>" + i + "</td><td>" + i + "</td><td>" + i + "</td></tr>");
$("#segmentTable").append(row);
}
if (segmentTable.rows.length > counter) {
var rowLen = segmentTable.rows.length;
var delIndex = 1;
for (i = 0; i <= rowLen; i++) {
if (i > counter) {
segmentTable.deleteRow(i - delIndex);
delIndex++;
}
}
}
});
});
<select id="noOfSegments">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
and #segmentTable is my table id
but I want some jQuery code for doing same, can you help me write it?
Thanks in advance.

-Update-
Demo: http://jsfiddle.net/C7Ygh/
js:
$("#noOfSegments").change(function(){
var count = $("#noOfSegments").val();
var rowcount = $("#segmentTable tr").length;
while (rowcount > count) {
$("#segmentTable tr:last-child").remove();
rowcount = $("#segmentTable tr").length;
}
});

I do not understand where is the chance for extra rows as you are appending rows in for loop based on select value.
But based on the counter if you want to remove extra elements, check how many are added extra and remove them.
var counter = $('#noOfSegments').val(),
Rows = $("#segmentTable > tr");
if(Rows.length > counter){
Rows.slice(counter - Rows.length).each(function(){
$(this).remove();
});
}

Related

How to design UI for multiple selection in a drop down list?

I'm setting up a UI for my application. I would like to have some idea about your guy's experiences.
I need to have multiple selections from different sources.
Input (Sources): Companies, Department. Multiple companies, departments allowed.
Output: People who belong to selected items
For example, I can select company1, company2, and select department1, department2 from a dropdown list.
I select one by one property( Select company1, company2, then go to another dropdown to select department1,2...)
In the end, I have company1,2,3 checked, department 1,2,3 checked.
Then the result will tell me user1...n belong to the selected list above.
The problem is nothing if I have only a few company and department but if coming to be complicated if I have multiple (more than 6 companies and departments). I can't come up with any good UI design for this problem.
I expected the output of (selected(checked company1,2,3... + department1,2,3)) -> result person1,2,3 belong to checked items.
Try the following code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Select Company: </p>
<select name="companySelector" multiple>
</select>
<p>Select Department: </p>
<select name="departmentSelector" multiple>
</select>
<p>Persons: </p>
<ul id="persons">
</ul>
<script>
var companySelector = document.querySelector("[name='companySelector']");
var departmentSelector = document.querySelector("[name='departmentSelector']");
var persons = document.getElementById("persons");
var temp, temp2 = 0;
var database = {
company_1: {
c1_department1: ["c1d1person1", "c1d1person2", "c1d1person3", "c1d1person4"],
c1_department2: ["c1d2person1", "c1d2person2", "c1d2person3", "c1d2person4"],
c1_department3: ["c1d3person1", "c1d3person2", "c1d3person3", "c1d3person4"]
},
company_2: {
c2_department1: ["c2d1person1", "c2d1person2", "c2d1person3", "c2d1person4"],
c2_department2: ["c2d2person1", "c2d2person2", "c2d2person3", "c2d2person4"],
c2_department3: ["c2d3person1", "c2d3person2", "c2d3person3", "c2d3person4"]
},
company_3: {
c3_department1: ["c3d1person1", "c3d1person2", "c3d1person3", "c3d1person4"],
c3_department2: ["c3d2person1", "c3d2person2", "c3d2person3", "c3d2person4"],
c3_department3: ["c3d3person1", "c3d3person2", "c3d3person3", "c3d3person4"]
},
company_4: {
c4_department1: ["c4d1person1", "c4d1person2", "c4d1person3", "c4d1person4"],
c4_department2: ["c4d2person1", "c4d2person2", "c4d2person3", "c4d2person4"],
c4_department3: ["c4d3person1", "c4d3person2", "c4d3person3", "c4d3person4"]
},
company_5: {
c5_department1: ["c5d1person1", "c5d1person2", "c5d1person3", "c5d1person4"],
c5_department2: ["c5d2person1", "c5d2person2", "c5d2person3", "c5d2person4"],
c5_department3: ["c5d3person1", "c5d3person2", "c5d3person3", "c5d3person4"]
}
}
for (temp in database) {
companySelector.innerHTML += '<option value="' + temp + '">' + temp.replace(/_/g, " ") + '</option>';
}
companySelector.onchange = function() {
departmentSelector.innerHTML = "";
var selectedCompnies = document.querySelectorAll("[name='companySelector'] option:checked");
for (var i = 0; i < selectedCompnies.length; i++) {
for (temp2 in database[selectedCompnies[i].value]) {
departmentSelector.innerHTML += '<option value="' + temp2 + '" data-company="' + selectedCompnies[i].value + '">' + temp2.replace(/_/g, " ") + '</option>'
}
}
}
departmentSelector.onchange = function() {
persons.innerHTML = "";
var selectedDepartments = document.querySelectorAll("[name='departmentSelector'] option:checked");
for (var i = 0; i < selectedDepartments.length; i++) {
var temp3 = selectedDepartments[i].dataset.company;
var prsonsArray = database[temp3][selectedDepartments[i].value];
for (var x = 0; x < prsonsArray.length; x++) {
persons.innerHTML += "<li>" + prsonsArray[x] + "</li>";
}
}
}
</script>
</body>
</html>
DEMO

comparing select box timings

<select id="ddlMinExp">
<option value="0">hour</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select id="mints1">
<option value="">minuts</option>
<option value="00">00</option>
<option value="30">30</option>
</select>
<select id="ddlMaxExp" class="slct">
<option value="0">hour</option>
</select>
<select id="mints">
<option value="">minuts</option>
<option value="00">00</option>
<option value="30">30</option>
</select>
JS:
<script>
$(function() {
$('#ddlMinExp').change(function() {
//var selectedMaxValue = Number($(this).val());
var selectedMinValue = Number($('#ddlMinExp').val());
// alert(selectedMinValue);
if (selectedMinValue < 12) {
//alert(selectedMinValue);
$(".slct option").remove();
for (i = selectedMinValue; i < 12; i++) {
$('select.slct').append('<option value="' + i + '"' + '>' + i + '</option>');
//alert(i);
}
}
$('body').on('change', '#mints1', function() {
var mints = Number($(this).val());
if (mints === 30) {
$(".slct option").remove();
var j = selectedMinValue + 1;
for (j; j < 12; j++) {
$('select.slct').append('<option value="' + j + '"' + '>' + j + '</option>');
//alert(i);
}
} else {
$(".slct option").remove();
for (i = selectedMinValue; i < 12; i++) {
$('select.slct').append('<option value="' + i + '"' + '>' + i + '</option>');
//alert(i);
}
}
});
});
})
</script>
if select from first select box 4 automatically 3rd select box starts from 4,but when even i select 30 from second select box 3rd select box should starts from 5, first time it is working,second time if i select 3 from first select box 3rd select box should stars from 4 becoz already second select box has the value 30,when ever i change first and second select boxes 3rd select box has to changesee fiddle link
Updated your fiddle, please check here https://jsfiddle.net/ka56qw6t/7/
I've added one more condition in $('#ddlMinExp').change(function() to check the value of 'mints1', if its 30 then increasing 'ddlMaxExp' by 1.
i have edited your whole code, i think its working as you expected, have a look at jsfidde
var selectedMinMnts = $('#ddlMntMin').val()!=="minuts"?Number($('#ddlMntMin').val()):null;
updateMaxTime(selectedMinHrs,selectedMinMnts);
});
$('body').on('change', '#ddlMntMin', function() {
var selectedMinHrs = $('#ddlHrsMin').val() !== "hour"?Number($('#ddlHrsMin').val()):null;
var selectedMinMnts = $('#ddlMntMin').val()!=="minuts"?Number($('#ddlMntMin').val()):null;
updateMaxTime(selectedMinHrs,selectedMinMnts);
});
function updateMaxTime(minHrs,minMnts){
if((minHrs && minHrs != null)){
if (minHrs < 12) {
//alert(selectedMinValue);
$(".ddlHrsMax option").remove();
for (i = minHrs; i < 12; i++) {
$('select.ddlHrsMax').append('<option value="' + i + '"' + '>' + i + '</option>');
//alert(i);
}
}
}
if((minMnts && minMnts != null)){
console.log(minMnts);
if (minMnts === 30) {
$(".ddlHrsMax option").remove();
var j = minHrs + 1;
for (j; j < 12; j++) {
$('select.ddlHrsMax').append('<option value="' + j + '"' + '>' + j + '</option>');
//alert(i);
}
} else {
$(".ddlHrsMax option").remove();
for (i = minHrs; i < 12; i++) {
$('select.ddlHrsMax').append('<option value="' + i + '"' + '>' + i + '</option>');
//alert(i);
}
}
}
}
})

Get the correspoding values from CSV

I need to solve one issue regarding csv. I have read all the values from csv (I have three fields like region,state,acc_name) and loaded into corresponding dropdown list.but my issue is if i select the region i need to get the corresponding state values from csv I have done something but not even get any single line code please help me to do that task.
My code is:
$(document).ready(function() {
// AJAX in the data file
$.ajax({
type: "GET",
url: "data.csv",
dataType: "text",
success: function(data) {
processData(data);
}
});
// Let's process the data from the data file
function processData(data) {
var table = $("<table />");
var rows = data.split(/\r\n|\n/);
for (var i = 1; i < rows.length - 1; i++) {
var row = $("<tr />");
var cells = rows[i].split(/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/);
for (var j = 0; j < rows.length; j++) {
var cell = $("<td />");
cell.html(cells[j]);
row.append(cell);
}
var usedNames = {};
$("select[name='company1'] > option").each(function() {
if (usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
$("select[name='company2'] > option").each(function() {
if (usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
$("select[name='company3'] > option").each(function() {
if (usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
var newvalue = cells[1].replace("\"", "");
//var newvalue=cells[1].trim();
var final1 = newvalue.replace("\"", "");
var pandu = cells[0];
$("#region").append("<option value =" + cells[0] + "> " + cells[0] + " </option>");
$("#state").append("<option value =" + final1 + "> " + final1 + "</option>");
$("#accname").append("<option value =" + cells[2] + ">" + cells[2] + "</option>");
table.append(row);
}
}
});
function getstate()
{
...
}
HTML:
Region:
<select id="region" class="select" name="company1" onchange="getstate()"></select>
<br> State:
<select id="accname" class="select" name="company3"></select>
<br> Acct_Name:
<select id="state" class="select" name="company2"></select>
<br>

Check if item exists in specific <td> by jquery

I have items names in drop down and a quantity text box. i am adding item and its quantity to table if quantity is greater then zero,
Now i want to check if item is already present in the table then just sum the quantity
<script>
$(document).ready(function(){
$("#addBtn").click(function(){
var rmnameList = document.getElementById("rname");
var name = rmnameList.options[rmnameList.selectedIndex].text;
var qty = $('#qty').val();
if (qty > 0)
{
var tbody = $('#rTable').children('tbody');
var table = tbody.length ? tbody : $('#rTable');
//Add row
table.append('<tr><td>'+ name + '</td><td>'+ qty +'</td></tr>');
}
});
});
</script>
I am unable to find the respective <td> element to update.
My jquery selector is :
$('#rTable tbody tr td:first-child')
and it returns:
[<td>​BUN​</td>​, <td>​Ketchup​</td>​, <td>​Banana​</td>​]
Use an attribute on the tr to store the rname, and then use it to check whether the element exists
$(document).ready(function() {
$("#addBtn").click(function() {
var name = $('#rname option:selected').text();
var qty = $('#qty').val();
if (qty > 0) {
var tbody = $('#rTable').children('tbody');
var table = tbody.length ? tbody : $('#rTable');
//Add row
var $tr = table.find('tr[data-rname="' + name + '"]');
if ($tr.length) {
$tr.find('td:last-child').text(function(i, t) {
return +t + +qty;
})
} else {
table.append($('<tr><td>' + name + '</td><td>' + qty + '</td></tr>').attr('data-rname', name));
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="rname">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input id="qty" />
<button id="addBtn">Add</button>
<br />
<table id="rTable"></table>
You can use .filter
var target = table.find("tr").filter(function(idx, tr) {
var td = tr.find('td:first-child');
return (td.text() === name);
});
if (target.length > 0) {
// Sum up
} else {
// Create new
}
I'd suggest you use <tr data-name="' + name + '"><td>'+ name + '</td><td>'+ qty +'</td></tr> to create a tr with data-name
Then the filter can be simplified to:
var target = table.find("tr").filter('[data-name="' + name + '"]');
You can use .filter() to check it the item is already present on the table.
var count = $('#rTable td').filter(function() {
return $(this).text().trim() == name;
});
count will be greater that one if the table contains that element.
Also you can use $("#rname option:selected").text(); inorder to get the selected option text.
$("#addBtn").click(function() {
var name = $("#rname option:selected").text();
var qty = parseInt($('#qty').val());
var count = $('#rTable td').filter(function() {
return $(this).text().trim() == name;
});
if (qty > 0 && count == 0) {
var tbody = $('#rTable').children('tbody');
var table = tbody.length ? tbody : $('#rTable');
//Add row
table.append('<tr><td>' + name + '</td><td>' + qty + '</td></tr>');
}
});

Creating a loop that populates a select tag

function buildOrder(data) {
var $fragment;
$fragment = $('<div/>');
for (var i = 0; i < data.length; i++) {
$fragment.append('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div></div>');
}
$('#review-section').append($fragment);
}
I essentially want to add a tag with 50 options being dynamically created using a for loop. But I'm not sure what the syntax would be to add it to the <div class="row-container"/> I know in php I would just throw the loop in the middle and echo the options, however that doesnt work in javascript.
EDIT:
It would look like this:
$fragment.append('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><select><option value="1">1</option> etc...</select><div class="clear"></div></div>');
You could pass a function to .append and do your loop there:
$("<div>").append(function() {
var $select = $("<select>");
for(var i = 1; i <= 50; i++) {
$("<option>").text(i).val(i).appendTo($select);
}
return $select;
});
// returns a jQuery object with one div element (with children):
// <div>
// <select>
// <option value="1">1</option>
// ...
// </select>
// </div>
Mixed into your code it would be along the lines of:
var $fragment = $("<div>");
for (var i = 0; i < data.length; i++) {
var $container = $("<div>").addClass("row-container")
.appendTo($fragment);
$("<div>").addClass("row cupcake-row")
.text(data[i].name)
.appendTo($container);
$("<div>").append(function() {
var $select = $("<select>");
for(var i = 1; i <= 50; i++) {
$("<option>").text(i).val(i).appendTo($select);
}
return $select;
}).appendTo($container);
$("<div>").addClass("clear")
.appendTo($container);
}
$("#review-section").append($fragment);
Try something like this
function buildOrder(data) {
var $fragment = $('<div></div>');
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div></div>');
}
$fragment.html(options.join("\n"));
$('#review-section').append($fragment);
}
According to your posted code:
function buildOrder(data) {
var $fragment;
$fragment = '<div><div class="row-container">';
for (var i = 0; i < data.length; i++) {
$fragment += '<div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div>';
}
$fragment += '</div></div>';
$('#review-section').append($fragment);
}
But in your posted code doesn't match with your post title, where you mentioned about select tag and in your code you're trying with div.
If you want to create a select, then something like:
function buildOrder(data) {
var $fragment;
$fragment = '<div class="row-container"><select>'; // taking select within your div
for (var i = 0; i < data.length; i++) {
// adding options to select
$fragment += '<option value="'+ data[i].name +'">' + data[i].name + '</option>';
}
$fragment += '</select></div>'; // end select and div
$('#review-section').append($fragment);
}

Categories

Resources