How to add dynamic textbox in MVC3 razor on button click - asp.net

I want to create the textbox dynamically on button click and remove it on another button click.
I have made it with jquery which is working fine.
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for (i = 1; i < counter; i++) {
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<input type="textbox" id="textbox1" />
</div></div><input type='button' value='Add Button' id='addButton' /><input type='button' value='Remove Button' id='removeButton' /><input type='button' value='Get TextBox Value' id='getButtonValue' />
But i want this functionality with mvc3 razor.

Related

Google Place Search using SearchBox - Restrict for UK only

I am using google place SearchBox ( not AutoComplete ) for place search. My objective is I want to restrict the search for a particular country (UK).
I know the same thing can be achieved easily by using AutoComplete. But I can't use this because my map will populate on enter key as well as against a search button.
I am using code to select the first option on search button click.
I have tried with google.maps.LatLngBounds but that only sets the priority of result, not restricting anything.
Html:
<ul class="list-unstyled search-branch">
<li>Search branches:</li>
<li><input type="text" placeholder="City, town or postcode" id="txtbranch" value="Eurochange" />
<input type="button" class="button gold" id="getbranch" value="Search" />
<div style="clear:both;"></div>
<div class="error-message-summary" id="locationnotfound" style="padding: 0;top:-30px; position:relative; font-size:16px;display:none">
No search results found.
</div>
</li>
</ul>
js:
var input = document.getElementById('txtbranch');
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 1512631)
);
var options = {
bounds: defaultBounds
}
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
$('#getbranch').click(function () {
var input = document.getElementById('txtbranch');
if (BranchAddressSelector.val() == "") {
return;
}
google.maps.event.trigger(input, 'focus');
google.maps.event.trigger(input, 'keydown', { keyCode: 13 });
return false;
})
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces()[0];
if (typeof (places) === "undefined") {
locationNotFoundSelector.css("display", "block");
return false;
}
if (BranchAddressSelector.val() == "") {
return false;
}
var address = places.formatted_address;
if (typeof (address) === "undefined") {
locationNotFoundSelector.css("display", "block");
return false;
}
var latitude = places.geometry.location.lat();
var longitude = places.geometry.location.lng();
$.ajax({
type: "GET",
url: BranchLocatorUrl.GetBranches,
data: { Latitude: latitude, longitude: longitude },
success: function (data) {
if (data.length > 0) {
markers = data;
LoadMap(0, 0);
BranchListSelector.html(CreateSearchHtml(markers));
goToByScroll("dvMap");
BranchListSelector.css("display", "none");
paginationSelector.css("display", "none");
$('.map-distance').css("display", "block");
locationNotFoundSelector.css("display", "none");
var show_per_page = 6;
var number_of_items = BranchListSelector.children('.BranchItem').size();
var number_of_pages = Math.ceil(number_of_items / show_per_page);
totalPages = number_of_pages;
$('#current_page').val(0);
$('#show_per_page').val(show_per_page);
var navigation_html = '<a class="previous_link" style="color: #007ea0;" href="javascript:previous();">Prev</a> ';
var current_link = 0;
while (number_of_pages > current_link) {
navigation_html += '<a class="page_link" style="color: #007ea0;" href="javascript:go_to_page(' + current_link + ')" longdesc="' + current_link + '">' + (current_link + 1) + '</a> ';
current_link++;
}
navigation_html += '<a class="next_link" style="color: #007ea0;" href="javascript:next();"> Next</a>';
$('#page_navigation').html(navigation_html).css("float", "right").css("display", "none");
$('#page_navigation .page_link:first').addClass('active_page');
BranchListSelector.children('.BranchItem').css('display', 'none');
BranchListSelector.children('.BranchItem').slice(0, show_per_page).css('display', 'block');
BranchListSelector.css("display", "block");
// paginationSelector.css("display", "block");
$('.map-distance').css("display", "none");
$('#moreBranch').css("display", "block");
}
else {
alert("Data not found.");
}
},
error: function (e) {
alert("Some Problem occurs.Try after some time");
return;
}
});
});

jquery dialog result not updating the control

