Check Items Already exista in the Table using Jquery - c#

I have a Select2 list and added multiple items to the table.But i wanted to check if items already exists in the table or not first and IF not only then add new item But below my code doesn't work.
In this code everytime it shows Not Found & add duplicate rows
HTML Part
<select id="select-product" multiple style="width: 300px">
</select>
Code
$("#select-product").change(function () {
debugger;
var $option = $('#select-product option');
if ($("#select-product option[value='ProductCode']").length > 0) {
alert("Found");
}
else
{
alert("Not Found");
}
$option.each(function () {
if ($(this).is(':selected')) {
debugger;
var itm = $(this).is(':selected');
var temp = $(this).attr('ProductCode');
var row = '<tr>';
row += '<td class="itmcode">' + $(this).attr('ProductCode') + '</td>';
row += '<td class="itmname">' + $(this).text().replace(temp, " ") + '</td>';
row += '<td class="unit">' + $(this).attr('Unit_UnitId') + '</td>';
row += '<td class="retprice" dir="rtl" align="right">' + $(this).attr('RetailPrice') + '</td>';
row += '<td class="col-md-1 inpqty" dir="rtl">' + '<input type="text" class="input-qty form-control col-md-3 center-block input-sm" data-id="' + $(this).val() + '" data-prod-id="' + $(this).attr('Value') + '">' + '</td>';
row += '<td class="col-md-1 disc" dir="rtl">' + '<input type="text" class="input-disc form-control input-sm">' + '</td>';
row += '<td class="tot" dir="rtl" align="right">0</td>';
row += '<td class="imgdel"><img class="btn-img-del" src="../Images/delete.png" alt="" title="Delete" /></td>';
row += '</tr>';
table.append(row);
}
});
$('#select-product').select2('data', null);
});
Multiple Products Code
function CallMultipleProducts() {
$.ajax({
type: "POST",
url: '/Sales/GetMultipleProducts',
contentType: "application/; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
debugger;
if (msg._productlist.length > 0) {
debugger;
$.each(msg._productlist, function (index, item) {
debugger;
$('#select-product').append($("<option></option>")
.attr("Value", item.ProductId)
.attr("RetailPrice", item.RetailPrice)
.attr("ProductCode", item.ProductCode)
.text((item.ProductCode) + " " + (item.ProductName))
);
});
}
}
// error: AjaxError
})
}

Make sure that you have only select item with unique id="select-product" throughout your html.
Try below code, use .find()
if ($("#select-product").find("option[value='ProductCode']").length > 0) {
alert("Found");
}

Please try adding the below option to your select2 options if the element is input type="text",
$("#select-product").select2({
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} }
});
If you are using <select> element, I'm afraid you can't use this option. You have to use input instead. You might find something useful here.

Related

Dropdown list onchange can't display dropdown list

I have 2 dropdown. States/Divisions and Townships. Townships dropdown is blank. If I choose something in the S/D dropdown, Township dropdown changes according to the S/D selection. But I can't see the dropdown list in the Township and it's just white. Can someone help me please?
It's work but the changes in township dropdown list are blank.
My controller
[HttpGet]
public JsonResult Township_Filter(string id)
{
List<string> tsp = db.TB_Township.Where(t => t.StateDivisionID.Equals(id)).Select(t => t.Township).ToList();
return Json(tsp, JsonRequestBehavior.AllowGet);
}
My Ajax call
$(document).ready(function () {
$("#StateDivision").on("change", function () {
var sdID = $("#StateDivision").val();
$.ajax({
type: 'GET',
url: '/LoanMaster/Township_Filter',
data: {id : sdID},
beforeSend: function(){
},
success: function (tsp) {
if(tsp != null)
{
$('#Township').empty();
$('#Township').append($('<option value="">--Choose--</option>'));
for (i = 0; i < tsp.length; i++)
{
$('#Township').append($('<option value="' + tsp[i] + '>"' + tsp[i] + '</option>'));
}
}
},
complete: function () {
}
});
});
});
My View
<select id="StateDivision" class="form-control">
<option>--Choose--</option>
<option value="100">A</option>
<option value="101">B</option>
</select>
<select id="Township" class="form-control abc">
<option>--Choose--</option>
</select>
There is a syntax error
$('<option value="' + tsp[i] + '>" ' + tsp[i] + '</option>')
maybe that's why. try This
$('<option value="' + tsp[i] + '">' + tsp[i] + '</option>')

