Sharepoint Dropdown Choices Filter - filter

I have a dropdown on a form. I have it set as unique entry for the list. That works fine, when a user selects an option that was already selected in a previous list entry they are notified when the save or submit the form. However I would rather remove the choice from the dropdown list if that selection was already made and exists in the list, that way they can't select something already selected.
Thanks for your help

We can use REST API to get all the exists dropdown items and then remove the downdown options in the new/edit form page. The following code for your reference.
<script src="//code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
removeDuplicateDropDowm("FilterDropDown");
});
function removeDuplicateDropDowm(fieldName){
var listId = _spPageContextInfo.pageListId.replace("{","").replace("}","");
var fieldHTML="";
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'"+listId+"')/items?$select="+fieldName;
$.ajax({
url: url,
method: "GET",
async:false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items = data.d.results;
$("select[title='"+fieldName+"'] option").each(function(){
for(var i=0;i<items.length;i++){
if(items[i][fieldName]==$(this).val()){
$(this).remove();
}
}
});
},
error: function (error) {
console.log(JSON.stringify(error));
}
});
return fieldHTML;
}
</script>

Related

jquery autocomplete is now working properly

I am working on jquery autocomplete in mvc platform. Now, my question is that in some textbox data autocomplete is working properly while in some textbox data autocomplete is not working properly.
For more clear, lets see the image of autocomplete task
now as per the image when I write the R word, I am getting the suggestion list of related R word.
now as per the second image I have written the whole word but still suggestion is not display.
Here is my code,
View
<input type="text" id="CustomerName" name="CustomerName" required data-provide="typeahead" class="typeahead search-query form-control autocomplete"
placeholder="Customer Name" />
<script>
$(document).ready(function () {
$.ajax({
url: "/ServiceJob/CustomerSerchAutoComplete",
method: "GET",
dataType: "json",
minLength: 2,
multiple: true,
success: function (data) {
/*initiate the autocomplete function on the "myInput" element, and pass along the countries array as possible autocomplete values:*/
//autocomplete(document.getElementById("CustomerName"), data.data);
$('#CustomerName').autocomplete({ source: data.data, minLength: 2, multiple: true });
}
});
});
</script>
Controller
[HttpGet]
public IActionResult CustomerSerchAutoComplete()
{
var customers = _Db.Ledger.Where(x => x.LedgerTypeId == (int)LedgerType.Customer).ToList();
var result = (from n in customers
select new
{
kk = n.Name.ToUpper()
}).ToList();
return Json(new { data = result });
}
As you are getting
Uncaught TypeError: Cannot read property 'substr' of undefined
For this error you should check that data is not null.
success: function (data) {
if(data != null)
{
autocomplete(document.getElementById("CustomerName"), data.data);
}
}

Using ajax to update the currently page with Laravel

I have this ajax inside my file.php (It hits the success callback):
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(data){
console.log(data);
}
});
})
</script>
Now on my Controller:
public function getProfessorList()
{
$professor = Professor::all();
$ano_semestre = isset($_GET['anoSemestre']) ? $_GET['anoSemestre'] : Horario::first()->distinct()->pluck('ano_semestre');
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
return View::make('professor', compact('professor', 'semestres', 'ano_semestre'));
}
What I want to do:
I have a LIST with professor and their disciplines. What I need to do is:
Whenever I change the value of that select box, I just remake the function with the new parameter.
I'm trying to use ajax to remake that list but nothing change, not even the URL with the professor.php?anoSemestre=xx.
Also, when I try to use the $_GET['anoSemestre'] the page doesnt show any change or any ECHO.
But If I go to Chrome spector>NEtwork and click the ajax I just made, it shows me the page with the data I sent.
Cant find out what I'm doing wrong.
UPDATE
I did what was suggested me, now I'm working with the data I get from the success callback:
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(data){
var lista = $(data).find('#list-professores'); //Get only the new professor list and thier disciplines
$('#list-professores').remove(); //Remove old list
$('#professores').append(lista); //Append the new list where the old list was before.
}
});
})
</script>
The return of var lista = $(data).find('#list-professores'); is:
Accordion Effect
#list-professores li input[name='item']:checked ~ .prof-disciplinas {
height: auto;
display:block;
min-height:40px;
max-height:400px;
}
This list is an Accordion Menu (using a checkbox and changing it with js&css), so everytime I click on a professor < li>, it's suppose to open and show a sublist (disciplines of that professor I clicked). But it's not opening anymore and no errors on the console. No idea why.
The issue here is what you are returning in your controller and how you do it, you donĀ“t need to redirect or refresh the entire page. This could be achived using a single blade partial for the piece of code you may want/need to update over ajax. Assuming you have an exlusive view for that info, you could solve this with something like this:
in your view:
<div class="tableInfo">
<!--Here goes all data you may want to refresh/rebuild-->
</div>
In your javascript:
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(){
$('.tableInfo').html(data); //---------> look at here!
}
});
})
</script>
in your controller:
public function getProfessorList()
{
$professor = Professor::all();
$ano_semestre = isset($_GET['anoSemestre']) ? $_GET['anoSemestre'] : Horario::first()->distinct()->pluck('ano_semestre');
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
if (Request::ajax()) {
return response()->json(view('YourExclusiveDataPartialViewHere', ['with' => $SomeDataHereIfNeeded])->render()); //---------> This is the single partial which contains the updated info!
}else{
return View::make('professor', compact('professor', 'semestres', 'ano_semestre'));//---------> This view should include the partial for the initial state! (first load of the page);
}
}

Updating a dropdown via knockout and ajax

