I have a search form with several autocomplete fields.
When the page loads first time, everything works nicely, but if I reload/press F5 all the fields with minLength: 0 are triggered even though none gets or have focus.
No other action causes this.
function autocompleter(searchfield, autocompletee) {
$(searchfield)
.autocomplete({
minLength: autocompletee.minLength,
source: autocompletee.array,
change: function(event, ui) {
if (!ui.item) {
event.target.value = "";
}
},
select: function (event, ui) {
var chosenWord = ui.item.label;
var searchKeyWord = {
"webformField": autocompletee.selected,
"searchString": chosenWord
};
$.ajax({
contentType: "application/json; charset=utf-8",
type: 'POST',
url: "MyHandler.ashx",
data: JSON.stringify(searchKeyWord),
});
var title = ui.item.label; //get the object title here
$(searchfield).val(title);
$(autocompletee.chosen).append("<asp:HyperLink href='#' class='myClass' runat='server' ID='" + chosenWord + "'>" + chosenWord + "</asp:HyperLink>"); //
$(searchfield).val("");
$(searchfield).blur();
return false;
}
}).focus(function() {
$(this).autocomplete("search", "");
});
}
$(document).ready(function() {
var myObject = {
array: window.myarray,
selected: "object_chosen",
chosen: "#object_chosen",
minLength: 0,
};
autocompleter('#inputField, myObject);
});
<input type="text" id="inputField" placeholder="Text" runat="server" clientidmode="Static" />
<asp:Panel ID="object_chosen" CssClass="chosen-tag-container" ClientIDMode="Static" runat="server">
<%-- links appear here--%>
</asp:Panel>
Try This
$(document).ready(function() {
var myObject = {
array: window.myarray,
selected: "object_chosen",
chosen: "#object_chosen",
minLength: 0,
};
autocompleter("#inputField", myObject); //Remove this because it's calling that function on page load
});
Related
I am having issue in displaying a widget inside a modal on ASP.NET MVC platform. Currently, the widget is showing at the back of my modal.
#Html.TextBoxFor(Function(model) model.Clinic, New With {.Style = "width:300px", .id = "txtClinic"})
Widget
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_create: function () {
this._super();
this.widget().menu("option", "items", "> :not(.ui-widget-header)");
},
_renderMenu: function (ul, items) {
var self = this,
thead;
if (this.options.showHeader) {
table = $('<div class="ui-widget-header" style="width:100%"></div>');
$.each(this.options.columns, function (index, item) {
table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
$.each(items, function (index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function (ul, item) {
var t = '',
result = '';
var term = this.term;
$.each(this.options.columns, function (index, column) {
var value = item[column.valueField ? column.valueField : index];
t += '<span style="padding:0px 4px;float:left;width:' + column.width + ';height:13px;">' + value + '</span>'
});
var $a = '<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>';
result = $('<li style="border-bottom: solid 1px #cccccc"></li>')
.data('ui-autocomplete-item', item)
.append($a)
.appendTo(ul);
return result;
}
});
Ajax
$("#txtClinic").mcautocomplete({
showHeader: true,
columns: [{
name: 'Code',
width: '120px',
valueField: 'ClinicCode'
}, {
name: 'Clinic Name',
width: '370px',
valueField: 'Clinic'
}
],
minLength: 3,
source: function (request, response) {
$.ajax({
cache: false,
url: '/User/GetClinicAllDetails',
type: "POST",
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
ClinicCode: item.ClinicCode,
Clinic: item.Clinic
}
}));
},
error: function (response) {
swal("", response.message, "error");
}
});
}
});
All the codes are listed in my Modal View, any ideas what could went wrong?
For anyone who is having the same issue as me.
Simply add the following line to the widget portion:
$(".ui-autocomplete.ui-front.ui-menu.ui-widget.ui-widget-content").addClass("zindex9999");
In your style:
.zindex9999{z-index:9999 !important;}
The reason of doing so is because when a modal is opened, the position is set to absolute and it neglect all the existing div, by setting z-index to 9999, it actually overwrites the absolute index as the absolute index is around 9998 (I'm not sure)
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<table id="tblAttachment"> </table>
<input id="btnSubmit" type="button" value="button" />
</form>
</body>
Dynamically inserting a FileUpload Control
<script>
$(document).ready(function () {
var MaxAttachment = 1;
$("#tblAttachment").append('<tr><td><input id=\"Attachment_' + MaxAttachment.toString() + '\" name=\"file\" type=\"file\" /><br><a class=\"MoreAttachment\">Additional Attachment</a></td></tr>');
$("#btnSubmit").on("click", UploadFile);
});
</script>
Sending Data to .ashx using Jquery
function UploadFile() {
var kdata = new FormData();
var i = 0;
//run through each row
$('#tblAttachment tr').each(function (i, row) {
var row = $(row);
var File = row.find('input[name*="file"]');
alert(File.val());
kdata.append('file-' + i.toString(), File);
i = i + 1;
});
sendFile("fUpload.ashx", kdata, function (datad) {
}, function () { alert("Error in Uploading File"); }, true);
}
On .ashx Count always Zero ??
public class fUpload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int k = context.Request.Files.Count;
context.Response.Write(UploadMultipleFiles());
}
Ajax Request
function sendFile(requestUrl, dataPayload, successfunc, errorfunc, synchronousMode) {
$.ajax({
url: requestUrl,
type: "POST",
dataType: "json",
contentType: false,
processData: false,
cache: false,
async: synchronousMode,
data: dataPayload,
success: successfunc,
error: errorfunc
});
}
Please Check .. where i m doing wrong
form tag having enctype="multipart/form-data" and each fileUPload control have uniue id and name attribute too
Thanks
You're sending a jQuery object, not a file ?
Shortened down, you're basically doing this
var kdata = new FormData();
var File = row.find('input[name*="file"]'); // jQuery object
kdata.append('file-0', File);
You need the files, not the jQuery objects
var kdata = new FormData();
var File = row.find('input[name*="file"]'); // jQuery object
var files = File.get(0).files[0]; // it not multiple
kdata.append('file-0', Files);
I have a form on which I am adding rows dynamically using Jquery.
Please take a look: DEMO
Now I want to save the data of all rows that has been added in my database using Jquery Ajax call on click event of SAVE button. The point where I am stuck is .. I am not sure how should I extract data of all rows and send it to the webmethod. I mean had it been c# I could have used a DataTable to store data of all rows before sending it to DataBase. I think I should create a string seperated by commas and pipe with data of each row and send it to webmethod. I am not sure if its the right approach and also how this is to be done (ie. creating such a string).
HTML
<table id="field">
<tbody>
<tr id="row1" class="row">
<td> <span class='num'>1</span></td>
<td><input type="text" /></td>
<td><select class="myDropDownLisTId"> <input type="text" class="datepicker" /></select></td><td>
<input type="submit"></input>
</td>
</tr>
</tbody>
</table>
<button type="button" id="addField">Add Field</button>
<button type="button" id="deleteField">Delete Field</button>
<button type="button" id="btnsave">SAVE</button>
2 suggestions:
To keep it as close as what you already have, you could just enclose your table in a form tag, and then you could just submit the form (use something like the jQuery Form plugin to submit it via Ajax). The trickiest part will be to bind that data to action parameters. You may be able to receive it in the form of an array, or you could default to looping through properties of the Request.Form variable. Make sure you generate proper names for those fields.
I think the cleanest way to do it would be to have a JavaScript object holding your values, and having the table generated from that object, with 2-way bindings. Something like KnockoutJS would suit your needs. That way the user enters the data in the table and you'll have it ready to be Json-serialized and sent to the server. Here's a quick example I made.
I wouldn't recommend that approach, but if you wanted to create your own string, you could do something along those lines:
$("#btnsave").click(function () {
var result = "";
$("#field tr").each(function (iRow, row) {
$("td input", row).each(function (iField, field) {
result += $(field).val() + ",";
});
result = result + "|";
});
alert(result);
});
You will have problems if the users types in a comma. That why we use well known serialization formats.
use ajax call on save button event...
like this
$(document).ready(function () {
$('#reqinfo').click(function () {
// debugger;
var emailto = document.getElementById("emailid").value;
if (emailto != "") {
$.ajax({
type: "GET",
url: "/EmailService1.svc/EmailService1/emaildata?Email=" + emailto,
// data: dat,
Accept: 'application/json',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// debugger;
},
error: function (result) {
// debugger;
}
});
}
else {
//your validation message goes here
return false;
}
});
});
and add you all data in quesry string and transfer it to webservice..
url: "/EmailService1.svc/EmailService1/emaildata?Email=" + emailto + "data1=" + data1,
<script type="text/javascript">
var _autoComplCounter = 0;
function initialize3(_id) {
var input_TO = document.getElementById(_id);
var options2 = { componentRestrictions: { country: 'ID' } };
new google.maps.places.Autocomplete(input_TO, options2);
}
google.maps.event.addDomListener(window, 'load', initialize3);
function incrementValue() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').value = value;
}
function GetDynamicTextBox(value) {
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
return '<input name = "DynamicTextBox" type="text" id="' + _id + '" value = "' + value + '" onkeypress = "calcRoute();" />' +
'<input type="button" class="superbutton orange" value="Remove" onclick = "RemoveTextBox(this)" />'
}
function AddTextBox() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
if (document.getElementById('number').value < 3) {
document.getElementById('number').value = value;
var div = document.createElement('DIV');
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
var ht = '<input name = "DynamicTextBox" type="text" id="' + _id + '" value = "" onkeypress = "calcRoute();" class="clsgetids" for-action="' + _id + '" />' +
'<input type="button" class="superbutton orange" value="#Resources.SearchOfferRides.btnRemove" onclick = "RemoveTextBox(this); calcRoute();" />';
div.innerHTML = ht;
document.getElementById("TextBoxContainer").appendChild(div);
setTimeout(function () {
var input_TO = document.getElementById(_id);
var options2 = { componentRestrictions: { country: 'ID' } };
new google.maps.places.Autocomplete(input_TO, options2);
}, 100);
document.getElementById("TextBoxContainer").appendChild(div);
}
else {
alert('Enter only 3 stop point. !!');
}
}
function RemoveTextBox(div) {
//calcStopPointRoute();
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value--;
document.getElementById('number').value = value;
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
// window.onload = RecreateDynamicTextboxes;
</script>
And get the value from textbox:
#region stop point
string[] textboxValues = Request.Form.GetValues("DynamicTextBox");
if (textboxValues != null)
{
for (Int32 i = 0; i < textboxValues.Length; i++)
{
if (textboxValues.Length == 1)
{
model.OptionalRoot = textboxValues[0].ToString();
}
else if (textboxValues.Length == 2)
{
model.OptionalRoot = textboxValues[0].ToString();
model.OptionalRoot2 = textboxValues[1].ToString();
}
else if (textboxValues.Length == 3)
{
model.OptionalRoot = textboxValues[0].ToString();
model.OptionalRoot2 = textboxValues[1].ToString();
model.OptionalRoot3 = textboxValues[2].ToString();
}
else
{
model.OptionalRoot = "";
model.OptionalRoot2 = "";
model.OptionalRoot3 = "";
}
}
}
#endregion
Short answer:
DataTable equivalent in javascript is Array of custom object (not exact equivalent but we can say that)
or
you roll your own DataTable js class which will have all the functions and properties supported by DataTable class in .NET
Long answer:
on client side(aspx)
you define a class MyClass and store all your values in array of objects of that class
and then pass that array after stingyfying it to web method
JSON.stringify(myArray);
on the server side(codebehind)
you just define the web method to accept a list of objects List<MyClass>
PS: When calling web method, Asp.net automatically converts json array into List<Object> or Object[]
Loooong answer (WHOLE Solution)
Page aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="App_Themes/SeaBlue/jquery-ui-1.9.2.custom.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.8.3.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.9.2.custom.min.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>
<script type="text/javascript">
function MyClass(title,option,date) {
this.Title = title;
this.Option = option;
this.Date = date;
}
function GetJsonData() {
var myCollection = new Array();
$(".row").each(function () {
var curRow = $(this);
var title = curRow.find(".title").val();
var option = curRow.find(".myDropDownLisTId").val();
var date = curRow.find(".datepicker").val();
var myObj = new MyClass(title, option, date);
myCollection.push(myObj);
});
return JSON.stringify(myCollection);
}
function SubmitData() {
var data = GetJsonData();
$.ajax({
url: "testForm.aspx/PostData",
data: "{ 'myCollection': " + data + " }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert("Success");
}
});
}
$(document).ready(function () {
filldd();
CreateDP();
var rowstring = "<tr class='row'><td class='number'></td><td><input type='text' class='title'/></td><td><select class='myDropDownLisTId'/><input type='text' class='datepicker'/></td><td><input type='submit'></input></td></tr>";
$("#addField").click(function (event) {
$("#field tbody").append(rowstring);
filldd();
CreateDP();
if ($("td").hasClass("number")) {
var i = parseInt($(".num:last").text()) + 1;
$('.row').last().attr("id", "row" + i);
$($("<span class='num'> " + i + " </span>")).appendTo($(".number")).closest("td").removeClass('number');
}
event.preventDefault();
});
$("#deleteField").click(function (event) {
var lengthRow = $("#field tbody tr").length;
if (lengthRow > 1)
$("#field tbody tr:last").remove();
event.preventDefault();
});
$("#btnsave").click(function () {
SubmitData();
});
});
function filldd() {
var data = [
{ id: '0', name: 'test 0' },
{ id: '1', name: 'test 1' },
{ id: '2', name: 'test 2' },
{ id: '3', name: 'test 3' },
{ id: '4', name: 'test 4' },
];
for (i = 0; i < data.length; i++) {
$(".myDropDownLisTId").last().append(
$('<option />', {
'value': data[i].id,
'name': data[i].name,
'text': data[i].name
})
);
}
}
function CreateDP() {
$(".datepicker").last().datepicker();
}
$(document).on('click', 'input[type="submit"]', function () {
alert($(this).closest('tr')[0].sectionRowIndex);
alert($(this).closest('tr').find('.myDropDownLisTId').val());
});
</script>
</head>
<body>
<form id="frmMain" runat="server">
<table id="field">
<tbody>
<tr id="row1" class="row">
<td>
<span class='num'>1</span>
</td>
<td>
<input type="text" class="title"/>
</td>
<td>
<select class="myDropDownLisTId">
</select>
<input type="text" class="datepicker" />
</td>
<td>
<input type="submit"></input>
</td>
</tr>
</tbody>
</table>
<button type="button" id="addField">
Add Field</button>
<button type="button" id="deleteField">
Delete Field</button>
<button type="button" id="btnsave">
SAVE</button>
</form>
</body>
</html>
CodeBehind:
public partial class testForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void PostData(List<MyClass> myCollection)
{
Console.WriteLine(myCollection.Count);
}
}
public class MyClass
{
string title;
public string Title
{
get { return title; }
set { title = value; }
}
string option;
public string Option
{
get { return option; }
set { option = value; }
}
string date;
public string Date
{
get { return date; }
set { date = value; }
}
}
Hope this helps
References:
Json2.js file
stringify method
define a class in js
My javascript is getting locked after ajax call.
When the user press enter then i call my c# method to search the city that the user typed, and then show the temperature, but when the search ends, the javascript stops working. And i found out that the error is on these lines:
var div = document.getElementById('rb-grid');
div.innerHTML = resp.responseText + div.innerHTML;
code:
$(document).ready(function () {
$('#search-bar').keyup(function (event) {
if (event.keyCode == 13) {
myFunction();
}
});
function myFunction() {
var city = $('#search-bar').val();
$.ajax({
url: '#Url.Action("getWeatherSearch", "Index")',
data: { city: city },
async: false,
complete: function (resp) {
var div = document.getElementById('rb-grid');
div.innerHTML = resp.responseText + div.innerHTML;
Boxgrid.init();
}
});
} });
HTML:
<div align="center" class="div-search-bar">
#Html.TextBox("search-bar", "", new { #class = "search-bar", placeholder = "search" })
</div>
Try the following and see if it works for you:
$(function () {
var $searchbar = $('#search-bar'),
$grid = $('#rb-grid');
if ($grid.length) {
$searchbar.on('keyup', function (event) {
if (event.keyCode == 13) {
myFunction();
}
});
function myFunction() {
var city = $searchbar.val();
$.ajax({
url: $.grid.data('weather-url'),
data: { city: city }
})
.done(function (resp) {
$grid.html(resp.responseText + $grid.html());
Boxgrid.init();
}
});
}
}
});
Add the following as a data attribute somewhere in your html, probably on your grid:
<div id='rb-grid' data-weather-url='#Url.Action("getWeatherSearch", "Index")'></div>
Using .NET here's what I've got.. The right results are returned, but they're all combined together into one long string. How can I make it so I can select one item at a time from the results returned? I know my source in the javascript is configured incorrectly. Any help would be appreciated. Thanks
Code behind:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string[] GetEmails(string emailContains)
{
LoginSet logins = staticLogic.searchLogins(staticClient, new SearchCriteriaSet());
List<BaseEntry> loginList = logins.Where(x => ((LoginEntry)x).LoginEMail.Contains(emailContains)).ToList();
List<string> emails = new List<string>();
for (int i = 0; i < loginList.Count(); ++i)
{
string email = ((LoginEntry)loginList.ElementAt(i)).LoginEMail;
emails.Add(email);
}
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//string json = serializer.Serialize(emails.ToArray());
return emails.ToArray();
}
UI:
<tr><td>Destination:</td>
<td>
<div class="ui-widget">
<input type="text" name="EMailReportDestination" id="EMailReportDestination" size="60" runat="server" />
</div>
</td>
</tr>
JQuery:
$('#EMailReportDestination').autocomplete({
source: function (request, response) {
$.ajax({
url: '/reports/editemailreport.aspx/GetEmails',
type: 'POST',
dataType: 'json',
data: "{'emailContains':'" + request.term + "'}",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
//console.log('autocomplete success: ' + data);
response($.map(data, function (item) {
return {
label: item,
value: item
}
}));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("autocomplete error: " + xhr.status + ", " + thrownError);
}
});
},
minLength: 2,
select: function (event, ui) {
console.log(ui.item ? "selected: " + ui.item.label : "nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
I tried and I don't know array returned in data.d. try to change
response($.map(data, function (item)
to
response($.map(data.d, function (item)