Clear jQuery Chosen select options on change event - jquery-chosen

I'm having some difficulty clearing previous jQuery Chosen select options on a change function from another select.
I tried
$(".chosen-workOrderFormModal_machineSelection").val('').trigger("chosen:updated"); but that did not work.
I am using Chosen v1.8.5
$('.chosen-workOrderFormModal_systemSelection').on('change', function(evt, params) {
systemCode=$('#workOrderFormModal_systemSelection').chosen().val();
$('#workOrderFormModal_systemSelection_chosen').css('color', '#495057');
$('#workOrderFormModal_systemSelection_chosen').css('border', 'none');
machineCodeSelect = '';
//*Start -getMachineSelectionData.php AJAX
$.ajax
({
type: "POST",
url: "getMachineSelectionData.php",
data: { locationCode: userLocationCode,
systemCode: systemCode,},
dataType: 'json',
cache: false,
success: function(data) {
$.each(data, function(i, machine){
machineCodeSelect += '<option value="' + machine.machineCode + '">' + machine.machineDescription + '</option>';
});
$('#workOrderFormModal_machineSelection').append('Select Machine...');
$('#workOrderFormModal_machineSelection').append(machineCodeSelect);
$(".chosen-workOrderFormModal_machineSelection").val('').trigger("chosen:updated");
$('.chosen-workOrderFormModal_machineSelection').chosen({
disable_search_threshold: 10,
no_results_text: 'Machine Not Found',
width:'271px',
});
}
}); //* END -getMachineSelectionData.php AJAX
$('#workOrderFormModal_machineSelection').attr('readonly', false);
$('#workOrderFormModal_machineSelection').removeAttr('disabled');
$(".chosen-workOrderFormModal_machineSelection").val('').trigger("chosen:updated");
$("#workOrderFormModal_machineSelection_chosen > a > span" ).text('Select Machine...')
});

Related

How can I change the behaviour of bindPopup

