Finding all checked check boxes isnt working - javascript

I've tried a few different ways of finding all the checkboxes that are checked but I don't know why this one isn't working.
JavaScript:
var idList = new Array();
function getIds()
{
var loopCounter = 0;
// find all the checked checkboxes
$('input[name^="check_"]:checked').each
{
function()
{
//fill the array with the values
idList[loopCounter] = $(this).val();
loopCounter += 1;
}
};
}
function showArray()
{
alert(idList);
}
and the HTML/ERB:
<% user_project_ids = #users_projects.collect { |up| up.project_id } %>
<fieldset style="width: 400px;">
<legend>Current Projects</legend>
<table>
<tr>
<th>Project ID</th>
<th>Project Name</th>
</tr>
<% #projects.each do |project| %>
<tr>
<td><%= project.id %></td>
<td><%= project.project_number %></td>
<td><%= project.project_name%></td>
<td><input name="check_<%= project.id %>" type="checkbox"
<%=' checked="yes"' if user_project_ids.include? project.id %>></td>
</tr>
<% end %>
</table>
</fieldset>
<div onclick="getIds();">
CLICK
</div>
<button onclick="showArray()">Click Again</button>
Not sure why this isn't working but maybe someone can see what I can't.

The parameter to .each need to be in round brackets .each()
function getIds()
{
var loopCounter = 0;
// find all the checked checkboxes
$('input[name^="check_"]:checked').each(function() {
//fill the array with the values
idList[loopCounter] = $(this).val();
loopCounter += 1;
});
}

The other answer already told you about your problem, but your code can be improved. There is no need to use a loop counter, each provides the iteration number.
function getIds()
{
//reset idArray
idList = [];
// find all the checked checkboxes
$('input[name^="check_"]:checked').each(function( ind ) {
idList[ind] = $(this).val();
});
}
You do not even need the index when you have methods on the array to add element
function getIds()
{
//reset idArray
idList = [];
// find all the checked checkboxes
$('input[name^="check_"]:checked').each(function() {
idList.push( $(this).val() );
});
}

Related

nodejs ejs render array object in to table

Good day
I need to write a table from a database and i can't access the values, if the array is greater than 1...
If i do it like this:
//spielzeiten
var spielzeitenArr = [{
spzeit: "",
spielzeit_id: "",
}];
var spzeitData = await myDB.selectSpielzeit();
for (var i = 0; i < 1/*spzeitData.length*/; i++) {
spielzeitenArr[i].spzeit = "meine Zeit" /*spzeitData.spzeit*/;
spielzeitenArr[i].spielzeit_id = "meine ID"/*spzeitData.spielzeit_id*/;
}
res.render('index', {
firmen: firmanameArr,
block: blocknameArr,
datei: dateinameArr,
jinglein: jingleinArr,
jingleout: jingleoutArr,
szdata: spielzeitenArr
});
and on the ejs side it looks like this:
<table id="todoTable">
<tr>
<td class="tdList">Datum</td>
<td class="tdList">Zeit</td>
<td class="tdList">Start Jingle</td>
<td class="tdList">End Jingle</td>
<td class="tdList">Name</td>
<td class="tdList">
<div class="select-wrapper">
<select id="categoryFilter" class="selectCompany"></select>
</div>
</td>
<% szdata.forEach((item) => { %>
<tr></tr>
<td><%= item.spzeit %></td>
<td><%= item.spielzeit_id %></td>
<% }); %>
</table>
if i use my hardcoded value, it works. But if i try to change the i value to 2 or more, it gives me an error... why is this so?
Many thanks for the help!
You are initializing your spielzeiten array with a length of 1 and not increasing its size if you have more than one record. Thus, of course if you try to access an spielzeiten[i].spzeit with an index different from 0 you get an error.
You should probably initialize your array as an empty array and add new items during the loop.
spielzeiten = [];
for (let i = 0; i < spzeitData.length; i++) {
spielzeiten.push({
spzeit: spzeitData[i].spzeit,
id: spzeitData[i].spielzeit_id
});
}
You could also use the Array.map function to directly initialize your array
let spielzeiten = spzeitData.map(d => ({
spzeit: d.spzeit,
id: d.spielzeit_id
}));

Clone a row in JSP table having drop-down from MYSQL DB and display data (from DB) related to the option selected in drop-down in each respective row

