Values selected in select box cannot be retrieved- jQuery - javascript

I am building an application in which I have table with form elements like select, input etc. I want to populate the values selected in form elements to another table.
You can find my code here
JS:
$('button').click(function() {
var rows = $('#table1 tbody tr');
var previewTable = $('#table2 tbody');
previewTable.find('tr').remove();
for (var i = 0; i < rows.length; i++) {
var tr = $('<tr> </tr>');
previewTable.append(tr);
var row_cloned = $(rows[i]).clone();
var cols = rows[i].getElementsByTagName("td");
for (var j = 0; j < cols.length; j++) {
var col_cloned = row_cloned.find('td').clone();
previewTable.find('tr').eq(i).append(col_cloned[j]);
if ($(col_cloned[j]).children().length > 0) {
$(col_cloned[j]).children().each(function(index, item) {
if ($(item).is('select')) {
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
console.log($(selected).val());
foo[i] = $(selected).val();
});
$(col_cloned[j]).text(foo);
} else {
$(col_cloned[j]).text($(item).val());
}
} else if ($(item).is('label')) {
var selected = [];
$(item).find('input:checked').each(function(index, item) {
selected.push($(item).val());
$(col_cloned[j]).append(selected + '<br>');
})
}
})
} else {
$(col_cloned[j]).text($(col_cloned[j]).text());
}
}
}
})
My steps:
Get table1 and table2
Count the number of rows in the table1
Add so many empty rows in the table2
Get each row in table1
Count the td in each row of table1
Find the children in each td
Check if children is select, input, or just plain text
If children is select, determine if it is multi-select or single
Act accordingly for each form elements to copy only values and then append to table2
finish
All this on a button click COPY
Problem: Somehow managed to get the checked input form element values. But failing to get the values selected in select box.
For multi select box my code:
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
console.log($(selected).val());
foo[i] = $(selected).val();
});
$(col_cloned[j]).text(foo);
}
For single select box :
else {
$(col_cloned[j]).text($(item).val());
}
What is my mistake exactly? Thanks in Advance

For selected .val() does not work.You will have to use find() as in reality when you select a select box , its value does not change.
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
foo[i] = $(selected).find(":selected").text(); // see this
});
$(col_cloned[j]).text(foo);
} else {
$(col_cloned[j]).text($(item).find(":selected").text()); // see this
}

For <select> you can't use val().
Using the .val() function on a multi-select list will return an array of the selected values:
This code:
if ($(item).is('select')) {
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
console.log($(selected).val());
foo[i] = $(selected).val();
});
$(col_cloned[j]).text(foo);
} else {
$(col_cloned[j]).text($(item).val());
}
}
Change to this:
if ($(item).is('select')) {
if ($(item).attr('multiple')) {
var foo = $('#multipleSelect').val();
$(col_cloned[j]).text(foo);
} else {
var optionSelected = $(item).find("option:selected");
$(col_cloned[j]).text(optionSelected.val());
}
}

Related

how do I make an advance filter logic using search filter and checkbox filter in javascript?

I have a search filter and a checkbox filter, It works, but individually. Example, if I check a category it will filter but if I enter a text in search box, the category filter will disappear as if it resets the filter all over. As I said, they work individually :(
here is my javascript
var input, filter, found, table, tr, td, i, j;
function myFunction() {
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
}
}
if (found) {
tr[i].style.display = "";
found = false;
} else {
if (tr[i].id !== 'tableHeader'){tr[i].style.display = "none";}
}
}
}
$(function() {
$('input[type="checkbox"]').change(function() {
if($('input[type="checkbox"]:checked').length > 0) {
var vals = $('input[type="checkbox"]:checked').map(function() {
return this.value;
}).get();
$('#myTable tr')
.hide() // 1
.filter(function() { // 2
$('#tableHeader').show();
return vals.indexOf($(this).find('td:eq(4)').text()) > -1;
}).show();
} else {
// Show all
$('#myTable tr').show();
}
});
});
You have to separate functions that filter same view. Each of the functions ignores the setting of the other (i.e., sets view only according to its triggering control).
You need to create one logic (e.g., function) that will consider the values of both - search input and checkbox. Then trigger this logic from these controls.

how to Delete duplicate items on asp:dropdownlist, Sharepoint Designer 2013