Good day everybody.
I bought a nice template and leaftlet is used to show maker.
Here is the demo . Actually when you clik on a marker, it open a widnows with a picture and some température value.
I would like to have all of the windows open. Of course, I am going to modify the html, to remove the picture and some information as GPS, and only keep the temperatue value. The goal is to be able to immediately see the temperature boxes below the markers. Optionaly, when I click on the marker it redirect to another page, same you click on the picture.
My first problem, I can not find the jacasvript script which work with the link of marker. The idea would be to cancel the effect of the click, or as I wrote, after we click it open the graph page instead of opening the windows.
My first question: how can I find a do to change the action of the click, on the marker
My second question (may be it be cancel the 1st question :) ), how can I change the behaviour of the bindpopup? Is there way "to tell" to the bindpopup, stay always open?
My thirst question: Or can we add one or two additional nice boxes, which show always the temperature below the marker, and keep the bindPopup, as it is? That would be nice as well
Here is the code of the map line 215
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// OpenStreetMap - Homepage
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function createHomepageOSM(_latitude,_longitude,_nbField){
setMapHeight();
if( document.getElementById('map') != null ){
var map = L.map('map', {
center: [_latitude,_longitude],
zoom: 18,
scrollWheelZoom: false
});
//L.tileLayer('http://openmapsurfer.uni-hd.de/tiles/roadsg/x={x}&y={y}&z={z}', {
L.tileLayer('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
//subdomains: '0123',
maxZoom: 20,
attribution: 'OpenStreetMap contributors, CC-BY-SA'
}).addTo(map);
var markers = L.markerClusterGroup({
showCoverageOnHover: false
});
function locateUser() {
$('#map').addClass('fade-map');
map.locate({setView : true})
}
$('.geo-location').on("click", function() {
locateUser();
});
$.ajax({
type: "POST",
url: "sql/get_map.mysql.php",
//data:'node=node1',
//data:{node_id:"firstnode", node2:"secondnode", node3:"thirdnode", from:"from", to:"to"}, // Send parameter to get.php
success: result,
error: error,
dataType: "json"
});
function error(data)
{
$('body').addClass('loaded');
alert("Error getting datas from DB");
console.log("Error getting datas from DB");
console.log(data);
}
function result(data){
console.info("data:",data);
var allMarkers=[];
var nhtml = '<img src="assets/img/property-types/vineyard.png">';
for (var i = 0; i < data.properties.length; i++) {
allMarkers.push(L.latLng(data.properties[i]['la'], data.properties[i]['lo']));
//data.properties[i]['b2'] = 0;
if((data.properties[i]['b1']>=data.properties[i]['se'] && data.properties[i]['b1'] < data.properties[i]['se']+1) ||
(data.properties[i]['b2']>=data.properties[i]['se'] && data.properties[i]['b2'] < data.properties[i]['se']+1) ||
(data.properties[i]['b3']>=data.properties[i]['se'] && data.properties[i]['b3'] < data.properties[i]['se']+1) ||
(data.properties[i]['b4']>=data.properties[i]['se'] && data.properties[i]['b4'] < data.properties[i]['se']+1)
)
{
nhtml = '<img src="assets/img/property-types/vineyard-orange.png">';
}
if(((data.properties[i]['b1'] < data.properties[i]['se']) && data.properties[i]['b1'] != null) ||
((data.properties[i]['b2'] < data.properties[i]['se']) && data.properties[i]['b2'] != null) ||
((data.properties[i]['b3'] < data.properties[i]['se']) && data.properties[i]['b3'] != null) ||
((data.properties[i]['b4'] < data.properties[i]['se']) && data.properties[i]['b4'] != null)
)
{
nhtml = '<img src="assets/img/property-types/vineyard-red.png">';
}
else{
nhtml = '<img src="assets/img/property-types/vineyard.png">';
}
var _icon = L.divIcon({
//html: '<img src="' + locations[i][7] +'">',
html: nhtml,
iconSize: [40, 48],
iconAnchor: [20, 48],
popupAnchor: [0, -48]
});
var title = data.properties[i]['station'];
var marker = L.marker(new L.LatLng(data.properties[i]['la'],data.properties[i]['lo']), {
title: title,
icon: _icon
});
var str ='';
if(data.properties[i]['b1'] != null)
{
str = str.concat('<div class="tag price"> ' + data.properties[i]['b1'] + '°C</div>');
}
if(data.properties[i]['b2'] != null)
{
str = str.concat('<div class="tag price"> ' + data.properties[i]['b2'] + '°C</div>');
}
if(data.properties[i]['b3'] != null)
{
str = str.concat('<div class="tag price"> ' + data.properties[i]['b3'] + '°C</div>');
}
if(data.properties[i]['b4'] != null)
{
str = str.concat('<div class="tag price"> ' + data.properties[i]['b4'] + '°C</div>');
}
marker.bindPopup(
'<div class="property">' +
'<a data-field=' + data.properties[i]['id_field'] +'" data-station=' + data.properties[i]['id_station'] +'" href="charts.php?field='+ data.properties[i]['id_field'] +'">' +
'<div class="property-image">' +
'<img src="img/stations/station-' + data.properties[i]['id_station'] + '.jpg">' +
'</div>' +
'<div class="overlay">' +
'<div class="info">' +
'<h3>' + data.properties[i]['station'] + '</h3>' +
'<figure>' + data.properties[i]['da'] + '</figure>' +
'<figure>' + data.properties[i]['la'] + ' ' + data.properties[i]['lo'] +'</figure>' +
str +
'<div class="tag"> ' + data.properties[i]['se'] + '°C</div>' +
'</div>' +
'</div>' +
'</a>' +
'</div>'
);
markers.addLayer(marker);
}
if(_nbField>1){
bounds = L.latLngBounds(allMarkers);
map.fitBounds(bounds,{ padding: [10, 10] });
}
map.addLayer(markers);
map.on('locationfound', onLocationFound);
function onLocationFound(){
$('#map').removeClass('fade-map');
}
$('body').addClass('loaded');
setTimeout(function() {
$('body').removeClass('has-fullscreen-map');
}, 1000);
$('#map').removeClass('fade-map');
}
}
}
My last question, with firefox, id possible "to track" the javascript action?
Feel free to aks complementary question to better understand and help, if I missed to provide information.
Many thanks
You can add a click event to the marker:
marker.on('click',(e)=>{
console.log(e);
});
Show all Popups:
You need to set the options autoClose and closeOnClick to false:
marker.bindPopup(content,{autoClose: false, closeOnClick: false});
You can use Tooltips:
marker.bindTooltip('5.3°C', {direction: 'bottom', permanent: true});
I don't know exactly what do you mean, but it sounds like debugging. Use the developer console with the Debugger.
Thanks for your reply and help
Unfortunately 2. does not work. There is no differences. I added closeButton:true, and that works, but it's not what I need.
marker.bindPopup(
'<div class="property">' +
'<a data-field=' + data.properties[i]['id_field'] +'" data-station=' + data.properties[i]['id_station'] +'" href="charts.php?field='+ data.properties[i]['id_field'] +'#st-'+ data.properties[i]['id_station'] +'">' +
'<div class="property-image">' +
'<img src="img/stations/station-' + data.properties[i]['id_station'] + '.jpg">' +
'</div>' +
'<div class="overlay">' +
'<div class="info">' +
'<h3>' + data.properties[i]['station'] + '</h3>' +
'<figure>' + data.properties[i]['da'] + '</figure>' +
'<figure>' + data.properties[i]['la'] + ' ' + data.properties[i]['lo'] +'</figure>' +
str +
'<div class="tag"> ' + data.properties[i]['se'] + '°C</div>' +
'</div>' +
'</div>' +
'</a>' +
'</div>',{autoClose: true, closeOnClick: false, closeButton: true}
);
I also tried the interesting option with tooltip. Bellow the above code I added
marker.bindTooltip('5.3°C', {direction: 'bottom', permanent: true});
But that print an error message
marker.bindTooltip is not a function
Is there additionally library I have to add for tooltop, or is inlcuded into leafet.
(bindTootip would be great and enough for my need)
Thanks for helping
Cheers