ISSUE:
I am trying to generate a invoice in JSP. Where I am selecting values of item name from drop down. Drop down values are from database, On change of select tag I want to display the values associate to that item name from database(item price, HSN code, tax, description of item etc.). This is working for first row in table But when we are adding new row(by cloning row) we are unable perform on change function hence the related data is not displayed.
I have tried the below codes on my own. But couldn't get the desired result.
http://jsfiddle.net/leftstick/DVEXG/
http://www.iamrohit.in/add-remove-table-rows-dynamically/
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-append-and-remove-table-row-dynamically
http://jsfiddle.net/HjZkB/2/
http://jsfiddle.net/Dz24f/
https://youtu.be/KnKMGCSPj3Y
https://www.youtube.com/watch?v=FVSfp8yT8lA&feature=youtu.be
I added database connection to below code but did not gave me the desired result.
<%# page import = "java.sql.*"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add / Remove Table Rows Dynamically</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
//$(function(){
$(document).ready(function () {
var j=1;
$("#table-data").on('click', 'input.addButton', function() {
var $tr = $(this).closest('tr');
var allTrs = $tr.closest('table').find('tr');
var lastTr = allTrs[allTrs.length-1];
var $clone = $(lastTr).clone();
$clone.find('td').each(function(){
var el = $(this).find(':first-child');
var r1= $(this).find(':first');
var idr= r1.attr('id') || null;
var id = el.attr('id') || null;
if(id) {
var i = id.substr(id.length-1);
var prefix = id.substr(0, (id.length-1));
el.attr('id', prefix+(+i+1));
el.attr('name', prefix+(+i+1));
}
});
$clone.find('input:text').val('');
$tr.closest('table').append($clone);
});
//var i=1;
$("#table-data").on('change', 'select', function(){
var value = $(this).val();
//var row1 = $(this).closest('table').find(' tbody tr:eq(0)').attr('id'); alert(row1);
var rid=$(this).closest('tr').attr("id"); alert(rid);
//var i=1;
$(this).closest('tr').find('input:text').each(function(){
$.get("myinvoice.jsp",{q:value},function(data){
//rid.val(data);
//$("#javaquery'"+i+"'").html(data);
//rid++;
$("#javaquery1").html(data);
$("#table-data option[value='"+value+"']").prop('selected', true);
});
}); //each
}); //select change
}); // ready function
//});
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data">
<thead>
<tr>
<td>SelectOne</td>
<td>TextBox</td>
<td>TextBox</td>
<td>Add</td>
</tr>
</thead>
<tbody>
<tr id="javaquery1">
<td>
<%
String desc = "";
String price= "";
// String q =request.getParameter("q"); System.out.println("q = "+q);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","root1216");
Statement smt = con.createStatement(); //Create Statement to inte000ract
ResultSet r = smt.executeQuery("select item_name from item"); %>
<select name="Id.0" class="dropdn" id="Id.0" ><option value="">--Select--</option>
<%
while(r.next())
{%>
<option value="<%=r.getString("item_name")%>"> <%=r.getString("item_name")%> </option>
<% } %>
</select>
<br>
<%
Statement s=con.createStatement();
String q =request.getParameter("q"); System.out.println("q = "+q);
ResultSet r1=s.executeQuery("select * from item where(item_name='"+q+"');");
while (r1.next()) {
desc = r1.getString("item_description");
price=r1.getString("item_price"); System.out.println("price = "+price);
}
%>
</td>
<td><input type="text" id="Integer1.0" name="Integer1.0" value='<%= price %>'/></td>
<td><input type="text" id="Integer2.0" name="Integer2.0" value='<%= desc %>'/></td>
<td><input type="button" class="addButton" value="Add" /></td>
</tr>
</tbody>
<%
con.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
enter image description here
enter image description here

for loop not returning data when iterating through multiple values

I have a function which its job its to delete a value selected by the user, it loops through an array of selected values and the data, when it iterates through both it checks if the selected value is equal to any property in the data, if it returns true, I get a new array of data.
When I select one value in the checkbox I do indeed see the correct data being returned, but when I select multiple my function does not work. I have being pondering all day, I will really appreciate any input.
HTML
<div class="ibox-content">
<table class="table table-striped">
<thead>
<tr>
<th>Select</th>
<th class="col-xs-3">Issue Description</th>
<th class="col-xs-3 text-center">Category</th>
<th class="col-xs-3 text-center">Jira</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="issue in wiq.data">
<td><input type="checkbox" checklist-model="wiq.selections" checklist-value="issue.jira"> </td>
<td>{{issue.issue}}</td>
<td class="text-center">{{issue.description}}</td>
<td class="text-center">{{issue.jira}}</td>
</tr>
<pre>{{wiq.selections}}</pre>
</tbody>
</table>
<form>
<button type="button" name="button" class="btn btn-success pull-right" style="margin-top:2em;" ng-click="wiq.acknowledge()">Acknowledge</button>
</form>
</div>
Controller.js
ctrl.selections = []
ctrl.data = [
{issue:"CMDY has issue", description:"issue",jira:"CDVR-173"},
{issue:"SPK has issue", description:"issue",jira:"CDVR-125"}
]
ctrl.acknowledge = function() {
var data = [];
for (var i = 0; i < ctrl.data.length; i++) {
for (var j = 0; j < ctrl.selections.length; j++) {
if (ctrl.selections[j] != ctrl.data[i].jira) {
data.push(ctrl.data[i]);
}
}
}
ctrl.data = data;
console.log(ctrl.data)
};
When you have multiple selection, you loop multiple times, so you call "push" too many times.
try :
function filterData(somedata, selections) {
return somedata.filter(item => (selections.findIndex(o => o === item.jira ) == -1));
};
then
ctrl.acknowledge = function() {
ctrl.data = filterData(ctrl.data,ctrl.selections);
console.log(ctrl.data)
};
Simple one liner will solve your problems, try this:
ctrl.acknowledge = function() {
var data = ctrl.data.filter(val => ctrl.selections.indexOf(val.jira) === -1);
ctrl.data = data;
console.log(ctrl.data)
};
Here's jsfiddle:
http://jsfiddle.net/pegla/xj9gqqxn/7/