I'm updating the value of a textbox when the jqueryui.dialog is closed. It displays the value in the textbox but when the textbox gets focus the value disappears. I just can't figure out the reason. There is no onfocus/onblur event on the textbox.
I'm updating the textbox value like this
$("#mycontrol").val(displayresult);
$(html).dialog({
modal: true,
height: 300,
overflow: scroll,
buttons: {
"Select": function () {
$(this).dialog("close");
var value, splitPosition, itemValues, displayValues;
var displayresult = "";
var itemresult = "";
var septex = "";
var sepval = "";
$("input:checkbox" && "[id^=" + controlName + "_selectionBoxCheckBox]").each(function () {
var $this = $(this);
if ($this.is(":checked")) {
value = $this.val();
splitPosition = value.indexOf("-");
itemValues = $this.val().substr(0, splitPosition);
displayValues = $this.val().substr(splitPosition + 1);
itemresult += sepval + itemValues;
displayresult += septex + displayValues;
sepval = ",";
septex = ", ";
}
});
$("#mycontrol").val(displayresult);
$(this).dialog('destroy').remove();
},
Cancel: function () {
$(this).dialog("close");
}
},
close: function () {
//alert('close');
},
beforeClose: function (event, ui) {
//alert("before close");
}
});
I wrapped this with some HTML code and it works fine. There must be some other code causing the problem.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
<body>
<form>
<input type="text" id="mycontrol" />
</form>
<div id="dialog" title="Dialog Title">
one <input type="checkbox" id="cb_selectionBoxCheckBox1" value="1-one" /><br />
two <input type="checkbox" id="cb_selectionBoxCheckBox2" value="2-two" /><br />
three <input type="checkbox" id="cb_selectionBoxCheckBox3" value="3-three" /><br />
</div>
<script type="text/javascript">
var displayresult="initial";
var controlName="cb";
var html='#dialog';
$().ready(function(){
$("#mycontrol").val(displayresult);
$(html).dialog({
modal: true,
height: 300,
overflow: scroll,
buttons: {
"Select": function () {
$(this).dialog("close");
var value, splitPosition, itemValues, displayValues;
var displayresult = "";
var itemresult = "";
var septex = "";
var sepval = "";
$("input:checkbox" && "[id^=" + controlName + "_selectionBoxCheckBox]").each(function () {
var $this = $(this);
if ($this.is(":checked")) {
value = $this.val();
splitPosition = value.indexOf("-");
itemValues = $this.val().substr(0, splitPosition);
displayValues = $this.val().substr(splitPosition + 1);
itemresult += sepval + itemValues;
displayresult += septex + displayValues;
sepval = ",";
septex = ", ";
}
});
$("#mycontrol").val(displayresult);
$(this).dialog('destroy').remove();
},
Cancel: function () {
$(this).dialog("close");
}
},
close: function () {
//alert('close');
},
beforeClose: function (event, ui) {
//alert("before close");
}
});
});
</script>
</body>
</html>

Add 'See on Map' Link in Fusion Tables Map List View