jQuery Select2 ajax data source not triggered / called

I'm trying to bind my Select2 dropdown list to an MVC (v5.2.3) controller of my application.
I've pretty much copied the code from the demo:
<select id="select-ticket-test" class="duplicate-post-select" style="width: 100%;" placeholder="Select ticket">
<option></option>
<option value="3620194" selected="selected">select2/select2</option>
</select>
#section Scripts {
<script type="text/javascript">
function formatTicket(ticket) {
if (ticket.loading) {
return ticket.text;
}
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__avatar'><img src='" + ticket.owner.avatar_url + "' /></div>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>" + ticket.full_name + "</div>";
if (ticket.description) {
markup += "<div class='select2-result-repository__description'>" + ticket.description + "</div>";
}
markup += "<div class='select2-result-repository__statistics'>" +
"<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + ticket.forks_count + " Forks</div>" +
"<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + ticket.stargazers_count + " Stars</div>" +
"<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + ticket.watchers_count + " Watchers</div>" +
"</div>" +
"</div></div>";
return markup;
}
function formatTicketSelection(ticket) {
return ticket.Id || ticket.Subject;
}
$("#select-ticket-test").select2({
placeholder: "Select a state",
allowClear: true,
ajax: {
url: "#Url.Action("GetAjaxAsync")",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term,
pageSize: params.page,
pageNum: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: false
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatTicket,
templateSelection: formatTicketSelection
});
</script>
}
public async Task<ActionResult> GetAjaxAsync(string searchTerm, int pageSize, int pageNum)
{
long number = Convert.ToInt64(searchTerm.Replace("T", null));
var posts = await UnitOfWork.SupportPosts.Where(x => x.Number == number).ToListAsync();
var json = new
{
Results = posts.Select(x => new
{
x.Id,
x.NumberName
}),
Total = posts.Count
};
return Json(json, JsonRequestBehavior.AllowGet);
}
What I've noticed is, that the placeholder isn't even shown. The Select2 is initialized (as in "not a "real" dropdown anymore"), but no placeholder is shown. And when typing into the textbox, no call is even made to my controller.
There are no JavaScript errors in the console either.

how can i pass ajax result object from one jquery function to other

I want to pass ajax success result object from one jquery function to other.
here is my code :
courses += '<a id="grid-item" class="dsd col-sm-6 col-md-4 " style="padding:10px; cursor:pointer" onclick="func("+result[i].subcourses+")" >';
my jquery function is :
function func(data)
{
}
but is giving me error. result[i].subcourses is object type
how can I achive this .. any help appreciated. thanks in advance
full code :
$.ajax({
type: "GET",
url: '#Url.Action("LoadCourse", "CourseMenu")',
datatype: 'json',
data: {
idsubCoursecategory: Number(subcategoryid)
},
success: function (result) {
if (result != null) {
if (result.length != 0) {
courses += '<h5 class="subcat-text">' + varsubcategoryname + '</h5>';
courses += "<div class='row' id='grid'>";
for (var i = 0; i <= result.length - 1; i++) {
var myid;
if (result[i].hassubcourse == false) {
courses += '<div id="grid-item" class="col-sm-6 col-md-4" style="padding:10px; cursor:pointer" onclick="fnLoadCourseMaster(\'' + result[i].coursecode + '\', ' + divid + ', \'' + varcoursetypename + '\', ' + varcoursecategoryid + ', \'' + varcoursecategoryname + '\', ' + subcategoryid + ', \'' + varsubcategoryname + '\', \'' + result[i].coursename + '\')">';
courses += "<div class='thumbnail'>";
courses += "<img src='../../Images/dotnet4logo.jpg' alt='coursing' width='100px' height='100px'>";
// courses += "<hr /'>";
courses += "<div class='caption'>";
courses += "<h3 >" + result[i].coursename + "</h3>";
courses += '</div>';
courses += '</div>';
courses += '</div>';
}
else {
courses += '<a id="grid-item" class="dsd col-sm-6 col-md-4 " style="padding:10px; cursor:pointer" onclick="func()" >';
courses += "<div class='thumbnail'>";
courses += "<img src='../../Images/dotnet4logo.jpg' alt='coursing' width='100px' height='100px'>";
// courses += "<hr /'>";
courses += "<div class='caption'>";
courses += "<h3 >" + result[i].coursename + "</h3>";
courses += "<input type='hidden' value='" + result[i].subcourses + "'>";
courses += '</div>';
courses += '</div>';
courses += '</a>';
}
}
courses += '</div>';
$("#divCoursesEngine-" + divid).append(courses);
}
else {
noresultmsg += '<div class="alert alert-warning alert-dismissible" role="alert">';
noresultmsg += '<strong>Oops.!</strong> no result found for selected criteria.';
noresultmsg += '</div>';
$("#divCoursesEngine-" + divid).append(noresultmsg);
}
}
else {
alert("hi");
}
},
error: function (xmlHttpRequest, textStatus, errorThrown) { alert('An error occurred while Data fetching.'); },
complete: function () { }
});
You can write as value='" + JSON.stringify(result[i].subcourses) + "' ............
and if you want back in JSON you can convert that string as JSON.parse(value).
Let me know if you want more help

