How to add a clear button in jquery autocomplete(mvc razor) - javascript

I have a search functionality which already works by searching the data that the user requests. I would like to add a clear button for the user to be able to clear the search bar, at the moment the user has to clear the search using the "backspace" button and press "enter to go back the page with all the data. I am a expert in front end so would appreciate some help thank you in advance.
Javascript
$(function () {
$("#SearchString").autocomplete({
source: '#Url.Action("GetUserJSON")',
minLength: 1
})
});
$(function () {
$("#SearchString").focus();
});
$(function () ) {
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close');
});
};
Razor HTML
#using (Html.BeginForm("Index", "User", FormMethod.Get, null))
{
<div class="search-wrap">
#Html.TextBoxFor(m => m.SearchString, new { id = "SearchString", #class = "lookup txt-search js-autocomplete-submit", #placeholder = "Search", #type ="search" })
#*<img src="~/Content/Images/close.png" id ="closebutton"/>*#
<button type="button" id="clearbutton">Click Me!</button>
<i onclick="submitform()" class="btn-search fa fa-search"></i>
</div>
}
C# Class where data get pull from
public JsonResult GetUserJSON(string term)
{
var stores = (from st in UserLogic.GetUserIndex(1, term).IndexList
select new { st.Username, st.FirstName, st.LastName }).ToList();
List<String> returnList = new List<string>();
foreach (var item in stores)
{
if (item.Username.ToString().ToUpper().StartsWith(term.ToUpper()))
{
returnList.Add(item.Username.ToString());
}
else if (item.FirstName.ToUpper().Contains(term.ToUpper()))
{
returnList.Add(item.FirstName);
}
else if (item.Username.ToUpper().Contains(term.ToUpper()))
{
returnList.Add(item.Username);
}
}
returnList = returnList.Distinct().OrderByAlphaNumeric(s => s).ToList();
return Json(returnList, JsonRequestBehavior.AllowGet);
}

I think this is what you need:
$(function () {
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close');
$("#SearchString").val("")
});
});
Add $("#SearchString").val("") to your clearbutton click event
Edit:
You have mistyped the function for clearSearch
this is working example

please try using this
$("#clearbutton").click(function () {
$('#SearchString').autocomplete('close').val('');
});

Related

How to click ActionLink automatically when the dropdown is changes?