devops using Ajax access query data WIQL

I am trying to access azure-devops data using Ajax. And below is my working code.
$.ajax({
url: 'https://dev.azure.com/ORG/products/_apis/wit/workitems/2065741?$expand=all&api-version=5.1',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + 'XXXX')
}
}).done(function( results ) {
});
After I need to access data using WQIL but it is giving an unexpected token error. I want to access WorkItem, and user activity. Can you please help with this?
$.ajax({
url: 'https://dev.azure.com/ORG/products/_apis/wit/wiql?api-version=5.1 ',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + 'XXXX')
},
JSON.Stringfy("QUERY":"SELECT [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.Tags] FROM workitemLinks WHERE " +
"( [Source].[System.TeamProject] = #project AND [Source].[System.WorkItemType] = 'User Story' ) AND ( [System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward' ) "+
" AND ( [Target].[System.TeamProject] = #project AND [Target].[System.WorkItemType] = 'Task' ) ORDER BY [System.Id] MODE (MustContain)")
}).done(function( results ) {
x=results
});
The previous script you are using is the method used to execute API, but not suitable for execute WIQL script. That's why you are facing that error.
Executing WIQL in Ajax is actually a request process: Send the wiql statement to the server you want to access, request to execute the query statement(Wiql), and return the execution result. Therefore, this is a process of requesting the execution of the Post command. But in your script, it did not tell the server what instructions need to be executed.
Here is the simple sample can for you refer to use WIQL with Ajax:
<script type="text/javascript">
$(document).ready(function () {
$("#SelectWIT").on("click", function () {
var d = { "query": " Select [System.Id] from WorkItems Where [System.WorkItemType] = 'Bug' "};
$.ajax({
type: 'POST',
url: 'https://dev.azure.com/{org name}/{project name}/_apis/wit/wiql?api-version=1.0',
contentType: 'application/json',
data: JSON.stringify(d),
cache: false,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("" + ":" + "{PAT token}"));
},
}).done(function (data) {
var items = [];
$.each(data.workItems, function (key, val) {
items.push("<li> <a href='" + val.url + "'>" + val.id + "</a></li>");
});
$("<ul/>", {
html: items.join("")
}).appendTo("body");
}).error(function (e) {
var s = "error error error";
});
})
});
</script>
The logic of my script is to request to run a API with a WIQL statement as request body, send this request to the project I want to access. Then display the response data with js syntax into the body of the page. This is the output:
Since I am not sure what is your next operation. You can replace the Wiql statement and the Url with yours in this script. Then change the corresponding done function to achieve what you want.
Somehow WQIL is giving error 400 it looks like a permission issue.
So I Solved it in a different way. Instead of the query, there is another method which gives me all the details of the workitem I just need to pass workitem Id's in that.
var d ={
"ids": [
20813,21677
],
"fields": ["System.Id","System.WorkItemType","System.Title","System.AssignedTo","System.State","System.Tags"]
};
$.ajax({
type: 'POST',
url: 'https://dev.azure.com/ORG/products/_apis/wit/workitemsbatch?api-version=5.1',
contentType: 'application/json',
data: JSON.stringify(d),
cache: false,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("" + ":" + "XXXXX"));
},
}).done(function (data) {
x=data
});

