My JavaScript:
var bossId = $('#BossId');
var date = $('#divDate');
var headDate = $('#HeadShipDate');
var select = '-- Select --';
bossId.change(function () {
if ( bossId.find(':selected').text() != select )
date.show();
else {
date.hide();
headDate.val('');
}
});
My View:
#Html.DropDownList(
"BossId", null, "-- Select --",
htmlAttributes: new { #class = "form-control" }
)
<div id="divDate" class="form-group" style="display:none">
#Html.EditorFor(
model => model.HeadShipDate,
new { htmlAttributes = new { #class = "form-control" } }
)
Per the title, this script works fine on Internet Explorer, but not in Chrome & Firefox. How can I Solve this?
Related
I have some problems with a multiple dropdownlist, while loading its showing a textbox and them it load the dropdownlist control:
this is the code in the View:
#Html.DropDownListFor(m => #m.SelectedInfractionsId,
new MultiSelectList(Model.InfractionList, "Value", "Text", #Model.SelectedInfractionsId),
new {
id = "SelectedInfractionsId",
#class = "form-control multiselect-dropdown",
multiple = "true",
data_placeholder = "Select Users"
})
This is the code in the Controller:
List<SelectListItem> Listofinfractions = new List<SelectListItem>();
var infractions = _context.InfractionsCategories.OrderByDescending(x => x.Id == 1);
foreach (var infraction in infractions)
{
Listofinfractions.Add(new SelectListItem()
{
Value = infraction.Id.ToString(),
Text = infraction.Name
});
}
Listofinfractions.Insert(0, new SelectListItem()
{
Text = "----Select----",
Value = string.Empty
});
Looks like the image down below:
DropDownListFor control while is loading
once is loaded the control looks like :
DropDownListFor control when is loaded
I am trying to give the background color to the textbox conditionally but not working when I assign the variable columnstyle to the textbox. Here is the html code
var columnstyle = "text-align:center;vertical-align:central;background-color:#FFBF00";
if (Model.attendanceLogList[i].IsProtected)
{
isdisabled = true;
styleset = "background-color:#90EE90";
columnstyle = "text-align:center;vertical-align:central;background-color:#90EE90";
}
<td>
#Html.TextBoxFor(m => m.attendanceLogList[i].NormalHrs, new { #class = "form-control input-sm NormalHrsl", #style= "#(columnstyle)", #Value = Model.attendanceLogList[i].NormalHrs, onchange = "CalculateTotal()" })
<td>
You can try something like this
var columnstyle = Model.attendanceLogList[i].IsProtected == false ? "text-align:center;vertical-align:central;background-color:#FFBF00" : "text-align:center;vertical-align:central;background-color:#90EE90";
...
I cannot figure out why this is not working, so please help me figure it out.
Display.js :
render(){
const notesList = this.props.notesList;
const displayNotes = notesList.map( (note,note_id) =>
<div className="display">
<p id={'note-' + note_id}>{note}</p>
<button type="button" className="edit-button" onClick={()=>this.props.edit(note_id)}>Edit</button>
<button type="button" className="delete-button" onClick={()=>this.props.delete(note_id)}>Delete</button>
</div> );
return <div>{displayNotes}</div>;
}
}
App.js:
handleEdit = (note_id) => {
const id = 'note-' + note_id;
document.getElementById(id).contentEditable = 'true';
}
handleDelete = (note_id) => {
const id = 'note-' + note_id;
document.getElementById(id).display = 'none';
}
When you want to change an element css property, you need to access the style object first.
This is how you would get it:
handleDelete = (note_id) => {
const id = 'note-' + note_id;
document.getElementById(id).style.display = 'none';
}
I have a form which would collect location information from the user. I'm using Google places api to autocomplete the location information. It works great. Everything got filled out nicely however there are some places (e.g. my workplace which is a building), Google does not return a postal code for it.
I followed this example from Google address autocomplete. It also doesn't return postal code for my workplace. So I'm not entire sure what I did wrong.
Below is my code:
HTML
<div id="location-autocomplete" style="display: none;">
<div class="half-formfield">
#Html.LabelFor(x => x.Address)
#Html.TextBoxFor(x => x.Address, new { #class = "two-third-field", id = "street_number", required = "required" })
</div>
<div>
#Html.LabelFor(x => x.UnitNumber, new { value = "Unit Number" })
#Html.TextBoxFor(x => x.UnitNumber, new { #class = "one-third-field" })
</div>
<div class="half-formfield">
#Html.LabelFor(x => x.City)
#Html.TextBoxFor(x => x.City, new { #class = "half-field", required = "required", id = "locality" })
</div>
<div>
#Html.LabelFor(x => x.ProvinceOrState)
#Html.TextBoxFor(x => x.ProvinceOrState, new { #class = "half-field", required = "required", id = "administrative_area_level_1" })
</div>
<div class="half-formfield">
#Html.LabelFor(x => x.ZipOrPostalCode)
#Html.TextBoxFor(x => x.ZipOrPostalCode, new { #class = "half-field", required = "required", id = "postal_code" })
</div>
<div>
#Html.LabelFor(x => x.Country)
#Html.TextBoxFor(x => x.Country, new { #class = "half-field", required = "required", id = "country" })
</div>
<input type="button" value="Clear Address" onclick="clearAddress()" id="clear-btn" class="service-form-btn"/>
JS
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initialize() {
// Create the autocomplete object, restricting the search
// to geographical location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {HTMLInputElement} */(document.getElementById('autocomplete')),
{ types: ['geocode'] });
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function () {
fillInAddress();
showAddressComponent();
setTimeout(hideAddressSearch, 800);
});
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
if (component != "route") {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
console.log(val);
if (addressType != "route") document.getElementById(addressType).value = val;
else if (addressType == "route") document.getElementById("street_number").value = document.getElementById("street_number").value + " " + val;
}
}
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
autocomplete.setBounds(new google.maps.LatLngBounds(geolocation,
geolocation));
});
}
}
Screenshot
I wonder if this is a bug or simply Google doesn't know the postal code of the building. In that case, is there simply any work around this?
Thanks in advance.
There is a postal code for this address, but only a part (I guess it's called FSA-code).
The function didn't recognize this part, because for this address the returned types-array is:
["postal_code_prefix", "postal_code"]
...but the function only checks the first item of the types-array.
possible fix:
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressTypes = place.address_components[i].types,addressType,val;
for(var j=0;j<addressTypes.length;++j){
addressType=addressTypes[j];
if (componentForm[addressType]) {
val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
break;
}
}
}
}
Hope this will explore more ideas.
function initDefaultAutoCompleteFunction() {
var objAddress = document.getElementsByClassName('autocomplete-address');
$(objAddress).each(function (index, address) {
if (typeof (address) != 'undefined' && address != null) {
let options = {
types: ['address'],
Fields: ['address_component', 'formatted_address'],
componentRestrictions: { country: ['us', 'ca'] }
};
let autocomplete = new google.maps.places.Autocomplete(address, options);
autocomplete.addListener('place_changed', function () {
debugger;
let place = autocomplete.getPlace();
if (place) {
let zipOrPostalCode = null; // or set empty etc.
$.each(place.address_components, function (index, value) {
let addressType = value.types[0];
if (addressType == 'street_number') {
// value.short_name; //this is your street number
}
if (addressType == 'route') {
// value.short_name; //this is your route
}
if (addressType == 'postal_code' || addressType == "postal_code_prefix") {
// value.short_name; //this is your postal_code
}
});
}
});
}
});
}
var location = place.geometry.location;
var lat = location.lat();
var lng = location.lng();
var latlng = {lat: lat, lng: lng};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results[0].address_components.length; i++) {
var types = results[0].address_components[i].types;
for (var typeIdx = 0; typeIdx < types.length; typeIdx++) {
if (types[typeIdx] == 'postal_code') {
//console.log(results[0].address_components[i].long_name);
var pincode = results[0].address_components[i].short_name;
alert('pin'+pincode);
}
}
}
$('#pac-input2').val(results[0].formatted_address);
infowindow.setContent(results[0].formatted_address);
//infowindow.open(map, marker);
}
}
});
I want to upload a Bing map on my project(MVC3 and Razor engine). I have Create and Edit Views to deal with dinner as well as display bing map. The problem is that only Edit view can display the map while Create view cannot. But both of the views render the same particial view called "DinnerForm". I am wondering why cause this problem.
The Create view
#model NerdDinner.Models.DinnerFormViewModel
#{
ViewBag.Title = "Create";
}
<h2>Host a dinner</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#{Html.RenderPartial("DinnerForm");}
The Edite view
#model NerdDinner.Models.DinnerFormViewModel
ViewBag.Title = #Html.Encode(Model.Dinner.Title);
<h2>Edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#{Html.RenderPartial("DinnerForm");}
The DinnerForm View
#model NerdDinner.Models.DinnerFormViewModel
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.Dinner.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Dinner.Title)
#Html.ValidationMessageFor(model => model.Dinner.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Dinner.Latitude)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Dinner.Latitude)
#Html.ValidationMessageFor(model => model.Dinner.Latitude)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Dinner.Longitude)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Dinner.Longitude)
#Html.ValidationMessageFor(model => model.Dinner.Longitude)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Dinner.EventDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Dinner.EventDate)
#Html.ValidationMessageFor(model => model.Dinner.EventDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Dinner.ContactPhone)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Dinner.ContactPhone)
#Html.ValidationMessageFor(model => model.Dinner.ContactPhone)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Dinner.Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Dinner.Address)
#Html.ValidationMessageFor(model => model.Dinner.Address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Dinner.Country)
</div>
<div class="editor-field">
#Html.DropDownList("Country", #Model.Countries)
#Html.ValidationMessageFor(model => model.Countries)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Dinner.HostedBy)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Dinner.HostedBy)
#Html.ValidationMessageFor(model => model.Dinner.HostedBy)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Dinner.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Dinner.Description)
#Html.ValidationMessageFor(model => model.Dinner.Description)
</div>
<p>
<input type="submit" value="Save" />
</p>
<div id="mapDiv">
#{Html.RenderPartial("Map", Model.Dinner);}
</div>
</fieldset>
<script type="text/javascript">
$(document).ready(function () {
$("#Address").blur(function (evt) {
$("#Latitude").val("");
$("#Longitude").val("");
var address = jQuery.trim($("#Address").val());
if (address.length < 1)
return;
FindAddressOnMap(address);
});
});
</script>
}
The Map view is fine because it appears on the page of Edit.
I have a js file called NerdDinner to reach the map function. FindAddressOnMap() function is defined there.
function NerdDinner() { }
NerdDinner.MapDivId = 'theMap';
NerdDinner._map = null;
NerdDinner._points = [];
NerdDinner._shapes = [];
NerdDinner.LoadMap = function (latitude, longitude, onMapLoaded) {
NerdDinner._map = new VEMap(NerdDinner.MapDivId);
var options = new VEMapOptions();
options.EnableBirdseye = false
// Makes the control bar less obtrusize.
this._map.SetDashboardSize(VEDashboardSize.Small);
if (onMapLoaded != null)
NerdDinner._map.onLoadMap = onMapLoaded;
if (latitude != null && longitude != null) {
var center = new VELatLong(latitude, longitude);
}
NerdDinner._map.LoadMap(center, null, null, null, null, null, null, options);
}
NerdDinner.ClearMap = function () {
NerdDinner._map.Clear();
NerdDinner._points = [];
NerdDinner._shapes = [];
}
NerdDinner.LoadPin = function (LL, name, description) {
var shape = new VEShape(VEShapeType.Pushpin, LL);
//Make a nice Pushpin shape with a title and description
shape.SetTitle("<span class=\"pinTitle\"> " + escape(name) + "</span>");
if (description !== undefined) {
shape.SetDescription("<p class=\"pinDetails\">" + escape(description) + "</p>");
}
NerdDinner._map.AddShape(shape);
NerdDinner._points.push(LL);
NerdDinner._shapes.push(shape);
}
NerdDinner.FindAddressOnMap = function (where) {
var numberOfResults = 1;
var setBestMapView = true;
var showResults = true;
var defaultDisambiguation = true;
NerdDinner._map.Find("", where, null, null, null,
numberOfResults, showResults, true, defaultDisambiguation,
setBestMapView, NerdDinner._callbackForLocation);
}
NerdDinner._callbackForLocation = function (layer, resultsArray, places, hasMore, VEErrorMessage) {
NerdDinner.ClearMap();
if (places == null) {
NerdDinner._map.ShowMessage(VEErrorMessage);
return;
}
//Make a pushpin for each place we find
$.each(places, function (i, item) {
var description = "";
if (item.Description !== undefined) {
description = item.Description;
}
var LL = new VELatLong(item.LatLong.Latitude,
item.LatLong.Longitude);
NerdDinner.LoadPin(LL, item.Name, description);
});
//Make sure all pushpins are visible
if (NerdDinner._points.length > 1) {
NerdDinner._map.SetMapView(NerdDinner._points);
}
//If we've found exactly one place, that's our address.
//lat/long precision was getting lost here with toLocaleString, changed to toString
if (NerdDinner._points.length === 1) {
$("#Latitude").val(NerdDinner._points[0].Latitude.toString());
$("#Longitude").val(NerdDinner._points[0].Longitude.toString());
}
}
NerdDinner.FindDinnersGivenLocation = function (where) {
NerdDinner._map.Find("", where, null, null, null, null, null, false,
null, null, NerdDinner._callbackUpdateMapDinners);
}
NerdDinner.FindMostPopularDinners = function (limit) {
$.post("/Search/GetMostPopularDinners", { "limit": limit }, NerdDinner._renderDinners, "json");
}
NerdDinner._callbackUpdateMapDinners = function (layer, resultsArray, places, hasMore, VEErrorMessage) {
var center = NerdDinner._map.GetCenter();
$.post("/Search/SearchByLocation",
{ latitude: center.Latitude, longitude: center.Longitude },
NerdDinner._renderDinners,
"json");
}
NerdDinner._renderDinners = function (dinners) {
$("#dinnerList").empty();
NerdDinner.ClearMap();
$.each(dinners, function (i, dinner) {
var LL = new VELatLong(dinner.Latitude, dinner.Longitude, 0, null);
// Add Pin to Map
NerdDinner.LoadPin(LL, _getDinnerLinkHTML(dinner), _getDinnerDescriptionHTML(dinner));
//Add a dinner to the <ul> dinnerList on the right
$('#dinnerList').append($('<li/>')
.attr("class", "dinnerItem")
.append(_getDinnerLinkHTML(dinner))
.append($('<br/>'))
.append(_getDinnerDate(dinner, "mmm d"))
.append(" with " + _getRSVPMessage(dinner.RSVPCount)));
});
// Adjust zoom to display all the pins we just added.
if (NerdDinner._points.length > 1) {
NerdDinner._map.SetMapView(NerdDinner._points);
}
// Display the event's pin-bubble on hover.
$(".dinnerItem").each(function (i, dinner) {
$(dinner).hover(
function () { NerdDinner._map.ShowInfoBox(NerdDinner._shapes[i]); },
function () { NerdDinner._map.HideInfoBox(NerdDinner._shapes[i]); }
);
});
function _getDinnerDate(dinner, formatStr) {
return '<strong>' + _dateDeserialize(dinner.EventDate).format(formatStr) + '</strong>';
}
function _getDinnerLinkHTML(dinner) {
return '' + dinner.Title + '';
}
function _getDinnerDescriptionHTML(dinner) {
return '<p>' + _getDinnerDate(dinner, "mmmm d, yyyy") + '</p><p>' + dinner.Description + '</p>' + _getRSVPMessage(dinner.RSVPCount);
}
function _dateDeserialize(dateStr) {
return eval('new' + dateStr.replace(/\//g, ' '));
}
function _getRSVPMessage(RSVPCount) {
var rsvpMessage = "" + RSVPCount + " RSVP";
if (RSVPCount > 1)
rsvpMessage += "s";
return rsvpMessage;
}
}
NerdDinner.dragShape = null;
NerdDinner.dragPixel = null;
NerdDinner.EnableMapMouseClickCallback = function () {
NerdDinner._map.AttachEvent("onmousedown", NerdDinner.onMouseDown);
NerdDinner._map.AttachEvent("onmouseup", NerdDinner.onMouseUp);
NerdDinner._map.AttachEvent("onmousemove", NerdDinner.onMouseMove);
}
NerdDinner.onMouseDown = function (e) {
if (e.elementID != null) {
NerdDinner.dragShape = NerdDinner._map.GetShapeByID(e.elementID);
return true;
}
}
NerdDinner.onMouseUp = function (e) {
if (NerdDinner.dragShape != null) {
var x = e.mapX;
var y = e.mapY;
NerdDinner.dragPixel = new VEPixel(x, y);
var LatLong = NerdDinner._map.PixelToLatLong(NerdDinner.dragPixel);
$("#Latitude").val(LatLong.Latitude.toString());
$("#Longitude").val(LatLong.Longitude.toString());
NerdDinner.dragShape = null;
NerdDinner._map.FindLocations(LatLong, NerdDinner.getLocationResults);
}
}
NerdDinner.onMouseMove = function (e) {
if (NerdDinner.dragShape != null) {
var x = e.mapX;
var y = e.mapY;
NerdDinner.dragPixel = new VEPixel(x, y);
var LatLong = NerdDinner._map.PixelToLatLong(NerdDinner.dragPixel);
NerdDinner.dragShape.SetPoints(LatLong);
return true;
}
}
NerdDinner.getLocationResults = function (locations) {
if (locations) {
var currentAddress = $("#Dinner_Address").val();
if (locations[0].Name != currentAddress) {
var answer = confirm("Bing Maps returned the address '" + locations[0].Name + "' for the pin location. Click 'OK' to use this address for the event, or 'Cancel' to use the current address of '" + currentAddress + "'");
if (answer) {
$("#Dinner_Address").val(locations[0].Name);
}
}
}
}