I have one dropdown and one actionlink.
where this actionlink will be clicked automatically when the dropdown changes. How to do that?. below is my code, thanks.
#Html.DropDownListFor(model => model.PaymentCode, (List<SelectListItem>)ViewBag.JenisPembayarans, new { #class = "form-control" })
#Html.ActionLink(
"Detail",
"GetInsuranceCompany","ParamBlacklistPembayaran",
new { id = Model.PaymentCode }, new { #class = "ddlSubmit"})
Controller
public ActionResult GetInsuranceCompany( ParamBlacklistPembayaranViewModel model,string id)
{
LoadThirdPartyDDL(string.Empty, string.Empty, id);
return View("Create", model);
}
#Html.DropDownListFor(model => model.PaymentCode, (List<SelectListItem>)ViewBag.JenisPembayarans, new { #class = "form-control",#id="ddl" })
#Html.ActionLink("Detail",
"GetInsuranceCompany","ParamBlacklistPembayaran",
new { id = "PaymentCodeVal" }, new { #id="anchorclick",#class = "ddlSubmit"})
You should call click event on drop down change like this:
<script>
document.getElementById('ddl').onchange = function () {
var path = document.getElementById('anchorclick').href;
path = path.replace("PaymentCodeVal", document.getElementById('ddl').value);
document.getElementById("anchorclick").href=path;
document.getElementById('anchorclick').click();
};
</script>
#NOTE : You want get updated PaymentCode. you have to inject url to pass PaymentCode on change event.
Assign onchange event in new {} section where you can raise the event of the particular action link by using their id.
#Html.DropDownListFor(model => model.PaymentCode, (List<SelectListItem>)ViewBag.JenisPembayarans, new { #class = "form-control", #id = "MyId", onchange = "MyFunction()" })
<script type="text/javascript">
function MyFunction() {
//alert('Changed');
document.getElementsByClassName("ddlSubmit").click();
$('#YourLabelId').val('ReplaceWithThisValue');
}
</script>
References:
Handling onchange event in HTML.DropDownList Razor MVC

ASP.NET MVC -Refresh CodeMirror editor onclick

I have a codemirror editor in a partial view and a list of files in the main view. I want to refresh the editor once a file name is clicked. I tried many solutions provided on StackOverflow and other websites but nothing worked , and This is my first time using Javascript so I can't figure out What am I doing wrong.
This is my code:
Controller:
public ActionResult Index()
{
StudentsCodes model = new StudentsCodes();
model.Student = (Student)CurrentUser;
var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
model.Instructor =(Instructor) user;
return View(model);
}
public PartialViewResult DevelopmentPartial (StudentsCodes path )
{
return PartialView(path);
}
Main view:
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.js"></script>
<ul id="tree">
#foreach (var file in Directory.GetFiles(Server.MapPath("~/Content/" + Model.Student.UserName + "/CompilerProject/" + name)))
{
var filename = Path.GetFileName(file);
<li id="filelist" onclick="#(Model.path = "~/Content/" + Model.Student.UserName + "/CompilerProject/src/" + #filename)">
<span class="glyphicon glyphicon-file"></span>
#filename
/li>
}
<div id="partial">
#{
Html.RenderPartial("DevelopmentPartial",null);
}
</div>
<script>
$(document).ready(function () {
$("#filelist").click(function (e) {
#{Html.RenderAction("DevelopmentPartial", Model);
}
});
});
</script>
partial view:
#using (Html.BeginForm())
{
var fileContents= "";
if (Model==null)
{
fileContents = "";
}
else
{
fileContents = System.IO.File.ReadAllText(Server.MapPath(Model.path));
}
#Html.TextArea("code", fileContents, new { id = "code" })
}
I can't assign ids for list elements since their number is unknown at compile time and it changes when the user adds or deletes a file, that's why most of the solutions provided didn't work . The result here was 3 editors overlapping and display the contents of the last file. And <li> items are non-clickable. What am I doing wrong in my code ?
Edit:
After updating the script as the following:
<script>
$(document).ready(function() {
$(".filelist").on("click",function (e) {
$("#partial").load('DevelopmentPartial');
});
});
</script>
It refreshes the partial view but the editor is always empty, and the Model is always null. Is it wrong to update the Model using "onclick"?
In case someone faced the same problem, I solved it by changing id to class at the list, then by using this script:
<div id="partial">
#{
Html.RenderAction("DevelopmentPartial", new { path1 = Model.path});
}
</div>
<script>
$(document).ready(function () {
$('.filelist').on('click', function (e) {
alert('Im clicked on filePath = ' + $(this).attr('value'));
var filePath = $(this).attr('value'); //value is attribute set in Html
$('#partial').load('DevelopmentPartial', { path1: filePath });
});
});
</script>
And the controller:
public PartialViewResult DevelopmentPartial(string path1)
{
modelSC.path = path1;
return PartialView(modelSC);
}
where modelSC is a global variable in the controller.

Similar MVC actions called by javascript, AntiForgery works on one, not the other