How to add Items in jcarousel ? in C#

I would like to add Items in jcarousel using c# Webmethod + jquery Ajax
for that i made something like this :
my Html is like :
<div>
<ul id="mycarousel" class="jcarousel-skin-tango" style="float: left">
</ul>
</div>
Jquery code for jcarousel and Ajax Method is like this :
$("#mycarousel").empty();
var element =jQuery('#mycarousel');
$.ajax({
url: "Home.aspx/GetProjectData",
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: "{}",
async: false,
success: function (response) {
if (response.d != null) {
//$.each(response.d, function (i, response) {
$("#mycarousel").html('response.d');
element.jcarousel(
{
pager: true,
visible: 6
});
}
else {
}
},
error: function (xhr) {
}
});
and webmethod is like this :
[WebMethod]
public static List<string> GetProjectData()
{
// here i have 3 list in returnvalue
foreach (var item in returnvalue)
{
var classvalue = item.Soid + "|"
+ item.ProjectTitle + "|"
+ item.Role + "|"
+ item.StartDate + "|"
+ item.EndDate + "|"
+ item.Location.Country + "|"
+ item.Location.State + "|"
+ item.Location.City + "|";
string Template = "<li><img src='../Images/DefaultPhotoMale.png' class='"+ classvalue + "' width='40' height='40' alt='image'/></li>";
list.Add(Template);
}
return list;
}
but problem is , i am not able to images in jcarousel , i only see white box, i am not able to seee images inside, why ?
I'm not sure but wouldn't you need to append the elements sort of like this:
var listItem = $(response.d); //I'm guessing reponse.d is your returned li
element.append(listItem);

send fieldset values by jquery

look at this code :
[WebMethod]
public static string GetFacilities(string id)
{
int hotelid = System.Convert.ToInt32(Tools.DecryptString(id));
string ret = "";
foreach (var item in new FacilityGroupBL().Load())
{
if(item.Facilities.Count != 0)
{
ret += "<fieldset>";
if (item.Facilities.Count() != 0)
{
foreach (var subitem in item.Facilities)
{
if (subitem.HotelFacilities.Where(obj => obj.HotelId == hotelid).Count() != 0)
ret += "<input type='checkbox' checked='false' />" + subitem.Name;
else
ret += "<input type='checkbox' checked='true' />" + subitem.Name;
}
}
else
{
ret += "There is no facility in this fieldset.";
ret += "</fieldset>";
}
}
}
return ret;
}
by this code i load some checkboxes in a DIV,then user change some checkboxes and press the SAVE button.at this time ,i should send the values of these checkboxes to server to update my data in database.by i dont know how?:( please help
note: my default code for this probem is here but it does not work($("#FacilitiesDIV input[type=checkbox]").serializeArray() is empty)
$.ajax({
type: "POST",
url: "HotelsList.aspx/SaveFacilities",
data: "{ 'id' : '" + $("#HiddenField").val() + "', 'Facilities' : '" + $("#FacilitiesDIV input[type=checkbox]").serializeArray() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function () {
$('#dialogMessage').dialog('open');
$('#dialogMessage span').html("Operation Error");
}
});
$("#FacilitiesDIV input[type=checkbox]").serializeArray() since you are referring element using "#" then you need to give the fieldset element an Unique ID assuming you have
html like
<fieldset> <input type='checkbox' checked='false' /> some text
<input type='checkbox' checked='false' /> some text
</fieldset>
set the id to element <fieldset id = 'FacilitiesDIV'>
I believe it should work if you give each checkbox a name, ie:
<input type='checkbox' checked='false' name="mycheckboxes" />

Categories