CSS does not work on controls added dynamically to row - javascript

I have a table where in I dynamically add rows with controls using javascript.
My problem is these controls are linked to CSS linked class.
<div id="DataTable">
<INPUT type="button" value="Add Row" onclick="addNewRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteSelectRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD></TD>
<TD>Name</TD>
<TD>Country</TD>
<TD>Security</TD>
</TR>
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD><INPUT type="text" name="txt"/></TD>
<TD>
<SELECT name="country">
<OPTION value="in">Greece</OPTION>
<OPTION value="de">Germany</OPTION>
<OPTION value="fr">India</OPTION>
<OPTION value="us">United States</OPTION>
<OPTION value="ch">France</OPTION>
</SELECT>
</TD>
<td>
<Select name="secName2" class="chosen-select" data-placeholder="Select Security(s)">
<option value="000"></option>
<%sQuery = "Select sID,SecurityName from SecurityMast where Active = 1 order by SecurityName"
Set oRS = oConn.Execute (sQuery)
if Not (oRS.EOF and oRS.BOF) then%>
<%Do While Not oRS.EOF%>
<option value="<%Response.Write(oRS(0))%>"
<%if sID=oRS(0) then Response.write "Selected"%>> <%Response.Write(oRS(1))%></option>
<%oRS.MoveNext
Loop%>
<%end if
oRS.Close%>
</select>
</td>
</TR>
</TABLE>
</div>
and my javascript looks liks this
function addNewRow(tID) {
var table = document.getElementById(tID);
var roCount = table.rows.length;
var ro = table.insertRow(roCount);
var coCount = table.rows[1].cells.length;
for(var i=0; i<coCount; i++) {
var newcell = ro.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
ok so now my problem is ...
when the user clicks add row we have a new row, but the drop down "SecName2" does not have the effects of class="chosen-select".
Is there anything that can be done about it.
What's special about class MySelect. Well besides the cosmetic matter there is a search box that helps to search for anything anywhere in the select list. Not just the starting characters which is default.
Appreciate your time and help
Vin
Edit:
I used the open source from http://harvesthq.github.io/chosen/ for the select.
there is a script section at the end ...
<script type="text/javascript" src="Scripts/chosen.jquery.js"></script>
<script type="text/javascript"> $(".chosen-select").chosen(); $(".chosen-select-deselect").chosen({allow_single_deselect:true}); </script>

Related

How do I make all values in html select element selected using Javascript

In Html have two select tags, the first contains all the worlds countries, the second contains only the countries selected by user.
<form action="/fixsongs.fix">
<table>
<tr>
<td colspan="2">
<label title="Potential Releases from these countries get their score boosted">
Preferred Release Countries
</label>
</td>
</tr>
<tr>
<td>
<select id="preferred_countries_all" size="15" style="width:200px" multiple="multiple">
<option value=" AF">Afghanistan</option><option value="AX">Åland Islands</option><option value="AL">Albania</option><option value="DZ">Algeria</option><option value="AS">American Samoa</option><option value="AD">Andorra</option><option value="AO">Angola</option><option value="AI">Anguilla</option><option value="AQ">Antarctica</option><option value="AG">Antigua and Barbuda</option><option value="AR">Argentina</option><option value="AM">Armenia</option><option value="AW">Aruba</option><option value="AU">Australia</option><option value="AT">Austria</option><option value="AZ">Azerbaijan</option><option value="BS">Bahamas</option><option value="BH">Bahrain</option>...<option value="ZW">Zimbabwe</option>
</select>
</td>
<td>
<button style="width:100px" type="button" id="preferred_countries_add" onclick="add_preferred_countries();">
Add
</button>
<br>
<button style="width:100px" type="button" id="preferred_countries_remove" onclick="remove_preferred_countries();">
Remove
</button>
</td>
<td>
<select id="preferred_countries_selected" name="preferred_countries_selected" size="15" style="width:200px" multiple="multiple">
<option value="GB">United Kingdom</option>
</select>
</td>
</tr>
</table>
<input type="submit" value="Start">
The user selects them by highlighting and then click on button which invokes the following Javascript function.
function add_preferred_countries() {
allCountries = document.getElementById('preferred_countries_all');
selectedCountries = document.getElementById('preferred_countries_selected');
var length=$('#preferred_countries_all option:selected').length;
if(length==0) {
return false;
}
$('#preferred_countries_all option:selected').each(function(){
$('#preferred_countries_selected').append($(this));
});
//selectedCountries.value = "";
for (var i = 0; i < selectedCountries.options.length; i++) {
selectedCountries.options[i].selected = selected;
}
}
'
That bits works fine, but I have realized that when I finally submit the form containing this and various other options that it will send items in the select list that are actually selected. So in the absence of a better solution I want to automatically select all values in the preferred_countries_selected whenever user adds new countries, so that when user submits form the preferred countries will be sent to server
I thought this would work, but has no effect
for (var i = 0; i < selectedCountries.options.length; i++) {
selectedCountries.options[i].selected = selected;
I know the existing function has some JQuery in it, but I would prefer pure javascript solution as I don't really understand JQuery syntax.
Ideally I would prefer to do this just as they press submit, but that is another question.
You have some HTML validation issues with your table and you really should not use inline CSS or HTML event attributes (i.e. onclick) as they have many harmful side-effects.
See the inline comments in the code snippet below and note that you need the checked CSS pseudo-class, rather than selected:
// Get references to the two lists
var allCountries = document.getElementById('preferred_countries_all');
var selectedCountries = document.getElementById('preferred_countries_selected');
function add_preferred_countries(operation) {
if(operation === "add"){
// Get the selected countries from list one into an array
var allPreferredSelected = Array.prototype.slice.call(allCountries.querySelectorAll('option:checked'));
// Loop over the array
allPreferredSelected.forEach(function(selOption){
selectedCountries.appendChild(selOption); // Add each to the second list
});
// Loop through the second list and select each option
Array.prototype.slice.call(selectedCountries.querySelectorAll("option")).forEach(function(opt){
opt.selected = "selected";
});
console.log("Item added");
} else {
// Do remove operation here
// Loop over the selected countries in the second list
Array.prototype.slice.call(selectedCountries.querySelectorAll("option:checked")).forEach(function(opt){
selectedCountries.removeChild(opt); // Remove country
});
console.log("Item removed");
}
}
// Get the add and remove buttons into an array and loop over the array
Array.prototype.slice.call(document.querySelectorAll("button[id^='preferred_countries']")).forEach(function(btn){
// Set up a click event handler for the button
btn.addEventListener("click", function(){
add_preferred_countries(this.dataset.action); // Call the add/remove function with the right arg
});
});
/* Do your styling separate from the HTML */
button[id^='preferred_countries'] { width:100px; }
select { width:200px; height:20em; }
<form action="/fixsongs.fix">
<table>
<tr>
<td colspan="2">
<span title="Potential Releases from these countries get their score boosted">
Preferred Release Countries
</span>
</td>
</tr>
<tr>
<td>
<select id="preferred_countries_all" multiple="multiple">
<option value=" AF">Afghanistan</option>
<option value="AX">Åland Islands</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
<option value="AS">American Samoa</option>
<option value="AD">Andorra</option>
<option value="AO">Angola</option>
<option value="AI">Anguilla</option>
<option value="AQ">Antarctica</option>
<option value="AG">Antigua and Barbuda</option>
<option value="AR">Argentina</option><option value="AM">Armenia</option>
<option value="AW">Aruba</option>
<option value="AU">Australia</option>
<option value="AT">Austria</option>
<option value="AZ">Azerbaijan</option>
<option value="BS">Bahamas</option><option value="BH">Bahrain</option>
...
<option value="ZW">Zimbabwe</option>
</select>
</td>
<td>
<button type="button" id="preferred_countries_add" data-action="add">Add</button>
<br>
<button type="button" id="preferred_countries_remove" data-action="remove">Remove</button>
</td>
<td>
<select id="preferred_countries_selected" name="preferred_countries_selected" multiple="multiple">
<option value="GB">United Kingdom</option>
</select>
</td>
</tr>
</table>
<input type="submit" value="Start">
</form>

Iterating over checkboxes in jQuery

I have a table with check-boxes, a dropdown, and other accompanying data.
I'd like to iterate over the rows that have been checked, and pull it's data, add that data into a dictionary, then into a master array.
It seems to be finding the correct rows with check boxes, but my for loop is not pulling each row properly. Here is my js code:
$("#thechecked").click(function(){
var send_list = []
$('#mytable').find(':checkbox:checked').each(function () {
var dict = {};
var value = $("#presetChoosen").val();
var filename = $("#filename").text();
dict['filename'] = filename
dict['value'] = value
send_list.push(dict)
});
console.log(send_list)
});
FULL EXAMPLE IN JSFIDDLE
What am I doing wrong?
You should not use the same ids everywhere like you did on the select element. Id's elements are meant to be unique.
I've used some jQuery methods(parent(), find(), next()) to target the specific values:
var value = $(this).parent().parent().find("select option:checked").val();
var filename = $(this).parent().next("td").text();
Below is a working snippet of what you're trying to achieve:
$("#thechecked").click(function() {
var send_list = []
$('#mytable').find(':checkbox:checked').each(function() {
var dict = {};
var value = $(this).parent().parent().find("select option:checked").val();
var filename = $(this).parent().next("td").text();
dict['filename'] = filename
dict['value'] = value
send_list.push(dict)
});
console.log(send_list)
});
tr,
td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
<thead>
<tr id="mq">
<td><input type="checkbox" /></td>
<td>What</td>
<td>Meta</td>
<td>Preset</td>
</tr>
</thead>
<tbody>
<tr id="1">
<td><input type="checkbox" /></td>
<td id="filename_1">Underthesea</td>
<td>1920x1080</td>
<td> <select id="presetChoosen_1">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
<tr id="2">
<td><input type="checkbox" /></td>
<td id="filename_2">Overthehill</td>
<td>1280x720</td>
<td> <select id="presetChoosen_2" value="asd">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
<tr id="3">
<td><input type="checkbox" /></td>
<td id="filename">Mocking</td>
<td>1280x720</td>
<td> <select id="presetChoosen" value="asd">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
</tbody>
</table>
<button id="thechecked">Get Checked</button>
You're re-using id attributes. IDs are supposed to be unique - and I believe it's actually a WC3 validation error to re-use the same ID in HTML.
You're also not scoping your selector to your checkbox at all.
Change your id="" to name="" and then try the following code concept:
$('#mytable').find('input[type="checkbox"]:checked').each(function () {
var tr = $(this).closest('tr'),
filename = tr.find('[name="filename"]').val();
// [...]
});
Once you get the checkbox (inside the loop), then you need to get the row for that checkbox, eg:
$("#thechecked").click(function(){
var send_list = []
$('#mytable :checkbox:checked').each(function () {
var row = $(this).closest("tr");
var value = row.find("#presetChoosen").val();
var filename = row.find("#filename").text();
var dict = {};
dict['filename'] = filename
dict['value'] = value
send_list.push(dict)
});
console.log(send_list)
});
bit hard to be 100% without your HTML (in the question) and it looks like you have elements with the same id, eg id='presetChoosen' on every row, which is advised against.
Like the accepted answer said, ids should be unique. What I would do is change filename and presetChoosen to classes instead, since they are a type of thing (class), not a particular thing (id). That way you could traverse the DOM in a more readable and easier to understand way:
$("#thechecked").click(function(){
var send_list = [];
$('#mytable').find(':checkbox:checked').each(function (index, checkbox) {
// Find the row this checkbox is in
var row = $(checkbox).closest('tr'),
value = row.find('.presetChoosen').val(),
filename = row.find('.filename').text();
send_list.push({
filename: filename,
value: value
});
});
console.log(send_list);
});
tr,td{border:1px solid black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
<thead>
<tr id="mq">
<td></td>
<td>What</td>
<td>Meta</td>
<td>Preset</td>
</tr>
</thead>
<tbody>
<tr id="1">
<td><input type="checkbox" /></td>
<td class="filename" >Underthesea</td>
<td>1920x1080</td>
<td> <select class="presetChoosen">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
<tr id="2">
<td><input type="checkbox" /></td>
<td class="filename" >Overthehill</td>
<td>1280x720</td>
<td> <select class="presetChoosen">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
<tr id="3">
<td><input type="checkbox" /></td>
<td class="filename" >Mocking</td>
<td>1280x720</td>
<td> <select class="presetChoosen">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
</tbody>
</table>
<button id="thechecked">Get Checked</button>

Fetching the values from dynamically generated text boxes and input fields

Following is my code in which I am adding rows with text boxes and drop downs dynamically.
Javascript:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
HTML:
<body onload="load()">
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="text" name="txt[]" id="t1"/></TD>
<TD>
<SELECT name="country[]" id="t2">
<OPTION value="in">India</OPTION>
<OPTION value="de">Germany</OPTION>
<OPTION value="fr">France</OPTION>
<OPTION value="us">United States</OPTION>
<OPTION value="ch">Switzerland</OPTION>
</SELECT>
</TD>
</TR>
</TABLE>
</BODY>
Now i am trying to fetch the values from fields added dynamically so that i can display it in table format . But i am not getting by which way i can do it . Please help.

javascript/jquery clone not working in dropdown list

I asked a question in the last post that i want rows to be dynamically generated and the data should be copied in the new row. it is working fine but only for text fields. but i also have dropdown in my form and it isn't showing the last row's selected options in new row.
this was my question
add previous row data to dynamically generated row
i have html code :
<form>
<table border="1" id="engagements">
<tr>
<th>
<input type="checkbox" onclick="checkAll(this)" />
</th>
<th>Organization</th>
<th>Project</th>
<th>Product</th>
<th>Activity</th>
</tr>
<tr>
<td>
<input type="checkbox" onclick="checkAll(this)" />
</td>
<td>
<select>
<option value = "1">One</option>/>
<option value = "1">two</option>/>
</td>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
</tr>
</table>
<select name="mode" id="mode">
<option value="">Add More Rows with Same Data as Above</option>
<option value="1">1 More</option>
<option value="2">2 More</option>
<option value="3">3 More</option>
<option value="4">4 More</option>
<option value="5">5 More</option>
</select>
</form>
and script code :
$("#mode").on('change', function () {
var rows = parseInt(this.value);
console.log(rows);
var lastRow;
for (var i = 0; i < rows; i++) {
lastRow = $('#engagements tr').last().clone();
$('#engagements tr').last().after(lastRow);
}
});
JS fiddle: http://jsfiddle.net/jW6eL/3/
for performance reasons, jquery doesn't keep selection while making clone of an element. However, you can try using
.clone(true)
this will copy all evens and data with drop down. this way you may use events and and select last option in the drop down.
try this
http://jsfiddle.net/jW6eL/7/
$("#mode").on('change', function () {
var rows = parseInt(this.value);
console.log(rows);
var lastRow;
for (var i = 0; i < rows; i++) {
lastRow = $('#engagements tr').last().html();
$('#engagements tr:last').after('<tr>'+lastRow+'</tr>');
$('#engagements tr:last').find('select').each(function(){
var this_select=$(this);
this_select.val(this_select.closest('tr').prev().find('td:eq('+this_select.closest('td').index()+')').find('select').val())
})
}
});

add new row to table with 2 drop down list- how do i change the name of the select

I would really appreciate if someone could help me. for two days I've tried to figure this out alone but its not working.
I'm writing a shopping list to my project at school. I have a table (shopinglist) that contains the form.
In the form I have 2 drop down lisst, one (product) is getting the values from my database and the second one (quantity) is constant numners. Next to these two I have 2 buttons add and remove.
When pressing add I want to add a new row with the same stuff.
The problem is that I can't (or maybe don't know how to) change the select name according to the row number. I mean like
One last thing- the row will be added only if the user choose from both selection, not only from one.
here is my code: the javascript add and remove functions:
function addRow(tableID) {
if (document.getElementById("product").value!="dafult" && document.getElementById("quantity").value!="zero")
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
var colCount = table.rows[0].cells.length;
for(var i=0; i<=colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
switch(newcell.childNodes[1].type) {
case "text":
newcell.childNodes[1].value = "";
break;
case "checkbox":
newcell.childNodes[1].checked = false;
break;
case "select-one":
newcell.childNodes[1].selectedIndex = 0;
break;
}
}
newcell.childNodes[1].visible = true;
table.rows[rowCount-1].cells[2].style.visibility="hidden" ;
}
else
{
if (document.getElementById("product").value!="dafult" && document.getElementById("quantity").value=="zero")
alert("please choose quantity") ;
if (document.getElementById("product").value=="dafult" && document.getElementById("quantity").value!="zero")
alert("please choose product") ;
if (document.getElementById("product").value=="dafult" && document.getElementById("quantity").value=="zero")
alert("please choose product and qantity") ;
}
}
function deleteRow(i){
if (document.getElementById("product").value!="dafult" && document.getElementById("quantity").value!="zero")
document.getElementById('shopinglist').deleteRow(i)
else
alert("you can't delete row before adding it");
}
and the HTML and ASP
<table border="0" id="shopinglist">
<caption valign="top" style="width:90%;height:35px; color:green ;"/> your order
<tr><td></td><td> product</td> <td> quantity</td></tr>
<tr>
<form name="juices">
<%
set rs=Server.CreateObject("ADODB.recordset")
rs.open "SELECT ID, [Product-Name] ,[size-liter],[Customer price] FROM Product GROUP BY ID,[Product-Name] ,[Product].[size-liter],[Product].[Customer price] ", conn
%>
<td>
<select name="product" id="product" width="10" >
<option value="dafult" selected>בחר מוצר מהרשימה</option>
<%
do while not rs.EOF %>
<option value=<%=rs("Product-Name")%> > juice<%=rs("Product-Name")%> <%=rs("size-liter")%> liter<%=rs("Customer price")%> $</option>
<%
rs.MoveNext()
loop
rs.close %>
</select>
</td>
<td>
<select name="quantity" id="quantity">
<option value="zero" selected="selected">0</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
<option value="five">5</option>
<option value="six">6</option>
<option value="seven">7</option>
<option value="eight">8</option>
<option value="nine">9</option>
<option value="ten">10</option>
</select>
</td>
<td>
<input type="button" value="add" onclick="addRow('shopinglist')" id="addbutton"/>
</td>
<td>
<input type="button" value="delete"onclick="deleteRow(this.parentNode.parentNode.rowIndex)" id="remove"/>
</td>
</tr>
</form>
IE will not let you change the name of an element after you add it to the page. The way this is written, you would have to actually alter the string containing the select before setting innerHTML
newcell.innerHTML = table.rows[1].cells[i].innerHTML.replace(/(\<select.+?name=".+?)"/, $1 + rowCount + i + "\"");
NOT TESTED... something like that...
Here is an example https://gist.github.com/957827 that you could start with. It is radically different but simpler than yours.
I don't have a IE6,7,8 to test it properly but it should be something like the example.
One more comment, id's must be unique. And you shouldn't use them on a row of a table that you will copy.

Categories