I have a javascript function I use to do an Ajax call to my controller function. The javascript is generic enough I can use it for multiple controls. I have two areas that use the script. One works, one doesn't. I believe it's the footprint of the MVC controller that is being called.
The javascript looks like this:
$(Document).on("click",".delete-link",function (event) {
var deleteLink = $(this);
deleteLink.hide();
var confirmButton = deleteLink.siblings(".delete-confirm");
confirmButton.show();
var cancelDelete = function () {
removeEvents();
showDeleteLink();
};
var deleteItem = function () {
removeEvents();
confirmButton.hide();
var url = '/' + confirmButton.attr('data-delete-controller') + '/' + confirmButton.attr('data-delete-action') + '/' + confirmButton.attr('data-delete-id');
$.post(
url,
AddAntiForgeryToken({ id: confirmButton.attr('data-delete-id') }))
.done(function () {
var parentRow = deleteLink.closest(".removable-row");//"tr:first, li:first");
parentRow.fadeOut('fast', function () {
parentRow.remove();
});
}).fail(function (data) {
alert("error");
});
return false;
};
var removeEvents = function () {
confirmButton.off("click", deleteItem);
$(document).on("click", cancelDelete);
$(document).off("keypress", onKeyPress);
};
var showDeleteLink = function () {
confirmButton.hide();
deleteLink.show();
};
var onKeyPress = function (e) {
//Cancel if escape key pressed
if (e.which == 27) {
cancelDelete();
}
};
confirmButton.on("click", deleteItem);
$(document).on("click", cancelDelete);
$(document).on("keypress", onKeyPress);
return false;
});
AddAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();
return data;
};
So the MVC view and controller action that work are defined like this:
<div class="row">
#Html.HiddenFor(model => model.CustomFieldOptionId)
#Html.HiddenFor(model => model.CustomFieldId)
#Html.HiddenFor(model => model.SortOrder, new { #class = "SortOrder" })
#Html.HiddenFor(model => model.IsActive)
#Html.ValidationMessageFor(model => model.OptionLabel, "", new { #class = "text-danger" })
<div class="col-md-2">
#Html.LabelFor(model => model.OptionLabel, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-7">
#Html.EditorFor(model => model.OptionLabel, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-3">
<input type="button" value="Delete" class="btn delete-link" />
<div class="btn btn-primary delete-confirm" style="display: none"
data-delete-id="#Model.CustomFieldOptionId"
data-delete-controller="customforms"
data-delete-action="_OptionEditorRowDelete">Confirm Delete</div>
</div>
</div>
Controller:
[HttpPost, ActionName("_OptionEditorRowDelete")]
[ValidateAntiForgeryToken]
public ActionResult _OptionEditorRowDelete(int id)
{
var custFieldOption = db.CustomFieldOptions.Find(id);
if (custFieldOption == null) return null;
custFieldOption.IsActive = false;
db.Entry(custFieldOption).State = EntityState.Modified;
db.SaveChanges();
return null;
}
The one that is not working is defined like this:
#foreach (var item in Model) {
<tr>
<td>
#Html.HiddenFor(modelItem => item.ProfileId)
#Html.DisplayFor(modelItem => item.ProfileIdentifierValue)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsPrimary)
</td>
<td>
#Html.ActionLink("Edit", "profileemailsedit", new { id = item.ProfileIdentifierId }) |
#Html.ActionLink("Delete", "_ProfileEmailsDelete", new { id = item.ProfileIdentifierId }, new { #class = "delete-link" })
<a class="delete-link" href="#Url.Action("_ProfileEmailsDelete", new { id = item.ProfileIdentifierId })">Delete</a>
<input type="button" value="Delete" class="btn delete-link" />
<div class="btn btn-primary delete-confirm" style="display: none"
data-delete-id="#item.ProfileIdentifierId"
data-delete-controller="profiles"
data-delete-action="_ProfileEmailsDelete">Confirm Delete</div>
</td>
</tr>
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult _ProfileEmailsDelete(int id)
{
var profIdentifier = db.ProfileIdentifier.Find(id);
if (profIdentifier == null) return null;
profIdentifier.IsActive = false;
db.Entry(profIdentifier).State = EntityState.Modified;
db.SaveChanges();
return null;
}
As you can see the controllers are very similar. However, the _ProfileEmailsDelete get's this javascript error:
POST http://localhost:63595/profiles/_ProfileEmailsDelete/168 500 (Internal Server Error)
Part of the server 500 error is:
[HttpAntiForgeryException]: The required anti-forgery form field
"__RequestVerificationToken" is not present. at
System.Web.Helpers.AntiXsrf.TokenValidator.ValidateTokens(HttpContextBase
httpContext, IIdentity identity, AntiForgeryToken sessionToken,
AntiForgeryToken fieldToken) at
System.Web.Helpers.AntiXsrf.AntiForgeryWorker.Validate(HttpContextBase
httpContext) at System.Web.Helpers.AntiForgery.Validate()
I'm not sure why the AntiForgery works with one and not the other.
The 500 error is your ajax response from the server, not your javascript. The actual problem is not jumping out at me, but most often when I have seen this type of behavior it ends up being something in the view rendering that causes it. For example trying to reference the values of a collection that is null in the view would act this way. Using the traffic analyzer features of the browser developer tools can sometimes help shed light on the real problem.
The first example was in a partial view. The parent view had this:
#Html.AntiForgeryToken()
I added that to the View for the second example, and then the javascript could properly get the token to pass back with the $.post command.

