Get a listbox's selected items in javascript - asp.net

I have two listboxes in asp.net. On the click of a button I want to load a list box with the elements of the selected items in the other box. The problem is that this has to be done on the client side because when the button is clicked I don't allow it to submit. I want to call a javascript function onselectedindexchange but that is server side. any ideas? Should i be more clear?
Solution
enter code here
function Updatelist() {
var sel = document.getElementById('<%=ListBox1.ClientID%>')
var lst2 = document.getElementById('<%=ListBox2.ClientId %>')
var listLength = sel.options.length;
var list2length = lst2.options.length;
for (var i = 0; i < listLength; i++) {
if (sel.options[i].selected) {
//lst2.options.add(sel.options[i].text);
lst2.options[list2length] = new Option(sel.options[i].text);
list2length++;
}
}
}

Try:
//onclick for button calls this function
function Updatelist() {
var sel = document.getElementbyId("list1");
var listLength = sel.options.length;
for(var i=0;i<listLength;i++){
if(sel.options[i].selected)
document.getElementById("list2").add(new Option(sel.options[i].value));
}

more precisely we can do it like;
function selectedVal(list) {
alert(list.options[list.selectedIndex].text);
}
<select id="listbox" multiple="multiple"
style="height: 300px; width: 200px;"
onclick="javascript:selectedVal(this);">
</select>

Here is a good article on how to do this using Jquery.
You could also stick your drop downs in an Update Panel.

function Updatelist() {
var sel = document.getElementById('<%=ListBox1.ClientID%>')
var lst2 = document.getElementById('<%=ListBox2.ClientId %>')
var listLength = sel.options.length;
var list2length = lst2.options.length;
for (var i = 0; i < listLength; i++) {
if (sel.options[i].selected) {
//lst2.options.add(sel.options[i].text);
lst2.options[list2length] = new Option(sel.options[i].text);
list2length++;
}
}
}

Related

creating a Placemarks that can be hidden

I have been trying to create a Placemark that I can hide and show (like turning visibility on and off) on demand (on click)... I am using this to make the placemark:
function placemark(lat, long, name, url, iconsrc){
var placemark = ge.createPlacemark(name);
ge.getFeatures().appendChild(placemark);
placemark.setName(name);
// Create style map for placemark
var icon = ge.createIcon('');
if(iconsrc == "0")
icon.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');
else{
icon.setHref(iconsrc);
}
var style = ge.createStyle('');
style.getIconStyle().setIcon(icon);
if(iconsrc != "0")
style.getIconStyle().setScale(2.5);
placemark.setStyleSelector(style);
// Create point
var point = ge.createPoint('');
point.setLatitude(lat);
point.setLongitude(long);
//point.setAltitudeMode(1500);
placemark.setGeometry(point);
google.earth.addEventListener(placemark, 'click', function(event) {
// Prevent the default balloon from popping up.
event.preventDefault();
var balloon = ge.createHtmlStringBalloon('');
balloon.setFeature(placemark); // optional
balloon.setContentString(
'<iframe src="'+ url +'" frameborder="0"></iframe>');
ge.setBalloon(balloon);
});
}
I have tried everything... from this:
function hidePlacemark(name){
var children = ge.getFeatures().getChildNodes();
for(var i = 0; i < children.getLength(); i++) {
var child = children.item(i);
if(child.getType() == 'KmlPlacemark') {
if(child.getId()== name)
child.setVisibility(false);
}
}
}
to using this ge.getFeatures().removeChild(child);
can anyone point me to the right direction on creating a function that will allow me to turn the visibility on/off on demand please.
Your hidePlacemark function is missing some {} in your final IF statement
if(child.getId()== name)
you have
function hidePlacemark(name){
var children = ge.getFeatures().getChildNodes();
for(var i = 0; i < children.getLength(); i++) {
var child = children.item(i);
if(child.getType() == 'KmlPlacemark') {
if(child.getId()== name)
child.setVisibility(false);
}
}
}
make it
function hidePlacemark(name){
var children = ge.getFeatures().getChildNodes();
for(var i = 0; i < children.getLength(); i++) {
var child = children.item(i);
if(child.getType() == 'KmlPlacemark') {
if(child.getId()== name) {
child.setVisibility(false);
}
}
}
}
HOWEVER ------- you are better off doing this as it is much faster as you don't need to loop through ALL your placemarks
function hidePlacemark(name) {
var placemark = ge.getElementById(name);
placemark.setVisibility(false);
}
I think the plain ge.getFeatures().removeChild(placemark); works.
I played with this GooglePlayground, and just added the following code to line 8 (that is empty in this GooglePlayground Sample):
addSampleButton('Hide Placemark', function(){
ge.getFeatures().removeChild(placemark);
});
Clicking the button Hide Placemark hides the placemark like a charm here. Any chances your problem is somewhere else in your code?

Client side sorting on ASP.NET MVC WebGrid

I have a partial view which contain an MVC WebGrid as below
<div id="grid">
#{
var grid = new WebGrid(source: Model.Items,
defaultSort: "Name",
rowsPerPage: 100);
}
#grid.GetHtml(columns: grid.Columns(
grid.Column(columnName: "Name", header: "Name", canSort:true),
grid.Column(columnName: "Code", header: "Code")
))
</div>
This partial view is loaded using Jquery ajax call and result is inserted into a DIV in the main page.
The table render fine but my problem is that the sorting always generates a callback to the server. I want the sorting to happen at the client side only. Is it possible using WebGrid without using external datatables like jQuery datatable?
Thanks in advance
You should probably implement Cline-Side Sorting by yourself according to the loaded table take a look here...
NOTE!: you could always make it more generic by using html attributes to tag your WebGrid.
Tag the table with 'data-clineSideSort=true' then add a jquery event that will attach the JS functionality to all such tables holding this property...
function SortTable(sortOn)
{
var table = document.getElementById('results');
var tbody = table.getElementsByTagName('tbody')[0];
var rows = tbody.getElementsByTagName('tr');
var rowArray = new Array();
for (var i = 0, length = rows.length; i < length; i++)
{
rowArray[i] = new Object;
rowArray[i].oldIndex = i;
rowArray[i].value = rows[i].getElementsByTagName('td')[sortOn].firstChild.nodeValue;
}
if (sortOn == sortedOn) {
rowArray.reverse();
}
else {
sortedOn = sortOn;
/*
Decide which function to use from the three:RowCompareNumbers,
RowCompareDollars or RowCompare (default).
For first column, I needed numeric comparison.
*/
if (sortedOn == 0) {
rowArray.sort(RowCompareNumbers);
}
else {
rowArray.sort(RowCompare);
}
}
var newTbody = document.createElement('tbody');
for (var i = 0, length = rowArray.length; i < length; i++)
{
newTbody.appendChild(rows[rowArray[i].oldIndex].cloneNode(true));
}
table.replaceChild(newTbody, tbody);
}
function RowCompare(a, b)
{
var aVal = a.value;
var bVal = b.value;
return (aVal == bVal ? 0 : (aVal > bVal ? 1 : -1));
}
// Compare number
function RowCompareNumbers(a, b)
{
var aVal = parseInt(a.value);
var bVal = parseInt(b.value);
return (aVal - bVal);
}
// compare currency
function RowCompareDollars(a, b)
{
var aVal = parseFloat(a.value.substr(1));
var bVal = parseFloat(b.value.substr(1));
return (aVal - bVal);
}
Have a look at jQuery Tablesorter. It can be applied to any well formed table (ie, has thead and tbodyelements. The only gotcha I can think of here is to make sure you bind table sorter once the data has been loaded in your ajax call.

auto Focus (Hit Enter) Javascript function is working good in IE7 but not working in IE8

I used a javascript FocusChange() in my aspx page. I have couple of controls and I need Hit enter key need to move next control based on tab index. It is working good in IE7 but not working in IE8... Please help me on this..
Thanks for your help in advance. The java script is given below.
function FocusChange() {
if (window.event.keyCode == 13) {
var formLength = document.form1.length; // Get number of elements in the form
var src = window.event.srcElement; // Gets the field having focus
var currentTabIndex = src.getAttribute('tabindex'); // Gets its tabindex
// scroll through all form elements and set focus in field having next tabindex
for (var i = 0; i < formLength; i++) {
if (document.form1.elements[i].getAttribute('tabindex') == currentTabIndex + 1) {
for (var j = i; j <= formLength; j++) {
if (document.form1.elements[j].disabled == false) {
document.form1.elements[j].focus();
event.returnValue = false;
event.cancel = true;
return;
}
}
}
}
}
}
I've got the same request as you, but solved it in a different manner, just replacing the Enter for Tab
<script language="JavaScript">
document.onkeydown = myOnkeydown;
function myOnkeydown()
{
var key = window.event.keyCode;
if (key == 13) //13 is the keycode of the 'Enter' key
{window.event.keyCode = 9; //9 is the code for the 'Tab' key. Essentially replacing the Enter with the Tab.
}
}
</script>
Warning: Works in IE only.

Jquery Listbox / Textbox filter

I have the following jquery function for filtering the contents of a listbox on the onkeyup event from a textbox.
function DoListBoxFilter(listBoxSelector, filter, keys, values) {
var list = $(listBoxSelector);
var selectBase = '<option value="{0}">{1}</option>';
list.empty();
for (i = 0; i < values.length; ++i) { //add elements from cache if they match filter
var value = values[i];
if (value == "" || value.toLowerCase().indexOf(filter.toLowerCase()) >= 0) {
var temp = String.format(selectBase, keys[i], value);
list.append(temp);
}
}
}
It works great for small to medium size lists, but it is a little bit slow when working with lists over 300-400 items... Can anyone help with some ideas to optimize the javascript a little bit to speed up the function?
The function is invoked with the following code:
$('#<% = txtSearch.ClientID %>').keyup(function() {
var filter = $(this).val();
DoListBoxFilter('#<% = lstPars.ClientID %>', filter, keys_<% = this.ClientID %>, values_<% = this.ClientID %>);
});
To use this, I bind an asp.net listbox and also populate two javascript arrays (key and value) on the page.
This IS storing the data in two places on the page, but using this method I am able to use the postback of the listbox to get the selected value without using javacript to extract the value and cache it in a hidden div. (it also saves having to run the function at page load on the clients browser.. and that is really the function where I am seeing the slowness, so storing in two places speeds up the page rendering)
I found that I needed to use the javascript array approach because most browsers don't acknowledge any attempts to hide an option tag... only Firefox appears to do it.
I'm not sure its possible to optimize and speed this code up any more, but if anyone has any ideas I would appreciate it.
Thanks,
Max Schilling
I am also using the same code to filter the list box but with a bit of change, in my code first I am comparing the searched value/word with the option items and if match got success then only filtering the list.
var existText = values[i].substring(0, filter.length);
if (existText.toLowerCase() == filter.toLowerCase())
Below is the full code:
function DoListBoxFilter(listBoxSelector, filter, keys, values) {
var list = $(listBoxSelector);
var selectBase = '<option value="{0}">{1}</option>';
list.empty();
for (i = 0; i < values.length; ++i) {
var existText = values[i].substring(0, filter.length);
if (existText.toLowerCase() == filter.toLowerCase()) {
var value = values[i];
if (value === "" || value.toLowerCase().indexOf(filter.toLowerCase()) >= 0) {
var temp = '<option value="' + keys[i] + '">' + value + '</option>';
list.append(temp);
}
}
}
}
var keys = [];
var values = [];
var options = $('#CountryList option');
$.each(options, function (index, item) {
keys.push(item.value);
values.push(item.innerHTML);
});
$(document).ready(function () {
$('input#CountrySearch').on('keyup', function () {
var filter = $(this).val();
DoListBoxFilter('#CountryList', filter, keys, values);
});
});
You can also see a demo here. In this demo I have used a list containing the more than 500 list items and its working fine without any performance issue.
It looks like you might be suffering in terms of performance with large lists because you are appending each item one at a time that matches the filter. I would build up an array of matches (or create a documentFragment) and then append that to the DOM in one go.
function DoListBoxFilter(listBoxSelector, filter, keys, values) {
var list = $(listBoxSelector);
var selectBase = '<option value="{0}">{1}</option>';
list.empty();
var i = values.length;
var temp = [];
var option, value;
while (i--) {
value = values[i];
if (value && value.toLowerCase().indexOf(filter.toLowerCase()) !== -1) {
option = String.format(selectBase, keys[i], value);
temp.push(option);
}
}
// we got all the options, now append to DOM
list.append(temp.join(''));
}
Following link helped me, though it is javascript.
Search ListBox items using JavaScript
<head id="Head1" runat="server">
<title>Demo</title>
</head>
<script type="text/javascript" language="javascript">
function SearchList()
{
var l = document.getElementById('<%= ListBox1.ClientID %>');
var tb = document.getElementById('<%= TextBox1.ClientID %>');
if(tb.value == ""){
ClearSelection(l);
}
else{
for (var i=0; i < l.options.length; i++){
if (l.options[i].value.toLowerCase().match(tb.value.toLowerCase()))
{
l.options[i].selected = true;
return false;
}
else
{
ClearSelection(l);
}
}
}
}
function ClearSelection(lb){
lb.selectedIndex = -1;
}
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" onkeyup="return SearchList();"/><br />
<asp:ListBox ID="ListBox1" runat="server" Height="150px" Width="250px">
<asp:ListItem>Vincent</asp:ListItem>
<asp:ListItem>Jennifer</asp:ListItem>
<asp:ListItem>Shynne</asp:ListItem>
<asp:ListItem>Christian</asp:ListItem>
<asp:ListItem>Helen</asp:ListItem>
<asp:ListItem>Vladi</asp:ListItem>
<asp:ListItem>Bee</asp:ListItem>
<asp:ListItem>Jerome</asp:ListItem>
<asp:ListItem>Vinz</asp:ListItem>
<asp:ListItem>Churchill</asp:ListItem>
<asp:ListItem>Rod</asp:ListItem>
<asp:ListItem>Mark</asp:ListItem>
</asp:ListBox>
</form>
</body>
</html>

jQuery with ASP.NET - How to Create, Populate, and Show UL

In an ASP.NET web app, I am trying to create and populate a UL based on user input. This is not a quick fill. User enters a couple of letters, clicks a button, and the server returns all records like the entry. If there is more than one match, an UL is created showing all of the matches.
I've tried to adapt this code from a plugin. I can step through it with the debugger and everything seems OK, but the UL is either not generated to the document or it is invisible.
Here is the simplified code:
function fillBusinessDropdown(ListOfBusinesses) {
var results = document.createElement("div");
var $results = $(results);
$results.hide().addClass("ac_results").css("position", "absolute");
if ($.browser.msie) {
$results.append(document.createElement('iframe'));
}
results.appendChild(businessToDom(ListOfBusinesses));
$results.css({
width: 400 + "px",
top: 100 + "px",
left: 150 + "px"
}).show();
function businessToDom(ListOfBusinesses) {
var ul = document.createElement("ul");
var iLen = ListOfBusinesses.length - 1
for (var i = 0; i <= iLen; i++) {
var row = ListOfBusinesses[i];
if (!row) continue;
var li = document.createElement("li");
// add the business name
li.innerHTML = row.Bu_name;
// add the business ID
li.selectValue = row.Bupk;
var extra = null;
if (row.length > 1) {
extra = [];
for (var j = 1; j < row.length; j++) {
extra[extra.length] = row[j];
}
}
li.extra = extra;
ul.appendChild(li);
$(li).hover(
function() { $("li", ul).removeClass("ac_over");
$(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
function() { $(this).removeClass("ac_over"); }
).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
}
return ul;
}
I am stumped. Does any0oe have any ideas where I've gone wrong?
Thanks
Mike Thomas
Not sure what is wrong with that code but you are using a mixture of javascript and Jquery. I suggest use JQuery all the time instead. Use .appendTo() etc

Resources