I am using the wonderful Fusion Tables Map Template by Derek Eder. I have activated the results list as instructed by him here.
I would like to have a 'See on Map' link on each listing so that when i click on the link the page scrolls up to the map and opens an infowindow for that particular listing. You can see an example on the geo places theme.
Below is my code
HTML
<!DOCTYPE html>
<html lang='en'>
<head>
<link rel="stylesheet" href="bootstrap.spacelab.min.css"/>
<link rel="stylesheet" href="bootstrap-responsive.min.css"/>
<link rel="stylesheet" href="custom.css"/>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
</head>
<body>
<div class='navbar'>
<div class='navbar-inner'>
<div class='container'>
<a class='brand' href='/'>Worldwide Stores</a>
</div>
</div>
</div>
<div class='container-fluid'>
<div class='row-fluid'>
<div class='span4'>
<div class='well'>
<h4>
Address <small>(<a id='find_me' href='#'>find me</a>)</small>
</h4>
<input class='input-block-level' id='search_address' placeholder='Enter an address or an intersection' type='text' />
<label>
show companies within
<select class='input-small' id='search_radius'>
<option value='400'>2 blocks</option>
<option value='805'>1/2 mile</option>
<option value='1610'>1 mile</option>
<option value='3220'>2 miles</option>
<option value='8050'>5 miles</option>
<option value='16100'>10 miles</option>
<option value='40250'>25 miles</option>
<option value='80500'>50 miles</option>
<option value='161000'>100 miles</option>
<option value='402500'>250 miles</option>
<option value='805000'>500 miles</option>
<option value='1610000'>1000 miles</option>
</select>
</label>
<h5> Refine Your Search By:</h5>
<label>
<select id='select_type'>
<option value=''>All Categories</option>
<option value='Hotels'>Hotels</option>
<option value='Restaurants'>Restaurants</option>
<option value='Shopping Malls'>Shopping Malls</option>
<option value='Travel Agents'>Travel Agents</option>
</select>
</label>
<label>
<select disabled id='select_type1'>
<option value=''>Select Two</option>
<option value='male'>Male</option>
<option value='female'>Female</option>
</select>
</label>
<label>
<select disabled id='select_type2'>
<option value=''>Select Three</option>
<option value='Advanced Materials/Prd'>Advanced Materials/Prd</option>
<option value='Advertising Agencies'>Advertising Agencies</option>
<option value='Advertising Sales'>Advertising Sales</option>
<option value='Advertising Services'>Advertising Services</option>
</select>
</label>
<input class='btn btn-primary' id='search' type='button' value='Search' />
<button class='btn' id='reset'>Reset</button>
</div>
<p class='alert alert-info lead' id='result_count'></p>
</p> </p>
</p> </p>
</p> </p>
</div>
<div class='span8'>
<div id='map_canvas'></div>
<div class='well'>
<div id='results_list'></div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="source/jquery.js"></script>
<script type="text/javascript" src="source/bootstrap.js"></script>
<script type="text/javascript" src="source/jquery.address.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript" src="source/jquery.geocomplete.min.js"></script>
<script type="text/javascript" src="maps_lib.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(window).resize(function () {
var h = $(window).height(),
offsetTop = 90; // Calculate the top offset
$('#map_canvas').css('height', (h - offsetTop));
}).resize();
$(function() {
MapsLib.initialize();
$("#search_address").geocomplete();
$(':checkbox').click(function(){
MapsLib.doSearch();
});
$(':radio').click(function(){
MapsLib.doSearch();
});
$('#search_radius').change(function(){
MapsLib.doSearch();
});
$('#select_type').change(function(){
MapsLib.doSearch();
});
$('#select_type1').change(function(){
MapsLib.doSearch();
});
$('#select_type2').change(function(){
MapsLib.doSearch();
});
$('#search').click(function(){
MapsLib.doSearch();
});
$('#find_me').click(function(){
MapsLib.findMe();
return false;
});
$('#reset').click(function(){
$.address.parameter('address','');
MapsLib.initialize();
return false;
});
$(":text").keydown(function(e){
var key = e.keyCode ? e.keyCode : e.which;
if(key == 13) {
$('#search').click();
return false;
}
});
});
//]]>
</script>
</body>
</html>
maps_lib.js
/*!
* Searchable Map Template with Google Fusion Tables
* http://derekeder.com/searchable_map_template/
*
* Copyright 2012, Derek Eder
* Licensed under the MIT license.
* https://github.com/derekeder/FusionTable-Map-Template/wiki/License
*
* Date: 12/10/2012
*
*/
var MapsLib = MapsLib || {};
var MapsLib = {
//Setup section - put your Fusion Table details here
//Using the v1 Fusion Tables API. See https://developers.google.com/fusiontables/docs/v1/migration_guide for more info
//the encrypted Table ID of your Fusion Table (found under File => About)
//NOTE: numeric IDs will be deprecated soon
fusionTableId: "1f8rnajgS2iSVwwBR1NwXwImUuFB7VCpOg1-IfCs",
//*New Fusion Tables Requirement* API key. found at https://code.google.com/apis/console/
//*Important* this key is for demonstration purposes. please register your own.
googleApiKey: "API KEY",
//name of the location column in your Fusion Table.
//NOTE: if your location column name has spaces in it, surround it with single quotes
//example: locationColumn: "'my location'",
locationColumn: "Address",
map_centroid: new google.maps.LatLng(17,15), //center that your map defaults to
locationScope: "", //geographical area appended to all address searches
recordName: "Store", //for showing number of results
recordNamePlural: "Stores",
searchRadius: 805, //in meters ~ 1/2 mile
defaultZoom: 2, //zoom level when map is loaded (bigger is more zoomed in)
addrMarkerImage: 'http://derekeder.com/images/icons/blue-pushpin.png',
currentPinpoint: null,
initialize: function() {
$( "#result_count" ).html("");
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: MapsLib.defaultZoom,
center: MapsLib.map_centroid,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($("#map_canvas")[0],myOptions);
// maintains map centerpoint for responsive design
google.maps.event.addDomListener(map, 'idle', function() {
MapsLib.calculateCenter();
});
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(MapsLib.map_centroid);
});
MapsLib.searchrecords = null;
//reset filters
$("#search_address").val(MapsLib.convertToPlainString($.address.parameter('address')));
var loadRadius = MapsLib.convertToPlainString($.address.parameter('radius'));
if (loadRadius != "") $("#search_radius").val(loadRadius);
else $("#search_radius").val(MapsLib.searchRadius);
$(":checkbox").attr("checked", "checked");
$("#result_count").hide();
//-----custom initializers-------
//run the default search
MapsLib.doSearch();
},
doSearch: function(location) {
MapsLib.clearSearch();
var address = $("#search_address").val();
MapsLib.searchRadius = $("#search_radius").val();
var whereClause = MapsLib.locationColumn + " not equal to ''";
//-----custom filters-------
if ( $("#select_type").val() != "") {
whereClause += " AND 'Category' = '" + $("#select_type").val() + "'";
}
if ( $("#select_type1").val() != "") {
whereClause += " AND 'sex' = '" + $("#select_type1").val() + "'";
}
if ( $("#select_type2").val() != "") {
whereClause += " AND 'Subindustry' = '" + $("#select_type2").val() + "'";
}
//-------end of custom filters--------
if (address != "") {
if (address.toLowerCase().indexOf(MapsLib.locationScope) == -1)
address = address + " " + MapsLib.locationScope;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
MapsLib.currentPinpoint = results[0].geometry.location;
$.address.parameter('address', encodeURIComponent(address));
$.address.parameter('radius', encodeURIComponent(MapsLib.searchRadius));
map.setCenter(MapsLib.currentPinpoint);
map.setZoom(14);
if (MapsLib.searchRadius == "400")
map.setZoom(16);
else if (MapsLib.searchRadius == "805")
map.setZoom(15);
else if (MapsLib.searchRadius == "1610")
map.setZoom(14);
else if (MapsLib.searchRadius == "3220")
map.setZoom(13);
else if (MapsLib.searchRadius == "8050")
map.setZoom(12);
else if (MapsLib.searchRadius == "16100")
map.setZoom(11);
else if (MapsLib.searchRadius == "40250")
map.setZoom(09);
else if (MapsLib.searchRadius == "80500")
map.setZoom(08);
else if (MapsLib.searchRadius == "161000")
map.setZoom(07);
else if (MapsLib.searchRadius == "402500")
map.setZoom(06);
else if (MapsLib.searchRadius == "805000")
map.setZoom(05);
else if (MapsLib.searchRadius == "1610000")
map.setZoom(04);
else
map.setZoom(14);
MapsLib.addrMarker = new google.maps.Marker({
position: MapsLib.currentPinpoint,
map: map,
icon: MapsLib.addrMarkerImage,
animation: google.maps.Animation.DROP,
title:address
});
whereClause += " AND ST_INTERSECTS(" + MapsLib.locationColumn + ", CIRCLE(LATLNG" + MapsLib.currentPinpoint.toString() + "," + MapsLib.searchRadius + "))";
MapsLib.drawSearchRadiusCircle(MapsLib.currentPinpoint);
MapsLib.submitSearch(whereClause, map, MapsLib.currentPinpoint);
}
else {
alert("We could not find your address: " + status);
}
});
}
else { //search without geocoding callback
MapsLib.submitSearch(whereClause, map);
}
},
submitSearch: function(whereClause, map, location) {
//get using all filters
//NOTE: styleId and templateId are recently added attributes to load custom marker styles and info windows
//you can find your Ids inside the link generated by the 'Publish' option in Fusion Tables
//for more details, see https://developers.google.com/fusiontables/docs/v1/using#WorkingStyles
MapsLib.searchrecords = new google.maps.FusionTablesLayer({
query: {
from: MapsLib.fusionTableId,
select: MapsLib.locationColumn,
where: whereClause
},
styleId: 2,
templateId: 2
});
MapsLib.searchrecords.setMap(map);
MapsLib.getCount(whereClause);
MapsLib.getList(whereClause);
},
clearSearch: function() {
if (MapsLib.searchrecords != null)
MapsLib.searchrecords.setMap(null);
if (MapsLib.addrMarker != null)
MapsLib.addrMarker.setMap(null);
if (MapsLib.searchRadiusCircle != null)
MapsLib.searchRadiusCircle.setMap(null);
},
findMe: function() {
// Try W3C Geolocation (Preferred)
var foundLocation;
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
foundLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
MapsLib.addrFromLatLng(foundLocation);
}, null);
}
else {
alert("Sorry, we could not find your location.");
}
},
addrFromLatLng: function(latLngPoint) {
geocoder.geocode({'latLng': latLngPoint}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
$('#search_address').val(results[1].formatted_address);
$('.hint').focus();
MapsLib.doSearch();
}
} else {
alert("Geocoder failed due to: " + status);
}
});
},
drawSearchRadiusCircle: function(point) {
var circleOptions = {
strokeColor: "#4b58a6",
strokeOpacity: 0.3,
strokeWeight: 1,
fillColor: "#4b58a6",
fillOpacity: 0.05,
map: map,
center: point,
clickable: false,
zIndex: -1,
radius: parseInt(MapsLib.searchRadius)
};
MapsLib.searchRadiusCircle = new google.maps.Circle(circleOptions);
},
query: function(selectColumns, whereClause, callback) {
var queryStr = [];
queryStr.push("SELECT " + selectColumns);
queryStr.push(" FROM " + MapsLib.fusionTableId);
queryStr.push(" WHERE " + whereClause);
var sql = encodeURIComponent(queryStr.join(" "));
$.ajax({url: "https://www.googleapis.com/fusiontables/v1/query?sql="+sql+"&callback="+callback+"&key="+MapsLib.googleApiKey, dataType: "jsonp"});
},
handleError: function(json) {
if (json["error"] != undefined) {
var error = json["error"]["errors"]
console.log("Error in Fusion Table call!");
for (var row in error) {
console.log(" Domain: " + error[row]["domain"]);
console.log(" Reason: " + error[row]["reason"]);
console.log(" Message: " + error[row]["message"]);
}
}
},
getCount: function(whereClause) {
var selectColumns = "Count()";
MapsLib.query(selectColumns, whereClause,"MapsLib.displaySearchCount");
},
displaySearchCount: function(json) {
MapsLib.handleError(json);
var numRows = 0;
if (json["rows"] != null)
numRows = json["rows"][0];
var name = MapsLib.recordNamePlural;
if (numRows == 1)
name = MapsLib.recordName;
$( "#result_count" ).fadeOut(function() {
$( "#result_count" ).html(MapsLib.addCommas(numRows) + " " + name + " found");
});
$( "#result_count" ).fadeIn();
},
getList: function(whereClause) {
var selectColumns = "StoreName, Address, Contact, Website";
MapsLib.query(selectColumns, whereClause, "MapsLib.displayList");
},
displayList: function(json) {
MapsLib.handleError(json);
var data = json["rows"];
var template = "";
var results = $("#results_list");
results.hide().empty(); //hide the existing list and empty it out first
if (data == null) {
//clear results list
results.append("<li><span class='lead'>No results found</span></li>");
}
else {
for (var row in data) {
template = "\
<div class='row-fluid item-list'>\
<div class='span12'>\
<span class='lead'>" + data[row][0] + "\</span>\
<br />\
" + data[row][4] + "\
<br />\
" + data[row][5] + "\
<br />\
<a href='" + data[row][6] + "'>\
<span>" + data[row][7] + "\</span>\
</a>\
<br />\
<a onClick=''>\
<span style='color: red;'>See on Map</span>\
</a>\
</div>\
</div>"
results.append(template);
}
}
results.fadeIn();
},
addCommas: function(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
},
// maintains map centerpoint for responsive design
calculateCenter: function() {
center = map.getCenter();
},
//converts a slug or query string in to readable text
convertToPlainString: function(text) {
if (text == undefined) return '';
return decodeURIComponent(text);
}
//-----custom functions-------
// NOTE: if you add custom functions, make sure to append each one with a comma, except for the last one.
// This also applies to the convertToPlainString function above
//-----end of custom functions-------
}
it's not as easy as it seems.
The location of a feature(e.g. marker) on a FusionTableLayer isn't available until you really click on it(this click can't be simulated).
You can't get the LatLng of the feature with the query, because you've stored addresses and not LatLng's inside the FusionTable.
Although the API knows the LatLng's of the addresses, there is no way to access them.
So the only thing you may do is:
Take the address of the row
use google.maps.Geocoder to geocode this address
open a custom InfoWindow(content populated by the properties of the row) at the LatLng returned by the geocoder.
I'd rather add a comment to Dr.Molle's answer, but thanks to Stack Overflow's point system, I have to add an answer even though I don't think this will be truly useful because I can't be very specific. I'm assuming that's because the goal is to get me to answer questions, not just talk about answers ;)
Dr.Molle was on the right track, but invoking the geocoder on every click is not only painfully slow, but every IP only gets so many geocoder requests per day. So:
Create a column that has a unique identifier. Add a listener to the marker so that when clicked, it will query your table for that ID. When the results come in, create an InfoWindow (sorry, no help here) with the returned data.
Here's a sample that does exactly what you're asking for:
https://developers.google.com/fusiontables/docs/samples/change_infowindow_content