I am trying to update a dropdown using knockout and data retrieved via an ajax call. The ajax call is triggered by clicking on a refresh link.
The dropdown is successfully populated when the page is first rendered. However, clicking refresh results in clearing the dropdown instead of repopulating with new data.
Html:
<select data-bind="options: pages, optionsText: 'Name', optionsCaption: 'Select a page...'"></select>
<a id="refreshpage">Refresh</a>
Script:
var initialData = "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]";
var viewModel = {
pages : ko.mapping.fromJS(initialData)
};
ko.applyBindings(viewModel);
$('#refreshpage').click(function() {
$.ajax({
url: "#Url.Action("GetPageList", "FbWizard")",
type: "GET",
dataType: "json",
contentType: "application/json charset=utf-8",
processData: false,
success: function(data) {
if (data.Success) {
ko.mapping.updateFromJS(data.Data);
} else {
displayErrors(form, data.Errors);
}
}
});
});
Data from ajax call:
{
"Success": true,
"Data": "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]"
}
What am I doing wrong?
The problem you have is that you are not telling the mapping plugin what to target. How is it suppose to know that the data you are passing is supposed to be mapped to the pages collection.
Here is a simplified version of your code that tells the mapping what target.
BTW The initialData and ajax result were the same so you wouldn't have noticed a change if it had worked.
http://jsfiddle.net/madcapnmckay/gkLgZ/
var initialData = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}];
var json = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"}];
var viewModel = function() {
var self = this;
this.pages = ko.mapping.fromJS(initialData);
this.refresh = function () {
ko.mapping.fromJS(json, self.pages);
};
};
ko.applyBindings(new viewModel());
I removed the jquery click binding. Is there any reason you need to use a jquery click bind instead of a Knockout binding? It's not recommended to mix the two if possible, it dilutes the separation of concerns that KO is so good at enforcing.
Hope this helps.

How to pass div's html to #Url.Action in Ajax post

A. Where I am so far successfully:
I have 3 divs"
NewAction
NewController
NewArea
I have an $.Ajax post with the url currently as follows
'#Url.Action("CurrentAction", "CurrentController", new { area = "CurrentArea" })'
I have several pages that require this particular Ajax post so I put the Ajax post in a partial, and each main page that uses it, has a parameter in the partial call, eg:
#Html.Partial("_PartialPage", new [] { "NewAction", "NewController", "NewArea" })
The divs in #1 above are successfully populated dynamically with the string values in #3
B. Where my difficulty lies:
Despite many efforts & attempts, I cannot change the #Url.Action values in #2 to the values in the divs in #1.
I even tried to declare C# private variables and populate them with the foreach that populated the divs above and pass those values to the #Url.Action link, but I get a run error.
Does anyone know a way I can pass the parameter values in my partial call (#3) to the Url.Action method in the Ajax post in #2 above.
Thanks in Advance.
You could have a method that will extract the values that are passed to this strongly typed partial and build the url:
#model string[]
#functions {
public string GetUrl() {
if (Model != null && Model.Length > 2)
{
var values = new RouteValueDictionary();
values["controller"] = Model[0];
values["action"] = Model[1];
values["area"] = Model[2];
return Url.RouteUrl(values);
}
return Url.Action("CurrentAction", "CurrentController", new { area = "CurrentArea" });
}
}
<script type="text/javascript">
var url = #Html.Raw(Json.Encode(GetUrl()));
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>
will render like this:
<script type="text/javascript">
var url = "/NewArea/NewAction/NewController";
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>
But if you don't need those route values separately another possibility is to directly pass the entire url to the partial view:
#Html.Partial("_About", Url.Action("NewAction", "NewController", new { area = "NewArea" }))
and then inside the partial simply use it:
#model string
<script type="text/javascript">
var url = #Html.Raw(Json.Encode(Model));
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>

How to associate an event to Html.ActionLink in MVC3

I have made an Ajax function but i am getting a big prolem in that.
I was displaying the contents on click of the link..
The links are fetched from the database and also the url of the links are fetched from the datbase.
I have wriiten ajax to call the contents dynamically on click of the link
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>
Now FetchUrlByHobbyName is the function called from the Controller thart returns the url
//Ajax routine to fetch the hobbyinfo by hobbyname
[HttpPost]
public ActionResult FetchUrlByHobbyName(string data)
{
HobbyMasters hobbymaster = new HobbyHomeService().FetchHobbyMasterByHobbyName(data);
string url = hobbymaster.InformationUrl;
if (HttpContext.Request.IsAjaxRequest())
return Json(url);
return View();
}
And in my View i have written the link like this:
#foreach (var item in Model)
{
<li >#Html.ActionLink(item.HobbyName, "Hobbies")
</li>
}
i tried this :
#Html.ActionLink(item.HobbyName, "Hobbies", null, new { id = "alink" })
and then calling Ajax on click of 'alink' but with this my ajax function doesnot get called.
Now the problem is the ajax function is getting called on click of every link on the page..
I want to assign a unique Id to it but i am not understanding how to do that
please Help me...
For that specific link, assign an id. E.g
<a id="someID" href="url">Link</a>
and than bind the click only with that link.
$('#someID').click(function (e)) ....
If I understood you correctly this helps you
The text of the link
<script type="text/javascript">
function myAjaxFunction(){
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
</script>
Try to give a css class selector to you action link like this...
#Html.ActionLink("some link", "Create", "Some_Controller", new { }, new { #class = "test" })
then User jquery for it..
<script type="text/javascript">
$(document).ready(function () {
$('.test').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>

Resources