Ruby on Rails - javascript table filtering doesn't work

I have a strange problem. My filtering table doesn't work as it should. Here is javascript function that is activated the moment select value is changed.
function filterTable(opt, coln, tbId){
var filter = opt.value.toLowerCase(),
table = document.getElementById(tbId),
trs = table.getElementsByTagName("TR"),
col = table.querySelector('th[title='+coln+']').cellIndex,
x;
for (var i = 1; i < trs.length; i++){
x = trs[i].getElementsByTagName("TD")[col];
if(x){
classes = trs[i].classList;
classes.remove(coln+'-filtered-active');
classes.remove(coln+'-filtered-hidden');
if(filter){
console.log('tekst:' + x.textContent.length + ' ' + x.textContent +' || filter:' + filter);
if (x.textContent.toLowerCase() == filter) {
classes.add(coln+'-filtered-active');
}
else {
classes.add(coln+'-filtered-hidden');
}
}
trs[i].style.display = "";
for(var k=0; k < classes.length; k++){
if(classes[k].includes('filtered-hidden')) {
trs[i].style.display = "none";
break;
}
}
}
}
}
Here is rendered (I'm working in Rails) html structured containing one of the cells that belongs to the column I want to sort by.
<td>
<div class="cardLabel feature">feature</div>
</td>
The thing is x.textContent returns not only feature but also newlines and whitespaces that amounts to 55 characters. I believe that's why my filtering method doesn't work. But I have no idea how to solve this problem.This is the way how I get data to the view:
<tbody>
<% #cards.each do |card| %>
<tr>
<td>
<%= card[:card_name].truncate(50) %>
</td>
<td>
<div class="cardLabel <%= card[:label_name].gsub(/\s+/, "").downcase %>"><%=card[:label_name].upcase %></div>
</td>
<td><%= card[:time_from]+'-'+card[:time_to]+'h' %></td>
<td><%= card[:list_name] %></td>
<td><%= card[:organization_name] %></td>
<td><%= card[:board_name] %></td>
</tr>
<% end %>
</tbody>
Try innerText. From the code you posted innerText and textContent should be the same. But I assume you have other codes that add other elements that are not displayed but are picked up by textContent
https://jsfiddle.net/msyLm8u2/

Accessing specific member of an ArrayList using Javascript

So, I have a table in a jsp page which shows the data fetched from a database via an ArrayList forwarded to the page. Each row of the table has a radio button corressponding to it. Now, I would like to access the elements in the row (the ArrayList's members on the selection of the corresponding radio button and then click of an 'edit' button)
Any thoughts as to how to achieve this would be very much appreciated. Here's my code for a bit intro.
<%
ArrayList<requestbean> reqjsp = new ArrayList<requestbean>();
reqjsp = (ArrayList<requestbean>) (request.getAttribute("reqdb"));
%>
<script type ="text/javascript">
function x() {
var ele = document.getElementsByName('reqradio');
var i = ele.length;
for ( var j = 0; j < i; j++ ) {
if ( ele[j].checked ) {
document.getElementById("edireq").disabled = false;
alert('request ' + ( j + 1 ) + ' selected');
//Here is where the functionality is desired to access reqjsp.get(j)
}
}
}
</script>
<input type="button" name="edireq" id="edireq" onclick="x()" value="Edit Request">
These are a few columns in my table.
<%
for ( int i = 0; i < reqjsp.size(); i++ ) {
%>
<tr>
<td> <input type="radio" name="reqradio" id="req<%=(i+1) %>"></td>
<td><%= reqjsp.get(i).getRequestid() %></td>
<td><%= reqjsp.get(i).getRequestor() %></td>
<td><%= reqjsp.get(i).getApprover() %></td>
</tr>
<%} %>
You could generate a JavaScript array with JSP code and then access this generated variable in your JavaScript. But you would not be able to change anything in the underlying Java object this way:
<script type ="text/javascript">
<%
ArrayList<requestbean> reqjsp = new ArrayList<requestbean>();
reqjsp = (ArrayList<requestbean>) (request.getAttribute("reqdb"));
%>
var myJsArray = new Array();
<%
for ( int i = 0; i < reqjsp.size(); i++ ) {
%>
myJsArray.push('<%= reqjsp.get(i) %>');
<%
}
%>
// JavaScript code to access the myJsArray array
</script>
The JSP code will generate this kind of code:
<script type ="text/javascript">
var myJsArray = new Array();
myJsArray.push('value1');
myJsArray.push('value2');
myJsArray.push('value3');
// JavaScript code to access the myJsArray array
</script>

Categories

Resources