Adding Attachment to Work Item through custom Widget Using ajax call

How to Add Attachment to Work Item through custom Widget using ajax call. I read about API call but did not understand how it would be done, through ajax I am able to create the work item using my widget, but unable to add attachment to it. Find my ajax code below:
$("#btnAttachment").click(function () {
var restURL = "https://dev.azure.com/organizationName/{" + VSS.getWebContext().project.id + "}/_apis/wit/attachments?fileName='C:\Users\Administrator\Downloads\picturemessage_4hm34b3k.kot.png'&api-version=5.0";
var myPatToken = "xyz";
$.ajax({
contentType: 'application/octet-stream',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + myPatToken)
},
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Failure");
console.log(JSON.stringify(data.responseText));
},
type: 'POST',
url: restURL
});
});

FullCalendar IETF date in Firefox

I have been working with the FullCalendar and came across some problems in Firefox. I have selectable on and the start date comes over in IETF format. For some reason, IE8 is able to post this (and autoconvert it to a timestamp), but Firefox won't.
It leaves it in IETF format, and PHP's date() function doesn't work with it. I used the fullCalendar.formatDate() function as a work-around, but this doesn't seem like the best solution to me.
Is there another way to make this work?
<script type='text/javascript'>
$(document).ready(function () {
var date = new Date();
var calendar = $("#calendar").fullCalendar({
theme: true,
title: "Employee Calendar",
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
buttonIcons: {prev: 'circle-triangle-w', next: 'circle-triangle-e'},
editable: true,
droppable: true,
events: '<?php echo matry::base_to('utilities/calendar_events');?>',
eventClick: function (event) {
$.ajax({
url: '<?php echo matry::base_to('utilities/calendar_tools');?>',
type: 'POST',
data: {id: event.id, job: 'getEvent'},
success: function(data){
$("#event_box").fadeIn(500);
$("#event_info").html(data);
}
});
},
selectable: true,
selectHelper: true,
select: function (start, end, allDay){
var title = prompt('Event Title');
start = $.fullCalendar.formatDate(start, 'yyyy-MM-dd HH:mm:ss');
end = $.fullCalendar.formatDate(end, 'yyyy-MM-dd HH:mm:ss');
if (title)
{
$.ajax({
type: 'POST',
url: '<?php echo matry::base_to('utilities/calendar_tools');?>',
data: {title: title, start: start, end: end, allDay: allDay, job: 'createEvent'},
success: function(data) {
calendar.fullCalendar('refetchEvents' );
$("#alerts").html(data);
}//close success function
})//close ajax
}
else
calendar.fullCalendar('unselect');
}//close select function
}); //close fullcalendar function
$("#calendar_controls").accordion({
collapsible: true,
clearStyle:true,
active: false,
autoHeight: true
});//close calendar controls
$(document).on('submit', '#event_form', function (event){
event.preventDefault();
$.ajax({
url: '<?php echo matry::base_to('utilities/calendar_tools');?>',
type: 'POST',
data: $('#event_form').serialize(),
success: function(data){
$("#event_box").fadeOut('2000');
$("#alerts").html(data).focus();
}
})
});//close on function
$(document).on('click', '#delete', function() {
var con = confirm('Do you want to delete this Event?');
if (con)
{
var id = $("#event_form input[name= 'id']").val();
$.ajax({
url: '<?php echo matry::base_to('utilities/calendar_tools');?>',
data: {id: id, job: 'deleteEvent'},
type: 'POST',
success: function(data){
$("#alerts").html(data).focus()
calendar.fullCalendar('refetchEvents');
$("#event_box").fadeOut(1000);
;}
});
}
})
}); //close document.ready function
</script>
IETF date format doesn't get passed correctly by firefox, but the date can be altered with the $.fullCalendar.formatDate() function that appears to work well. IF this is added wherever dates are passed, the format can be changed.