Signal R Chat application on IIS not working

I am trying to build a SignalR application in Visual Studio 2012. My problem is that it works well under Visual Studio debug (using Visual Studio 2012 on Windows 7), but when I try to deploy the application on IIS 7.5 , the app does nothing more than displaying the index.html page.
my Index.html page is like :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link type="text/css" rel="stylesheet" href="Css/ChatStyle.css" />
<link rel="stylesheet" href="/Css/JQueryUI/themes/base/jquery.ui.all.css">
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="/Scripts/jquery-1.8.2.min.js"></script>
<script src="/Scripts/ui/jquery.ui.core.js"></script>
<script src="/Scripts/ui/jquery.ui.widget.js"></script>
<script src="/Scripts/ui/jquery.ui.mouse.js"></script>
<script src="/Scripts/ui/jquery.ui.draggable.js"></script>
<script src="/Scripts/ui/jquery.ui.resizable.js"></script>
<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
setScreen(false);
// Declare a proxy to reference the hub.
var chatHub = $.connection.chatHub;
registerClientMethods(chatHub);
// Start Hub
$.connection.hub.start().done(function () {
registerEvents(chatHub)
});
});
function setScreen(isLogin) {
if (!isLogin) {
$("#divChat").hide();
$("#divLogin").show();
}
else {
$("#divChat").show();
$("#divLogin").hide();
}
}
function registerEvents(chatHub) {
$("#btnStartChat").click(function () {
var name = $("#txtNickName").val();
if (name.length > 0) {
chatHub.server.connect(name);
}
else {
alert("Please enter name");
}
});
$('#btnSendMsg').click(function () {
var msg = $("#txtMessage").val();
if (msg.length > 0) {
var userName = $('#hdUserName').val();
chatHub.server.sendMessageToAll(userName, msg);
$("#txtMessage").val('');
}
});
$("#txtNickName").keypress(function (e) {
if (e.which == 13) {
$("#btnStartChat").click();
}
});
$("#txtMessage").keypress(function (e) {
if (e.which == 13) {
$('#btnSendMsg').click();
}
});
}
function registerClientMethods(chatHub) {
// Calls when user successfully logged in
chatHub.client.onConnected = function (id, userName, allUsers, messages) {
setScreen(true);
$('#hdId').val(id);
$('#hdUserName').val(userName);
$('#spanUser').html(userName);
// Add All Users
for (i = 0; i < allUsers.length; i++) {
AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName);
}
// Add Existing Messages
for (i = 0; i < messages.length; i++) {
AddMessage(messages[i].UserName, messages[i].Message);
}
}
// On New User Connected
chatHub.client.onNewUserConnected = function (id, name) {
AddUser(chatHub, id, name);
}
// On User Disconnected
chatHub.client.onUserDisconnected = function (id, userName) {
$('#' + id).remove();
var ctrId = 'private_' + id;
$('#' + ctrId).remove();
var disc = $('<div class="disconnect">"' + userName + '" logged off.</div>');
$(disc).hide();
$('#divusers').prepend(disc);
$(disc).fadeIn(200).delay(2000).fadeOut(200);
}
chatHub.client.messageReceived = function (userName, message) {
AddMessage(userName, message);
}
chatHub.client.sendPrivateMessage = function (windowId, fromUserName, message) {
var ctrId = 'private_' + windowId;
if ($('#' + ctrId).length == 0) {
createPrivateChatWindow(chatHub, windowId, ctrId, fromUserName);
}
$('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' + fromUserName + '</span>: ' + message + '</div>');
// set scrollbar
var height = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
$('#' + ctrId).find('#divMessage').scrollTop(height);
}
}
function AddUser(chatHub, id, name) {
var userId = $('#hdId').val();
var code = "";
if (userId == id) {
code = $('<div class="loginUser">' + name + "</div>");
}
else {
code = $('<a id="' + id + '" class="user" >' + name + '<a>');
$(code).dblclick(function () {
var id = $(this).attr('id');
if (userId != id)
OpenPrivateChatWindow(chatHub, id, name);
});
}
$("#divusers").append(code);
}
function AddMessage(userName, message) {
$('#divChatWindow').append('<div class="message"><span class="userName">' + userName + '</span>: ' + message + '</div>');
var height = $('#divChatWindow')[0].scrollHeight;
$('#divChatWindow').scrollTop(height);
}
function OpenPrivateChatWindow(chatHub, id, userName) {
var ctrId = 'private_' + id;
if ($('#' + ctrId).length > 0) return;
createPrivateChatWindow(chatHub, id, ctrId, userName);
}
function createPrivateChatWindow(chatHub, userId, ctrId, userName) {
var div = '<div id="' + ctrId + '" class="ui-widget-content draggable" rel="0">' +
'<div class="header">' +
'<div style="float:right;">' +
'<img id="imgDelete" style="cursor:pointer;" src="/Images/delete.png"/>' +
'</div>' +
'<span class="selText" rel="0">' + userName + '</span>' +
'</div>' +
'<div id="divMessage" class="messageArea">' +
'</div>' +
'<div class="buttonBar">' +
'<input id="txtPrivateMessage" class="msgText" type="text" />' +
'<input id="btnSendMessage" class="submitButton button" type="button" value="Send" />' +
'</div>' +
'</div>';
var $div = $(div);
// DELETE BUTTON IMAGE
$div.find('#imgDelete').click(function () {
$('#' + ctrId).remove();
});
// Send Button event
$div.find("#btnSendMessage").click(function () {
$textBox = $div.find("#txtPrivateMessage");
var msg = $textBox.val();
if (msg.length > 0) {
chatHub.server.sendPrivateMessage(userId, msg);
$textBox.val('');
}
});
// Text Box event
$div.find("#txtPrivateMessage").keypress(function (e) {
if (e.which == 13) {
$div.find("#btnSendMessage").click();
}
});
AddDivToContainer($div);
}
function AddDivToContainer($div) {
$('#divContainer').prepend($div);
$div.draggable({
handle: ".header",
stop: function () {
}
});
////$div.resizable({
//// stop: function () {
//// }
////});
}
</script>
</head>
<body>
<div id="header">
ABC BANK CHAT ROOM
</div>
<br />
<br />
<br />
<div id="divContainer">
<div id="divLogin" class="login">
<div>
Your Name:<br />
<input id="txtNickName" type="text" class="textBox" />
</div>
<div id="divButton">
<input id="btnStartChat" type="button" class="submitButton" value="Start Chat" />
</div>
</div>
<div id="divChat" class="chatRoom">
<div class="title">
Welcome to Chat Room [<span id='spanUser'></span>]
</div>
<div class="content">
<div id="divChatWindow" class="chatWindow">
</div>
<div id="divusers" class="users">
</div>
</div>
<div class="messageBar">
<input class="textbox" type="text" id="txtMessage" />
<input id="btnSendMsg" type="button" value="Send" class="submitButton" />
</div>
</div>
<input id="hdId" type="hidden" />
<input id="hdUserName" type="hidden" />
</div>
</body>
</html>
I have tried some of the methods listed here: Signalr/Hub not loading in IIS 7 but working correctly in Visual Studio, but none of them seem to work. Any help would be greatly appreciated. Thanks, chiranjit
I think you have to remove all the leading slashes "/"
(Ans maybe also upgrade to at least jquery-1.9.1)
<link type="text/css" rel="stylesheet" href="Css/ChatStyle.css" />
<link rel="stylesheet" href="Css/JQueryUI/themes/base/jquery.ui.all.css" />
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/ui/jquery.ui.core.js"></script>
<script src="Scripts/ui/jquery.ui.widget.js"></script>
<script src="Scripts/ui/jquery.ui.mouse.js"></script>
<script src="Scripts/ui/jquery.ui.draggable.js"></script>
<script src="Scripts/ui/jquery.ui.resizable.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>