BeginCollectionItem new element not working with jQuery MVC 5

I'm trying to test whether content is in a text field, this works with initially loaded elements, but not the elements (which share the same class name) added using beginCollectionItem.
For example a textbox is added through bci and gets filled in, when filled in and focus goes elsewhere, the textbox will be given the 'makeitred' class.
What's wrong with the javascript I'm using?
partial using BCI
<div class="editorRow">
#using (Html.BeginCollectionItem("ispDetails"))
{
<div class="ui-grid-c ui-responsive">
<div class="ui-block-a">
<span>
#Html.TextBoxFor(m => m.type, new { #class = "isitempty" })
</span>
</div>
</div>
}
</div>
Index segment calling partial - on page load elements the jQuery works, anything there after using the add button doesn't
#using (Html.BeginForm())
{
<div id="editorRowsEQM">
#foreach (var item in Model.ispDetails)
{
#Html.Partial("EquipView", item)
}
</div>
#Html.ActionLink("Add", "ispManager", null, new { id = "addItemEQM", #class = "button" });
}
JS from the Index
$(function () {
$('#addItemEQM').on('click', function () {
$.ajax({
url: '#Url.Action("ispManager")',
cache: false,
success: function (html) { $("#editorRowsEQM").append(html); }
});
return false;
});
$(document).on('change', '.isitempty', function checkFill (e) {
if ($(this).val().length == 0) {
$(this).removeClass('makeitred');
} else $(this).addClass('makeitred');
});
});

How to get a #html.Checkbox to update a #html.dropdownList

I have the following checkbox:
#Html.CheckBox("Norm", false, new { #class = "checkbox" })
Once this is checked, I want it to auto update my dropdown
#Html.DropDownList("selectedCore", (SelectList)ViewBag.CoreSheets)
The dropdown selectlist is populated from my controller like this,
ViewBag.CoreSheets = new SelectList(db.CoreSheets, "sheetID", "Abb");
So in summary, I want to click the check box and have the current dropdown value be updated.
Cheers,
B
N J
Try this code
#Html.CheckBox("Norm", false, new { #class = "checkbox",#onclick="clickNorm()" })
<script type="text/javascript">
function clickNorm(){
$.ajax({
url:'#Url.Action("LoadSelectedCoreList")'
dataType:'json',
success:function(res){
if(res && res.length>0){
$('#selectedCore).empty();
$.each(res,function(index,item){
$('#selectedCore').append(new Option(item.Abb,item.sheetID));
});
}
}
});
</script>
In Coltroller
public ActionResult LoadSelectedCoreList()
{
var selectedCoreList=..
return Json(selectedCoreList,
JsonRequestBehavior.AllowGet);
}
I solved this myself by doing the following,
Check box
#Html.CheckBox("Norm", false, new { #class = "checkbox" })
Jquery
<script type="text/javascript">
$(document).ready(function() {
$("#Norm").on("click", function () {
if ($(this).is(":checked")) {
$("#kammcoreauto").val(1);
$("#kammfaceauto").val(1);
$("#spacecoreauto").val(1);
$("#Washercoreauto").val(1);
$("#IsoCoreauto").val(1);
$("#IsoFaceauto").val(1);
}
});
});
</script>
and this just refers to the id of the dropdowns that you can add like this
#Html.DropDownList("selectedCore", (SelectList)ViewBag.CoreSheets, new { id = "kammcoreauto" })
Big Thanks to everyone who tried to help

Categories

Resources