how to read jquery.ajax() data in mvc 2 controller

I'm using mvc2 and jqueries to post the data from view to controller.
This is my view
$('#btnSaveAcademicInfo').click(function() {
var recordsToSave = [];
var curRecord = null;
$.each($("#academics tr"), function(i, v) {
curRecord = {};
curRecord.Institution = $(this).find('.tdName').text();
curRecord.PassoutYear = $(this).find('.tdPassOutYear').text();
curRecord.Percentage = $(this).find('.tdPercentage').text();
curRecord.Specialization = $(this).find('.tdspecialization').text();
recordsToSave.push(curRecord);
});
$.ajax({
type: 'POST',
url: '/EmployeeMaster/SaveAcademicInfo',
data: recordsToSave,
success: function(result) { success(result); },
datatype: "json"
});
});
and my controller is
[HttpPost]
public ActionResult SaveAcademicInfo(List<AcademicModel> data)
{
//Here data is always null
return View("GetPersonalDataById");
}
Here im not getting the data to controller. But when i use, data: JSON.stringify(recordsToSave), I'm able to see the data in firebug.
How do i read the data in controller.
Please help.
JSON.stringify converts a javascript object into a JSON string. If you want to send JSON requests in ASP.NET MVC 2 you need a JSON value provider as this is not built-in. See this blog post for more details. In ASP.NET MVC 3 this works out of the box thanks to the built-in JsonValueProviderFactory.
Also if you want to send a JSON request you need to specify the content type as well:
$.ajax({
type: 'POST',
url: '/EmployeeMaster/SaveAcademicInfo',
data: JSON.stringify(recordsToSave),
contentType: 'application/json',
dataType: 'json', // <!-- notice the capital T
success: function(result) {
success(result);
},
});
and if you don't want to use JSON you will need to format the request in a way that the default model binder can understand. Try like this:
var recordsToSave = [];
$.each($('#academics tr'), function (index, value) {
recordsToSave.push({
'name': '[' + index + '].Institution',
'value': $(this).find('.tdName').text()
});
recordsToSave.push({
'name': '[' + index + '].PassoutYear',
'value': $(this).find('.tdPassOutYear').text()
});
recordsToSave.push({
'name': '[' + index + '].Percentage',
'value': $(this).find('.tdPercentage').text()
});
recordsToSave.push({
'name': '[' + index + '].Specialization',
'value': $(this).find('.tdspecialization').text()
});
});
$.ajax({
type: 'POST',
url: '/EmployeeMaster/SaveAcademicInfo',
data: recordsToSave,
success: function (result) {
success(result);
}
});