Inserting table into Trirand JQGrid Edit Dialog that was creating with JQuery

I have a JQuery and AJAX function that creates a table with 2 list boxes and buttons to add/remove from one list box to another. I want to insert this table into the Edit Dialog box of the JQGrid. So that when the add or edit button is clicked the table displays and the user can add items and the corresponding cell is edited.
Java script and AJAX:
function create_listbox() {
var html = '<select id="ddlRoles" size="7" multiple></select>';
var selected = '<select id="ddlSelectedRoles" size="7" multiple></select>';
var table = '<table id="table1" border="3"></table>';
var tr = '<tr id="tr1"></tr>';
var td1 = '<td id="td1"></td>';
var td2 = '<td id="td2"></td>';
var td3 = '<td id="td3"></td>';
var addButton = '<button id="add" onclick="addRole()">Add Role</button><br>';
var removeButton = '<button onclick="removeRole()">Remove Role</button><br>';
$('#whatever').append(table);
$('#table1').append(tr);
$('#tr1').append(td1);
$('#tr1').append(td2);
$('#tr1').append(td3);
$('#td1').append(html);
$('#td2').append(addButton);
$('#td2').append(removeButton);
$('#td3').append(selected);
$.ajax({
url: "MyApplication.asmx/GetRoles",
data: "{ }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
// alert(data.d);
for (var i = 0; i < data.d.length; i++) {
$('#ddlRoles').append("<option value=\"" + data.d[i].RoleID + "\">" + data.d[i].RoleName + "</option>")
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ":" + errorThrown);
}
});
}
I know that I need an EditTypeCustomElement and EditTypeGetCustomValue but I am completely stumped as to how to accomplish this.
I've tried returning $table.get(0) with the create_listbox function which adds a table but it doesn't add the child elements. Any help?
You need a EditTypeCustomElement (below) JQuery and Ajax:
function create_listbox(value, options) {
var htmlRolesDdl = '';
var htmlRolesSelectedDdl = '';
$.ajax({
url: "MyApp.asmx/GetRoles",
data: "{ }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
var roles = new Array();
if (value.toString().match(',') == null) roles.push(value.toString());
else roles = value.toString().split(",")
for (var i = 0; i < data.d.length; i++) {
var isMatch = false;
for (var j = 0; j < roles.length; j++) {
if (data.d[i].RoleName == roles[j].toString()) {
htmlRolesSelectedDdl += "<option id=\"option" + data.d[i].RoleID + "\"" + " value=\"" + data.d[i].RoleID + "\">" + data.d[i].RoleName + "</option>";
//$selected.append("<option id=\"option" + data.d[i].RoleID + "\"" + " value=\"" + data.d[i].RoleID + "\">" + data.d[i].RoleName + "</option>")
isMatch = true;
}
}
if (!isMatch) {
htmlRolesDdl += "<option id=\"option" + data.d[i].RoleID + "\"" + " value=\"" + data.d[i].RoleID + "\">" + data.d[i].RoleName + "</option>"
//$listbox.append("<option id=\"option" + data.d[i].RoleID + "\"" + " value=\"" + data.d[i].RoleID + "\">" + data.d[i].RoleName + "</option>")
}
}
},
async: false,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ":" + errorThrown);
}
});
var html = '<table id="UserRole" border="0">';
html += '<tr>';
html += '<td>';
html += '<select id="ddlRoles" size="7" multiple width="155" style="width:155px;">';
html += htmlRolesDdl;
html += '</select>';
html += '</td>';
html += '<td>';
html += '<button onclick="addRole()" style="width:100px;"> Add >></button><br>';
html += '<button onclick="removeRole()" style="width:100px;"><< Remove</button><br>';
html += '</td>';
html += '<td>';
html += '<select class="ListBoxStyle" id="ddlSelectedRoles" size="7" width="155" multiple style="width:155px;">';
html += htmlRolesSelectedDdl;
html += '</select>';
html += '</td>';
html += '</tr>';
html += '<tr>';
html += '<td colspan="3" align="center" style="padding-top:5px;padding-bottom:10px;">';
html += '(Press and Hold "Ctrl" to select multiple roles)';
html += '</td>';
html += '</tr>';
html += '</table>';
return $(html);
}
and a EditTypeGetCustomValue (below) JQuery and AJAX:
function listbox_value(elem, type, stringvalue) {
if (type == 'get') {
var roles = new Array();
$("#ddlSelectedRoles > option").each(function () {
roles.push($(this).val().toString());
});
return roles.toString();
} else if (type == 'set') {
var roles = new Array();
$("#ddlSelectedRoles > option").each(function () {
roles.push($(this).val().toString());
});
$("#<%= hdnSelectedRoles.ClientID %>").val(roles);
return roles.toString();
}
}

Resources