Adding Item to list on click Javascript/Jquery - javascript

So i have list that is created dynamically as shown
Now I need a ADD button, which on click will add new item to list automatically. Help me out with this please.

Hi this is how can you retrive data using jquery
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "URL/MethodName",
data: "{}",// you can provide parameteres to your function here
dataType: "JSOn",
success: function (data) {
for (var i in data) {
alert(data[i].Id); //assign to controls
alert(data[i].Header);// assign to controls
alert( data[i].Content) ;// assign to contols
}
alert('Data fetched Successfully');
},
error: function (result) {
alert('Data not fetched ');
return false;
}
});
return false;
});
/*************************************************************************
[System.Web.Services.WebMethod]
public ActionResult Careers()
{
List<JobOpening> job = new List<JobOpening>()
{
new JobOpening{Id = 1, Header = "Job1", Content = "edde" },
new JobOpening{Id = 2,Header = "Job2", Content = "deded" },
};
}

Related

jquery how to display values in alert message

this is my code please help me with the query
$("#update").click(function () {
var security_code = (red[0]["id"]);
var sector_class_id = (red[0]["cid"]);
var sector_id = $("#s1").val();
$.ajax({
type: "POST",
url: "Default.aspx/update",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ security_code: security_code, sector_class_id: sector_class_id, sector_id: sector_id }),
dataType: "json",
success: function (response) {
var updatedata = (response.d);
var ud1 = JSON.parse(updatedata);
udata = $.map(ud1, function (n, i) {
var temp7 =
{
secr_code: n.SECURITY_CODE,
sect_class: n.SECTOR_CLASS_ID,
sect_id: n.SECTOR_ID
}
return temp7
});
$("#mod1").modal('hide');
display();
$("#t1").hide();
$(".alert-succcess").alert();
window.setTimeout(function () {
$(".alert-success").fadeTo(2000, 500).slideUp(500, function () {
//$("#l1").val(security_code);//label values from db
//$("#l2").val(sector_class_id);//label values from db
//$("#s1").val(sector_id);// user selects n den updates value
$(".alert-success").slideUp(500);
});
});
},
i want to show updated values in my alert message along with the previous values which were updated what should i do
what should i do??????

how to pass dynamically created options in multi select box to MVC controller

Please help. I'm using MVC, razor 3, jquery.
I dynamically create a multi select box when a dropdown selection changes. I bind the multiple selection to a List in my model. And it works, except it passes me the list of selected indice, instead of a list of the selected text. I want selected text, not index of the list. I set the value as text, but I have no luck.
if I manually create the list, everything works. How do I pass a list of selected options back to the controller?
I have this div in my view:
<div class="row-fluid" id="divAvailableAssemblies" hidden ="hidden">
<label class="span4">Available Assemblies:</label>
<select multiple="multiple" class="span8 ui-corner-all" id="Request_SelectingAssemblies" name="Request.SelectingAssemblies">
#*<option value="test">test</option>
<option value="test2">test2</option>*#
</select>
</div>
Here my jquery:
<script type="text/javascript">
$(function () {
$('#ddPartsToCreate').live('change',function () {
var selectedPart = this.value;
if (selectedPart < 6 || $("#txtOrderNumber").val()=="")
{
$("#divAvailableAssemblies").attr("hidden", "hidden");
return;
}
$("#divAvailableAssemblies").removeAttr("hidden");
$.ajax({
type: 'POST',
url: '#Url.Action("GetSelectingAssembliesFromOrder", "Home")',
data: JSON.stringify({ orderNumber: $("#txtOrderNumber").val() }),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
async: false,
success: function (response) {
var returnedData = JSON.parse(response);
var selectingAssemblies = $("#Request_SelectingAssemblies");
selectingAssemblies.empty();
for (var assembly in returnedData)
{
//selectingAssemblies.append($('<option >', { value: assembly }).text(returnedData[assembly].Text)).hide().show();
//selectingAssemblies.append($('<option value=' + assembly + '>' + returnedData[assembly].Text + '</option>'));
//selectingAssemblies.append($('<option >', { value: assembly, text: returnedData[assembly].Text }));
//selectingAssemblies.append($('<option></option>').val(assembly).html(returnedData[assembly].Text));
//$("#Request_SelectingAssemblies").append($('<option>', { value: assembly }).text(returnedData[assembly].Text));
//$("#Request_SelectingAssemblies").append($('<option>', { value: assembly }).text(returnedData[assembly].Text));
//$('<option />', { value: assembly, text: returnedData[assembly].Text }).appendTo(selectingAssemblies);
selectingAssemblies.append($('<option></option>').val(assembly).html(returnedData[assembly].Text));
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
in the backend, I generate JSON:
foreach (var assembly in pr.ShipParts)
{
sb.Append(String.Format(",{{\"Text\":\"{0}\", \"Value\":\"{1}\"}}", assembly.Mark.ToString(), assembly.Mark.ToString()));
availableAssemblies.Add(assembly.Mark.ToString());
}
I bind the multiple selection(Request_SelectingAssemblies) with this property in my model:
public List<String> SelectingAssemblies
{
get
{
return _SelectingAssemblies;
}
set
{
_SelectingAssemblies = value;
}
}
private List<String> _SelectingAssemblies = new List<string>();
When it gets to my action in the controller, SelectingAssemblies has index instead of the actual text. But I set the value of each option as text. If I set the option manually, they will show in source page and return the text. But since I dynamically create the options, they don't show in source page. I don't know how I can make MVC understand dynamic data.
In the picture, the list of CX001, RBX001, RBX002 is dynamically created. if I hit F12 in IE, I will see them created correctly in the DOM. If I choose CX001 and RBX002, SelectionAssembies will have 0 and 2.
Thanks
This is the latest and working code, thanks to #StephenMuecke:
<script type="text/javascript">
$(function () {
$('#ddPartsToCreate').live('change',function () {
var selectedPart = this.value;
if (selectedPart < 6 || $("#txtOrderNumber").val()=="")
{
$("#divAvailableAssemblies").attr("hidden", "hidden");
return;
}
$("#divAvailableAssemblies").removeAttr("hidden");
$.ajax({
type: 'POST',
url: '#Url.Action("GetSelectingAssembliesFromOrder", "Home")',
data: JSON.stringify({ orderNumber: $("#txtOrderNumber").val() }),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
async: false,
success: function (response) {
var returnedData = JSON.parse(response);
var selectingAssemblies = $("#Request_SelectingAssemblies");
$.each(returnedData, function (index, item) {
selectingAssemblies.append($('<option></option>').val(item.Value).html(item.Text));
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
public ActionResult GetSelectingAssembliesFromOrder(String orderNumber)
{
return Json(model.GetSelectingAssembliesFromOrder(orderNumber), JsonRequestBehavior.AllowGet);
}
public String GetSelectingAssembliesFromOrder(String orderNumber)
{
//...
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (var assembly in pr.ShipParts)
{
string assemblyName = assembly.Mark.Trim();
sb.Append(String.Format(",{{\"Text\":\"{0}\", \"Value\":\"{1}\"}}", assemblyName, assemblyName));//JSON to build the list
//...
}
sb.Append("]");
sb.Remove(1, 1);//remove extra comma
_db.SaveChanges();
return sb.ToString();
}

Autocomplete textbox in asp.net mvc4 using ajax and jQuery

I am trying to fetch company name in textbox as autocomplete. When I run my project, Ajax will call the success function, and the record is also fetched correctly, but there are no autocomplete suggestions in the textbox.
My view is:
$("#idcompanyname").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Companymap", "admin")',
data: "{'term':'" + document.getElementById('idcompanyname').value + "'}",
dataType: "json",
success: function (data) {
alert(data)
response($.map(data, function (v, i) {
var text = v.vcCompanyName;
alet(text)
if (text && (!request.term || matcher.test(text))) {
return {
label: v.vcCompanyName,
value: v.kCompanyId
};
}
}));
},
error: function(result) {
alert("No Match");
}
});
}
});
}
Here is Method on controller:
var query = db.tbaccounts.Where(t => t.vcCompanyName.ToLower()
.StartsWith(term)).ToList();
List<string> lst = new List<string>();
foreach (var item in query)
{
lst.Add(item.vcCompanyName);
}
return Json(lst, JsonRequestBehavior.AllowGet);
Here is the referred Javascript:
<script src="~/script/jquery-2.0.3.js"></script>
<script src="~/script/jquery-ui.js"></script>
<script src="~/js/jquery-1.10.2.js"></script>
<script src="~/js/jquery-ui.js"></script>
Please try removing
~/script/jquery-2.0.3.js
from the script references in your application, and that should work for you....

JQuery Success Function not firing

I have the following script. It runs, it passes the variables to the controller, the controller executes correctly, but for whatever reason the success function does not fire and therefore does not refresh my html. Instead the error fires off. Nothing is jumping out at me as to the cause. Thanks for the help!
$(function() {
$("#btnUpdateTick").unbind('click').click(function () {
var currenttick =
{
"TicketID":#Html.Raw(Json.Encode(Model.TicketID)),
"Title": $("#Title").val(),
"Creator": $("#Creator").val(),
"StatusID": $("#StatusID").val(),
"Description": $("#Description").val(),
"newComment":$("#txtAddComment").val(),
Cat:
{
"CatID":$("#ddCurrTickCat").val()
}
}
//var newcomment = $("#txtAddComment").val();
var conv = JSON.stringify(currenttick);
$.ajaxSetup({cache:false});
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
});
});
My controller:
[HttpPost]
public PartialViewResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return PartialView("TicketDetails", model);
}
Your controller is returning a view instead of json. You should be returning a JsonResult instead. Try this:
[HttpPost]
public JsonResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return Json(model);
}
If you want to return Partial view from ajax call then modify ur ajax request as :
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "html",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
Now "data" in ur success function will have html returned from PartialViewResult().

show a dialog box , when hovering over the auto complete records

I have the following JavaScript code to do an autocomplete:
$("#Technology2_Tag").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Content("~/Switch/AutoComplete2")",
dataType: "json",
minLength: 2, delay: 2000,
data: {
term: request.term,
SearchBy: $("#ChoiceTag").prop("checked") ? $("#ChoiceTag").val() : $("#ChoiceName").val(),
},
success: function (data) {
response(data);
}
});
},
});
And I am returning the autocomplete records as JSON:
public ActionResult AutoComplete2(string term, string SearchBy)
{
if (SearchBy == "Tag")
{
var tech = repository.AllFindTechnolog(term).OrderBy(p => p.Tag).Select(a => new { label = a.Tag }).ToList();
return Json(tech, JsonRequestBehavior.AllowGet);
}
else
{
var tech = repository.FindActiveResourceByName(term, true).OrderBy(p => p.RESOURCENAME).Select(a => new { label = a.RESOURCENAME }).ToList();
return Json(tech, JsonRequestBehavior.AllowGet);
}
}
But my question is how I can show a dialog the contains additional info about the record, when the user hovers over an autocomplete record.
what i am thinking of is as follows:
when the user hovers over any autocomplete record, to fire a JavaScript function.
the function calls an action method, that returns JSON.
to build the dialog box using the returned JSON object.
First you need to create a div let's say with the id=mydiv which can be a dialog. Initialize it as a dialog.
Then in your autocomplete use focus event. Which will handle an Ajax function which will call an Action (this action can return a Partial view) and will fill your div with the description.
$("#mydiv").dialog();
$ ("#Technology2_Tag").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Content("~/Switch/AutoComplete2")",
dataType: "json",
minLength: 2, delay: 2000,
data: {
term: request.term,
SearchBy: $("#ChoiceTag").prop("checked") ? $("#ChoiceTag").val() : $("#ChoiceName").val(),
},
success: function (data) {
response(data);
}
});
},
focus: function(event,ui){
var element =ui.item.val;
$.ajax({
url: "#Url.Content("~/Switch/ActionDescription")",
dataType: "json",
data: {
hoverelment: element },
success: function (data) {
$('#myDiv').append(data);
$('#myDiv').show();
}
});
}
});
I gave you lines, you have to create another action which will receive a parameter, can send a partial view or just string.
public ActionResult ActionDescription(string hoverlement)
{
.........//linq queries to retrieve description by hoverelement
}
I hope it will help.

Categories

Resources