I have used asp:drowdownlist on dataviewwebpart and is bind with source spdatasource1.
It have multiple duplicate items. How could I delete those duplicate item
asp:DropDownList runat="server" id="DropDownList1" DataValueField="ID" DataTextField="ProgramMaster" DataSourceID="spdatasource1" AutoPostBack="False" AppendDataBoundItems="True" ToolTip="Select a Program from the list"/>
Also, It is showing items in following formation ID;#ProgramName. How can I get programName only.
Well I use JQuery to remove duplicates item from asp:dropdownlist and here's the code if in-case somebody might need it. The code works in four part, Get the value from Dropdown, strip off the Duplicates and get the value in usable form, Remove the existing value from Dropdown and last set or append the values back to the dropdown list.
<script type="text/javascript">
$(document).ready(function(){
var handles= [];
$('#DropDownList1 option').each(function() {
var Prog1 = $(this).attr('text');
if(Prog1 != 'All'){
var Prog2 = Prog1.split(';#');
handles.push('All');
handles.push(Prog2[1]);
}
//Remove The existed Dropdownlist value
$("select#DropDownList1 option[value='" + $(this).val() + "']").remove();
//$(this).val().remove();
});
//Removing the Duplicates
var individual = [];
for (var i = 0; i<handles.length; i++) {
if((jQuery.inArray(handles[i], individual )) == -1)
{
individual .push(handles[i]);
}
}
//Inserting or setting the value from array individual to the dropdownlist.
var sel = document.getElementById('DropDownList1');
for(var i = 0; i < individual.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = individual[i];
opt.value = individual[i];
sel.appendChild(opt);
}
});
</script>
P.S if the given ID didn't work fine for dropdown, get the ID from IE debugging tool which will be in form ctl00_PlaceHolderMain_g_a0a2fb36_2203_4d2e_bcd4_6f42243b880f_DropDownList1
you can do this with jquery
var usedNames = {};
$("select[name='company'] > option").each(function () {
if(usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
or with server side code try this
void RemoveDuplicateItems(DropDownList ddl)
{
for (int i = 0; i < ddl.Items.Count; i++)
{
ddl.SelectedIndex = i;
string str = ddl.SelectedItem.ToString();
for (int counter = i + 1; counter < ddl.Items.Count; counter++)
{
ddl.SelectedIndex = counter;
string compareStr = ddl.SelectedItem.ToString();
if (str == compareStr)
{
ddl.Items.RemoveAt(counter);
counter = counter - 1;
}
} } }

Display the value on click of check box in an array

I have an array of 10 checkboxes. onclick of checkbox i want to get the value of that particular checkbox. That I am able to achieve using my code.When I click in serial order it is working fine. When I click on checkbox 5 after clicking on checkbox 7 the value of checkbox 5 ie..5 is getting added befor 7. I dont want in that order. I want the values to displayed in whatever order I click. My js file is as follows
var selected = new Array();
$(document).ready(function(){
checkBoxTest();
});
function checkBoxTest() {
alert("checkbox test");
for(i = 0; i < 10; i++){
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' +i+' "/><td></tr>');
test();
}
}
function test() {
$('#catalog_table input:checkbox').change(function() {
var emails = [];
$('#catalog_table input:checkbox:checked').each(function() {
emails.push($(this).val());
});
var textField = document.getElementById("root");
textField.value = emails;
});
}
My HTML code is something like this
<table id="catalog_table"> </table>
<textarea id="root"></textarea>
Can any one please tell me how to do this?
Demo
Its messy, but it works:
http://jsfiddle.net/za7m8/1/
var selected = new Array();
$(document).ready(function(){
$("input[type='checkbox']").on('change', function() {
// check if we are adding, or removing a selected item
if ($(this).is(":checked")) {
selected.push($(this).val());
} else {
for(var i = 0; i<selected.length;i++) {
if (selected[i] == $(this).val()) {
// remove the item from the array
selected.splice(i, 1);
}
}
}
// output selected
var output = "";
for (var o = 0; o<selected.length; o++) {
if (output.length) {
output += ", " + selected[o];
} else {
output += selected[o];
}
}
$("#root").val(output);
});
});
You just have to change your javascript like this.
var selected = new Array();
$(document).ready(function(){
checkBoxTest();
});
function checkBoxTest() {
alert("checkbox test");
for(i = 0; i < 10; i++){
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' +i+' "/><td></tr>');
test();
}
}
var emails = [];
function test() {
$('#catalog_table input:checkbox').change(function() {
if (this.checked)
{
if ( emails.indexOf( $(this).val() ) === -1 )
{
emails.push($(this).val());
}
} else
{
if ( emails.indexOf( $(this).val() ) !== -1 )
{
var index = emails.indexOf( $(this).val() );
emails.splice(index, 1);
}
}
var textField = document.getElementById("root");
textField.value = emails;
});
}
You need to clear up your code a bit, like this:
I assume that unchecking removes the value from the array, and checking adds.
var selected = new Array(); // What for is this here ?
$(document).ready(function () {
checkBoxTest();
});
function checkBoxTest() {
for (i = 0; i < 10; i++) {
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' + i + ' "/><td></tr>');
}
test();
}
function test() {
var emails = [],
textField = document.getElementById("root");
$('#catalog_table input:checkbox').change(function () {
var val = $(this).val();
// if you don't want removal of values on `uncheck`, comment out everything below excluding `emails.push(val)` and the last line
if(this.checked){ // if checked
emails.push(val); // add it
}else{
emails.splice(emails.indexOf(val), 1); // remove it if not checked
}
textField.value = emails; // set the value
});
}
DEMO

Moving checked items to the top after unchecking all items

I implemented a solution, moving checked items to top of list, using
Keep checked items at top of list
Now, I have an anchor to uncheck all items in the list. The items are unchecked once we click the anchor tag. But the items are not sorting. It should default to first displayed list, as in html list:
var list = $("ul"),
origOrder = list.children();
list.on("click", ":checkbox", function () {
var i, checked = document.createDocumentFragment(),
unchecked = document.createDocumentFragment();
for (i = 0; i < origOrder.length; i++) {
if (origOrder[i].getElementsByTagName("input")[0].checked) {
checked.appendChild(origOrder[i]);
} else {
unchecked.appendChild(origOrder[i]);
}
}
list.append(checked).append(unchecked);
});
The demo of the scenario can be found here
http://jsfiddle.net/RPN3x/
in JS
var list = $("ul");
var html=$("ul").html();
sortItems(list);
var anch = $('#clear');
list.on('click',"a",function(){
var list = $("ul"); //$(this).parents().eq(0).find(':checkbox').removeAttr('checked');
$("ul").html(html);
sortItems(list);
});
function sortItems(list){
origOrder = list.children();
list.on("click", ":checkbox", function() {
var i, checked = document.createDocumentFragment(),
unchecked = document.createDocumentFragment();
for (i = 2; i < origOrder.length; i++) {
if (origOrder[i].getElementsByTagName("input")[0].checked) {
checked.appendChild(origOrder[i]);
} else {
unchecked.appendChild(origOrder[i]);
}
}
list.append(checked).append(unchecked);
});
}
see DEMO

getting selected radio button value

I am adding a radio button in a gridrow dynamically on rowdatabound event.
I want value of selected radio button of specific row of grid.
Currently I am getting value bt it will no return the value for specific row index.
See my below code:
function GetBlastid()
{
var gv = document.getElementById("<%=grdOofMailProcess.ClientID%>");
var rbs = gv.getElementsByTagName("input");
var flag = 0;
for (var i = 0; i < rbs.length; i++)
{
if (rbs[i].type == "radio")
{
if (rbs[i].checked)
{
alert(rbs[i]);
flag = 1;
document.getElementById('hdnBlastId').value=rbs[i].value
break;
}
}
}
}
well once you get which radiobox is checked navigate to its parent and get the row index row.rowIndex , i couldnt give you the exact code coz i dont know how you placed the radio button, whether its directly under a column or have a different parent.
function GetBlastid()
{
var gv = document.getElementById("<%=grdOofMailProcess.ClientID%>");
var rbs = gv.getElementsByTagName("input");
var flag = 0;
for (var i = 0; i < rbs.length; i++)
{
if (rbs[i].type == "radio")
{
if (rbs[i].checked)
{
alert(rbs[i]);
//here get the parent of rbs[i] and navigate to the row to get the row index.
flag = 1;
document.getElementById('hdnBlastId').value=rbs[i].value
break;
}
}
}
}

Categories