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())
})
}
});
Related
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>
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>
I am trying to validate the DONM using jquery Please look into the fiddle.
My objective is not to select the same country to same room number .
I have two scenarions
scenario 1 (before saving into DB)
The example is working fine
scenario 2 (After saving the data into db )
saved data coming from DB
Available Country RooNumber SelectedPerson
droipdown1 1
dropdown2 2 chennai
WRONG SELECTION
Available Country RooNumber SelectedPerson
chennai 1 chennai
chennai 2 chennai
JSFiddle:
http://jsfiddle.net/bharatgillala/9o1gxa1h/10/
code:
<table id="gridviewInfo" runatr="server">
<TBODY><TR>
<TH scope=col>Available Country</TH>
<TH scope=col>RooNumber</TH>
<TH scope=col>Selected</TH>
</TR>
<OPTION selected value=>
</OPTION>
<OPTION value=maxico>maxico
</OPTION> <OPTION value=chennai>chennai</OPTION> <OPTION value=newdelhi>newdelhi</OPTION> <OPTION value=hongkong>hongkong</OPTION></SELECT> </TD>
<TD style="WIDTH: 100px">1</TD>
<td>
<label id='lbl2'> maxico </label>
</td>
</TR>
<TR>
<TD style="WHITE-SPACE: nowrap" align=left>
<SELECT class="judges" id='ddlAvailableJudges2' name=ctl00$contentBody$gvwRoomInformation$ctl03$ddlAvailableJudges>
<OPTION selected value=>
</OPTION>
<OPTION value=maxico>maxico</OPTION> <OPTION value=chennai>chennai</OPTION> <OPTION value=newdelhi>newdelhi</OPTION> <OPTION value=hongkong>hongkong</OPTION></SELECT> </TD>
2
<td>
<label id='lbl2'>chennai</label>
</td>
</tr>
</table>
First of all, you're creating n label tags with the id lbl2.
This is happening, because you're developing with ASP.NET and you didn't create your label with the runat=server attribute, so it won't generate different label IDs for each label created.
Second, your code was too ugly / verbose, so I decided to make a complete new code to achieve what you want, and the snippet is below, full commented:
(function(d) {
// when all the DOMElements are already loaded into the document
d.addEventListener('DOMContentLoaded', function() {
// gets the generated table, and get all the dropdownlists inside it
var table = document.getElementById('gridviewInfo'),
ddls = [].slice.call(table.querySelectorAll('select'));
// loop through the dropdownlists
ddls.forEach(function(ddl, i) {
// get the label inside the last td
var lbl = ddl.parentNode.parentNode.lastElementChild.firstElementChild;
// initially, we want to change the dropdownlist selectedvalue to the label text
ddl.value = lbl.textContent.trim();
// then, we must disable this option in all the other dropdownlists
updateDisabled(ddl);
// so, we add a change event handler
ddl.addEventListener('change', function(e) {
// when the ddl value is changed, we update the label text
lbl.textContent = ddl.value;
// and we disable the option selected in all the other dropdownlists
updateDisabled(ddl);
});
});
function updateDisabled(ddl) {
// to disable all the other dropdownlists
// we loop through all the HTMLOptionElements inside the table
[].forEach.call(table.querySelectorAll('option'), function (opt, j) {
// we look if the current option inside the loop is not the selected one
if (opt.parentNode !== ddl) {
// then, if the option has the same selected value, we disable it, else we enable
opt.disabled = opt.value && opt.value === ddl.value;
}
});
}
});
})(document);
#gridviewInfo td:nth-child(1) {
white-space: nowrap;
text-align: left;
}
<table id="gridviewInfo" runatr="server">
<thead>
<tr>
<th>Available Person</th>
<th>RooNumber</th>
<th>SelectedPerson</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select class="judges" id="ddlAvailableJudges1" name=ctl00$contentBody$gvwRoomInformation$ctl02$ddlAvailableJudges>
<option selected value=''></option>
<option value="maxico">maxico</option>
<option value="chennai">chennai</option>
<option value="newdelhi">newdelhi</option>
<option value="hongkong">hongkong</option>
</select>
</td>
<td>1</td>
<td>
<label>maxico</label>
</td>
</tr>
<tr>
<td>
<select class="judges" id="ddlAvailableJudges2" name=ctl00$contentBody$gvwRoomInformation$ctl03$ddlAvailableJudges>
<option selected value=''></option>
<option value="maxico">maxico</option>
<option value="chennai">chennai</option>
<option value="newdelhi">newdelhi</option>
<option value="hongkong">hongkong</option>
</select>
</td>
<td>2</td>
<td>
<label>hongkong</label>
</td>
</tr>
</tbody>
</table>
Update
Since the OP asked, I've created a fiddle for him: http://jsfiddle.net/h1b6e8zm/
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>
I have this problem about retrieving row data in jQuery. this is not really a simple problem for me since my table cells contains a select tag, and a input box. To be clear enough, here's my html code of my table:
<tr>
<td>
<select style="width:5em;" class="field">
<option></option>
<option>name</option>
<option>age</option>
<option>sex</option>
</select>
</td>
<td>
<select style="width:5em;" class = "comp">
<option></option>
<option>equals</option>
<option>starts with</option>
<option>not equal to</option>
</select>
</td>
<td><input type="text" class = 'value'></td>
</tr>
<tr>
<td>
<select style="width:5em;" class="field">
<option></option>
<option>name</option>
<option>age</option>
<option>sex</option>
</select>
</td>
<td>
<select style="width:5em;" class = "comp">
<option></option>
<option>equals</option>
<option>starts with</option>
<option>not equal to</option>
</select>
</td>
<td><input type="text" class = 'value'></td>
</tr>
<tr>
<td>
<select style="width:5em;" class="field">
<option></option>
<option>name</option>
<option>age</option>
<option>sex</option>
</select>
</td>
<td>
<select style="width:5em;" class = "comp">
<option></option>
<option>equals</option>
<option>starts with</option>
<option>not equal to</option>
</select>
</td>
<td><input type="text" class = 'value'></td>
</tr>
</table>
<input type="button" value = "go" id="out">
Here's my Javascript code:
$('#out').click(function(){
var tr = 1;
$('table tr').each(function(){
var td = 1;
$(this).find('td').each(function(){
alert(JSON.stringify($(this).text()));
td++;
});
tr++;
});
})
What I am trying to do is that i want to get all the row data in the table, but everytime I click the button, it won't display the correct output.
I also tried this:
$(this).children($(".field option:selected").text())
to get the value of selected option, but it still no good.
DEMO here. Please help....
Does this help you?
http://jsfiddle.net/KzXjb/3/
$('#out').click(function(){
var data = new Array();
$("table select, table input").each(function(){
data.push($(this).val());
});
alert(data.toString());
})
Here is what I think you meant
http://jsfiddle.net/mplungjan/8xFFH/12/
$('#out').click(function(){
var tr = 1;
$('table tr').each(function(){
var td = 1;
$(this).find('td').each(function(){
var fld = $(this).find('select, input');
alert(fld.val());
td++;
});
tr++;
});
})
You can try something like this :
$('#out').click(function(){
$('table tr').each(function(){
var td = '';
$(this).find('option:selected').each(function(){
td = td + ' ' + $(this).text();
});
td = td + ' ' + $(this).find('input').val();
alert(td);
});
})
If i correctly understand what you need ^^