Autocomplete is not working after Postback in mvc - javascript

In my mvc application i'm appending jquery autocomplete to the searchbox. my problem is at first time autocomplete is working fine. it shows the related items when ever we type in the searchbox. after selecting one of the item it will redirect to another page. where the searchbox autocomplete is not working.
Here is my code:
View:
<div id="targetDiv">
#Html.TextBox("name", null, new { id = "SearchBox", #class = "SearchBox" })
</div>
Javascript code:
<script type="text/javascript">
function load() {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(getItems);
}
$(document).ready(function () {
//We have used keyup event to track the user enter value in the textbox.
$("#SearchBox").keyup(function () {
//Fetching the textbox value.
var query = $(this).val();
//Calling GetItems method.
getItems(query);
});
function getItems(query) {
//var path = '#Url.Action("Suggest", "Home")';
//Here we are using ajax get method to fetch data from the list based on the user entered value in the textbox.
//We are sending query i.e textbox as data.
$.ajax({
url: '#Url.Action( "RemoteData", "Home")',
data: { "query": query },
type: 'POST',
dataType: 'json',
success: function (response) {
if (response.Data != null) {
if ($("#targetUL") != undefined) {
//If the UL element is not null or undefined we are clearing it, so that the result is appended in new UL every next time.
$("#targetUL").remove();
}
//assigning json response data to local variable. It is basically list of values.
data = response.Data;
//appending an UL element to show the values.
$("#targetDiv").append($("<ul id='targetUL'></ul>"));
//Removing previously added li elements to the list.
$("#targetUL").find("li").remove();
//We are iterating over the list returned by the json and for each element we are creating a li element and appending the li element to ul element.
$.each(data, function (i, value) {
//On click of li element we are calling a method.
$("#targetUL").append($("<li class='targetLI' onclick='javascript:appendTextToTextBox(this)'>" + value + "</li>"));
});
}
else {
//If data is null the we are removing the li and ul elements.
$("#targetUL").find("li").remove();
$("#targetUL").remove();
}
},
error: function (xhr, status, error) {
}
});
}
});
//This method appends the text oc clicked li element to textbox.
function appendTextToTextBox(e) {
//Getting the text of selected li element.
var textToappend = e.innerText;
//setting the value attribute of textbox with selected li element.
$("#SearchBox").val(textToappend);
//Removing the ul element once selected element is set to textbox.
$("#targetUL").remove();
}
</script>
controller code:
[HttpPost]
public ActionResult RemoteData(string query)
{
ArrayList list = new ArrayList();
SearchModel searchmodel = new SearchModel();
DataTable dt = new DataTable();
dt = searchmodel.FilteredSearchProductDisplay(query, 5, 0);
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
list.Add(dr["ProductName"]);
}
}
return Json(new { Data = list });
}
Redirected-Page:
if (#Model.dtProduct.Rows.Count > 0)
{
<div style="width:100%; height:auto;">#Html.Raw(#Model.dtProduct.Rows[0]["ThumbnailFilename"])</div>
<br />
if (ViewBag.RedirectedFromPage == "Search" || ViewBag.RedirectedFromPage == "OfferProduct")
{
if (#Model.dtProduct.Rows[0]["Stock"].ToString().Length > 0)
{
<table id ="priceTable">
<tr>
#if(#offerPrice > 0)
{
<td style="width:10%" class="divSizehPrice"><label>#Html.Raw(#Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])#APrice.ToString("0.00")</label></td>
<td style="width:90%" class="divSizehPrice"><label>RRP </label><p>#Html.Raw(#Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])#Price.ToString("0.00")</p></td>
}
else
{
<td colspan=2 style="width:90%" class="divSizehPrice"><p>#Html.Raw(#Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])#APrice.ToString("0.00")</p></td>
}
</tr>
</table>
<div id="divPrice2"style="display:none">
<table>
<tr>
<td>#Html.Raw(#Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])</td>
<td><div id="PriceDiv2"></div></td>
</tr>
</table>
</div>
<br />
Change currency
<br />
Add to Shopping Cart
}
else
{
using (Html.BeginForm("SelectedProductDisplay", "Product", FormMethod.Post, new { ProductId = #Model.dtProduct.Rows[0]["ProductId"], ProductpriceId = #Model.dtProduct.Rows[0]["ProductPriceId"] }))
{
<b>Out of stock</b>
<br />
#*<p>Please enter your email address below and we will contact you when it comes back in to stock.</p>
<br />
<label>Email:</label> #Html.TextBoxFor(m => m.OutOfStockEmail, new { id = "emailid" })
<br />
<div id="erroremail" class="validationColor" style="width:100%; text-align:center"></div>
<label>#Model.OutOfStockStatus</label>
<input type="submit" value="Notify Me" onclick="return checkEmail()"/>*#
}
Continue Shopping
}
<br />
<div class="divSearchHeader">
<p>#Html.Raw(Model.dtProduct.Rows[0]["ProductName"])</p>
<br />
</div>
<div class="divSearchContent">
#Html.Raw(#Model.dtProduct.Rows[0]["ProductDescription"])
</div>
<div class="divSearchContent">
#Html.Raw(#Model.dtProduct.Rows[0]["Description"])
</div>
}
else
{
<table style="width:100%" id="priceTable1">
#if (offerPrice > 0)
{
<tr>
<td style="width:25%"><div class="divSizehPrice">#APrice.ToString("0.00")</div></td>
<td style="width:75%"><div class="divSizehPrice"><p><label>RRP </label>#Price.ToString("0.00")</p></div></td>
</tr>
}
else
{
<tr>
<td colspan=2 class="divSizehPrice"><p>#Html.Raw(#Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])#APrice.ToString("0.00")</p></td>
</tr>
}
</table>
<div id="divPrice1"style="display:none" class="divSizehPrice">
<table>
<tr>
<td>#Html.Raw(#Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])</td>
<td><div id="PriceDiv1"></div></td>
</tr>
</table>
</div>
<br />
Change currency
<br />
Add to Shopping Cart
<br />
<div class="divSearchHeader">
<p>#Html.Raw(Model.dtProduct.Rows[0]["Name"])</p>
<br />
</div>
<div class="divSearchContent">
#Html.Raw(#Model.dtProduct.Rows[0]["Description"])
</div>
}
}
else
{
<p>No records found.</p>
}

Please use live instead simple keyup:
$('selector').live('keyup',function(){
//your code
});

Try :
$('sel').on('keyup',function(){
//your code
});

Please try this
$("body").delegate("selector","keyup",function(e){//your code.})

Try this:
$('selector').on('input', function(){
// Do your stuff here
});
Check the 'input' event,

I have also used Jquery AutoComplete Search Box it is working fine the only difference is in Controller Code
public ActionResult Autocomplete(string term)
{
// Return the Result list store in searchResultList
return Json(searchResultList, JsonRequestBehavior.AllowGet);
}
Removed Httpost Attribute
While Returning Json, use the 2nd Overload Method JsonRequestBehavior.AllowGet
Hope it helps you, Please note I am using MVC4 VS 2010

Related

Show checkboxes that are already checked by getting the information from database

I have created a method in my asp project where I can select a garage and fill in some checkboxes that I want associated with the garage. These are stored in a database cross table. Here's the table structure:
SELECT [ID]
,[GarageID]
,[RequestProperty]
,[Active]
,[CreatedDate]
,[CreatedBy]
,[UpdatedDate]
,[UpdatedBy]
FROM [dbo].[GarageCrossRequestType]
Example data after checkboxes are sent:
ID GarageID RequestProperty Active
299 64043 1 1
Now, I would like these checkboxes to be crossed/checked by getting the information from the database, so for example when choosing garage with id 64043 the box for requestproperty with value 1 should be checked/crossed. I have created a c# method for getting the information from the database like following:
public List<GarageModel> getRequestType(int garageId)
{
var rModel = new List<GarageModel>();
try
{
string sql = "SELECT GarageID, RequestProperty FROM¨
GarageCrossRequestType WHERE GarageID = " + garageId;
var cmd = new SqlCommand(sql, Connection);
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
foreach (DataRow i in dt.Rows)
{
var model = new GarageModel();
model.GarageId = Convert.ToInt32(i["GarageID"].ToString());
model.Values = Convert.ToInt32(i["RequestProperty"].ToString());
rModel.Add(model);
}
}
catch(Exception ex)
{
var error = ex.ToString();
}
finally
{
Connection.Close();
}
return rModel;
}
When debugging, this works and I get the correct values. However, I am stuck on how I should proceed to fill the checkboxes? I will share my code on how I send the values to the database and how I fill the checkboxes below. Here's the c# method:
public bool EditGarage(GarageModel model)
{
var valid = false;
var cmd = new SqlCommand("spGarageEditGarage", Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#GarageId", model.GarageId);
cmd.Parameters.AddWithValue("#Email", model.Email);
cmd.Parameters.AddWithValue("#Note", model.Note);
try
{
int result = cmd.ExecuteNonQuery();
if (result == 1)
valid = true;
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
finally
{
Connection.Close();
}
// Add request types for garage when editing garage
if (model.garageCrossRequestType != null) {
foreach (var item in model.garageCrossRequestType)
{
var cmd1 = new SqlCommand("spGarageGetRequestTypes", Connection);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#GarageId", model.GarageId);
cmd1.Parameters.AddWithValue("#RequestType", item);
cmd1.Parameters.AddWithValue("#Active", 1);
int result = cmd1.ExecuteNonQuery();
if (result == 1)
valid = true;
}
}
return valid;
}
Html(Index):
#foreach (var items in Model)
{
<style>
.ab{
margin-right: 8px;
}
</style>
<div style=" width: 40%; display: block; float: right; margin-right: 10%; margin-top: 10%;">
<h4>Choose request types for garage:</h4><br />
<div class='form-group'>
<div class="rowa">
<label class="ab">Claim</label>
<input type="checkbox" class="checkbclass" name="#items.Claim" id="#items.Claim" placeholder="Tires" value="1" /> <!-- values for request type -->
</div>
</div>
<div class='form-group'>
<div class="rowa">
<label class="ab">Scheduled Service</label>
<input type="checkbox" class="checkbclass" name="#items.ScheduledService" id="#items.ScheduledService" placeholder="Scheduled" value="2" />
</div>
</div>
<div class='form-group'>
<div class="rowa">
<label class="ab">Tires</label>
<input type="checkbox" class="checkbclass" name="#items.Tires" id="#items.Tires" placeholder="Tires" value="3" />
</div>
</div>
<div class='form-group'>
<div class="rowa">
<label class="ab">Rent Replacement Car</label>
<input type="checkbox" class="checkbclass" name="#items.RentRepalcementCar" id="#items.RentRepalcementCar" placeholder="Tires" value="4" />
</div>
</div>
<div class='form-group'>
<div class="rowa">
<label class="ab">Other Work</label>
<input type="checkbox" class="checkbclass" name="#items.OtherWork" id="#items.OtherWork" placeholder="Tires" value="5" />
</div>
</div>
<div class='form-group'>
<div class="rowa">
<label class="ab">Insurance</label>
<input type="checkbox" class="checkbclass" name="#items.Insurance" id="#items.Insurance" placeholder="Tires" value="6" />
</div>
</div><br />
</div>
}
JavaScript/Jquery:
$("#EditGarageBtn").click(function () {
var customerNumber = customerNumberOfEditingGarage;
name = $("#GarageName").val();
countryId = $("#Country").val();
var garageId = $("#garageId").val();
var note = $("#Note").val();
var email = $("#Email").val();
var garageCrossRequestType = $(".checkbclass:checked").map(function () {
return $(this).val(); // to see which request types are checked
}).toArray();
console.log(garageCrossRequestType);
$("#EditGarageBtn").hide();
if (countryId == "Norway")
countryId = 2;
if (countryId == "Finland")
countryId = 4;
if (name.length > 0 && email.length > 0 && phone.length > 0 && contactperson.length > 0) {
$.ajax({
url: '#Url.Action("EditGarage", "Garage")',
type: 'POST',
dataType: 'JSON',
data: {
garageCrossRequestType: garageCrossRequestType,
name: name, countryId: countryId, garageId: garageId,
note: note, email: email
},
success: function (data) {
if (data == "Failure") {
toastr["error"]("Error editing Garage");
}
else {
toastr["success"]("Garage successfully updated");
customerNumberOfEditingGarage = null;
refreshGrid();
}
},
error: function () {
}
});
} else {
toastr["error"]("Error editing Garage");
}
});
Now, I've tried doing a ajax call similar to the code above to at least get the data from the database when using console.log, but I can't seem to get the data from the controller to the index either. So I guess what I need help with is 1. How I can get the data that I get in my c# method to show in the view and 2. How can I connect this so that the correct checkboxes gets checked with the values? Or maybe I am completly off and there's a simpler way to do this?
Thankful for any help!
UPDATE: So I created added this Ajax call:
$.ajax({
type: "POST",
url: '#Url.Action("getRequestType", "Garage")?garageId=' + garageId,
dataType: 'JSON',
data: {
garageId: garageId, Values: Values
},
sucess: function (data) {
if (data != "Failure") {
//return garageId, value;
}
}
}); console.log(garageId, Values);
It works etcetera, I can see in the console log that I can get the garageId and the Value. However (lol) the problem now is that I can test for example in the model like this:
public int Values { get; set; } = 5;
which will result in showing a number 5 and the correct garageid when i use console log. But the values from the method getRequestType does not seem to connect to the model. As seen I use a foreach loop in the method and set model.Values with the database value from RequestProperty. So If I set the model to:
public int? Values { get; set; } = null;
for example, It will show null etcetera. So something is clearly not working correctly. I can't seem to figure out what about the method is wrong however, so again very thankful for any help!! (Classic programming solving one problem but finding another one lol)
Well, I think a listView works better.
and for the list of selections, use a checkBoxlist.
So we have
tblGarage - our list of garages
tblitemsInGarge - list of times in each garage
tblItems - our list of possible choices.
So, say this markup:
<asp:ListView ID="LvGarage" runat="server" DataKeyNames="ID" OnItemDataBound="LvGarage_ItemDataBound" >
<ItemTemplate>
<tr style="">
<td><asp:Label ID="GarageNameLabel" runat="server" Text='<%# Eval("GarageName") %>' /></td>
<td><asp:Label ID="GarageTypeLabel" runat="server" Text='<%# Eval("GarageType") %>' /></td>
</tr>
<tr>
<td colspan="2">
<h4>Items in Garage</h4>
<asp:CheckBoxList ID="ckList" runat="server"
CellPadding="10" CellSpacing="20"
DataTextField="ItemName" DataValueField="ID"
RepeatDirection="Horizontal"></asp:CheckBoxList>
<hr style="border:solid;border-top:1px"/>
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" Class="table table-hover">
<tr runat="server" style="">
<th runat="server">GarageName</th>
<th runat="server">GarageType</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
<br />
<asp:Button ID="cmdSave" runat="server" Text="Save Changes" CssClass="btn-default" OnClick="cmdSave_Click" />
And we now load ListView, but for each row, we pull choices from the database.
(row data bound).
So, our code to load is thus this:
DataTable rstItems = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadMyView();
}
public void LoadMyView()
{
rstItems = MyRst("SELECT ID, ItemName from tblItems ORDER BY ItemName");
LvGarage.DataSource = MyRst("SELECT * From tblGarage ORDER BY GarageName");
LvGarage.DataBind();
}
public DataTable MyRst(string strSQL)
{
var rst = new DataTable();
using (SqlCommand cmdSQL = new SqlCommand(strSQL,
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
// fill items table
rst.Load(cmdSQL.ExecuteReader());
}
return rst;
}
But, we need on Row data bind to fill out the check box list (the table of choices), and ALSO set the selected ones (from tbleItemsInGarage).
We have this:
protected void LvGarage_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
CheckBoxList ckList = (CheckBoxList)e.Item.FindControl("ckList");
ckList.DataSource = rstItems;
ckList.DataBind();
// now get all rows for this garage
int ID = (int)LvGarage.DataKeys[e.Item.DataItemIndex]["ID"];
DataTable rstItemsChecked = new DataTable();
rstItemsChecked = MyRst("SELECT * FROM tblItemsInGarage WHERE Garage_ID = " + ID);
foreach (DataRow OneRow in rstItemsChecked.Rows)
ckList.Items.FindByValue(OneRow["Item_ID"].ToString()).Selected = true;
}
}
And the output is now this:
All we need now, is a single save button to send any changes you make back to the database. And that code looks like this:
protected void cmdSave_Click(object sender, EventArgs e)
{
foreach (ListViewItem lvRow in LvGarage.Items)
{
// now get all rows for this garage
int ID = (int)LvGarage.DataKeys[lvRow.DataItemIndex]["ID"];
string strSQL = "SELECT ID, Item_ID, Garage_ID FROM tblItemsInGarage WHERE Garage_ID = " + ID;
using (SqlCommand cmdSQL = new SqlCommand(strSQL,
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
SqlDataAdapter dUpdate = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder sUpdate = new SqlCommandBuilder(dUpdate);
DataTable rstItemsChecked = new DataTable();
rstItemsChecked.Load(cmdSQL.ExecuteReader());
// remove all selected
foreach (DataRow OneRow in rstItemsChecked.Rows)
OneRow.Delete();
// now add back ONLY checked items
CheckBoxList ckList = (CheckBoxList)lvRow.FindControl("ckList");
foreach (ListItem citem in ckList.Items)
{
if (citem.Selected)
{
DataRow OneRow = rstItemsChecked.NewRow();
OneRow["Item_ID"] = citem.Value;
OneRow["Garage_ID"] = ID;
rstItemsChecked.Rows.Add(OneRow);
}
}
dUpdate.Update(rstItemsChecked);
}
}
}
Now a bit of code, but not too much!!!
Using listview, dropping in that checkBox list and DRIVING the checkbox list from the table of choices.
We get:
not a lot of markup
not a lot of code to load
But REALLY make gains in the database update process.
All in all, not a lot of code, given that we have to pull + push back the selecting from that check box list.

JavaScript not updating value from HTML

I have a small problem. This is my HTML code fragment:
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr th:each="boiler : ${boilers}">
<td th:text="${boiler.value[0].model}"></td>
<td th:text="${boiler.value[0].brand}">
<td th:text="${#lists.size(boiler.value)}"></td>
<td th:text="${boiler.value[0].price}"></td>
<td>
<form>
<input type="text" th:class="boiler_model" th:id="boiler_model"
th:value="${boiler.value[0].model}" style="width:75px;"/>
<input class="form-control" type="number" id="quantity" style="width: 80px"/>
</form>
<td>
<button type="submit" class="btn btn-primary btn_submit" th:text="Add">Add</button>
</td>
</tr>
</tbody>
</table>
this is my jQuery:
$(document).ready(function () {
$('.btn_submit').on("click", function (e) {
e.preventDefault();
var quantity = $("#quantity").val();
// var boilerModel = $(".boiler_model").val();
var boilerModel = document.getElementById('boiler_model').value;
if (quantity === 0) {
alert("You must fill the quantity");
}
else if ($.trim(boilerModel) === "") {
alert("You must choose the model");
}
else {
var productIds = [];
$.ajax({
type: "POST",
url: "/order",
data: {quantity: quantity, model: boilerModel},
success: function (data) {
window.reload();
}
});
}
});
My problem is when I click the button it does read the quantity, but only reads the first model, even though it is printed in input correctly. I even removed the "hidden" type so I could see it for myself.
As you can see - the input is printed correctly, but when I debug this the controller always receives a quantity that is null if clicked on 2nd or 3rd model, but correct for the first one and model that is always the same. It always is "Super Hot Premium".
Could you please help me modify the table so it reads input separately from each row and then sends it to my controller?
Thank you very much.
There are several issues with your code :
you are looping through your boilers collection and generating a row for each loop. Each row contains two input fields with the same ids : quantity and boiler_model
in your click event handler, you are not looping through each row to submit data.
To fix this :
Follow this example to keep track of your loop status
Use the row index to generate unique ids for both your input fields
Store the size of your boilers collection in some hidden field to be able to send data from all rows
In your event handler, retrieve the size of your boilers collection and retrieve/send data for each row.
Here is a suggestion for your template (please note that I haven't tested it) :
<tr th:each="boiler, iterStatus : ${boilers}">
<td th:text="${boiler.value[0].model}"></td>
<td th:text="${boiler.value[0].brand}">
<td th:text="${#lists.size(boiler.value)}"></td>
<td th:text="${boiler.value[0].price}"></td>
<td>
<form>
<input type="text" th:class="boiler_model" id="boiler_model_${iterStatus.index}"
th:value="${boiler.value[0].model}" style="width:75px;"/>
<input class="form-control" type="number" id="quantity_${iterStatus.index}" style="width: 80px"/>
</form>
<td>
<button type="submit" class="btn btn-primary btn_submit" th:text="Add">Add</button>
</td>
</tr>
<input type="hidden" id="boilersLength" th:value="${#lists.size(boilers)}"/>
And your event handler :
$(document).ready(function () {
$('.btn_submit').on("click", function (e) {
var quantity, boilerModel, boilersLength, i;
e.preventDefault();
// retrieving the length of the boilers collection
boilersLength = $("#boilersLength").val();
// looping and sending data for each row :
for (i=0;i<boilersLength;i++) {
// retrieving data from both inputs :
quantity = $("#quantity_" + i).val();
boilerModel = $("#boiler_model_" + i).val();
if (quantity === 0) {
alert("You must fill the quantity");
}
else if ($.trim(boilerModel) === "") {
alert("You must choose the model");
}
else {
var productIds = [];
$.ajax({
type: "POST",
url: "/order",
data: {quantity: quantity, model: boilerModel},
success: function (data) {
// I wouldn't reload the window here, or you may reload before all data is sent
// window.reload();
}
});
}
}
});
}
You need to send a unique-id to identify on which Row the button is clicked so that you could get those values on your controller on the basis of that 'unique-id'
For Example :--
<tr th:each="boiler : ${boilers}">
<td th:text="${boiler.uniqueID}"></td>
<td th:text="${boiler.value[0].model}"></td>
<td th:text="${boiler.value[0].brand}">
<td th:text="${#lists.size(boiler.value)}"></td>
<td th:text="${boiler.value[0].price}"></td>
//Rest of your Code
<td>
<button type="submit" th:onclick="'javascript:addFunction(\'' + ${boiler.uniqueID} +'\');'" >Add</button>
</td>
</tr>

Change value of disabled checkbox

So I've run across a little snag. I have a page where I have a checkbox being displayed but is disabled (the user can't change it's value due that it's DB driven). Below this checkbox, I have an autocomplete field. Should an item from the autocomplete come back, I need to be able to toggle the value of the disabled checkbox. However, I'm unable to do so at this moment.
Here is my code so far.
View
...
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.IsSpecialOrder):
</td>
<td class="adminData">
#Html.DisplayFor(model => model.IsSpecialOrder)
#Html.HiddenFor(model => model.IsSpecialOrder)
</td>
</tr>
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.ItemNumber):
</td>
<td class="adminData">
#if (Model.Id > 0)
{
#Html.DisplayFor(model => model.ItemNumber)
}
else
{
#Html.EditorFor(model => model.ItemNumber)
}
</td>
</tr>
...
<script type="text/javascript">
...
$("#ItemNumber").autocomplete({
minLength: 2,
source: function (request, response) {
var itemNumber = $("#ItemNumber").val();
//Get available Products based on search parameter and map data
$.getJSON('#Url.Action("GetProductsByItemNumber", "PurchaseOrder")', { searchProduct: itemNumber }, function (data) {
for (var i = 0; i < data.length; i++) {
productData.push({ 'Id': data[i].Id, 'Name': data[i].Name, 'ItemNumber': data[i].ItemNumber, 'Description': data[i].Description,
'IsSpecialOrder': data[i].IsSpecialOrder
});
}
response($.map(data, function (item) {
return {
value: item.ItemNumber,
id: item.Id
};
}));
})
},
select: function (event, ui) {
if (ui.item.id == 0) {
//Do some house cleaning and alert user to mistake
alert("You must retry your search for a Product");
$("#Name").val("");
$("#ItemNumber").val("");
$(".ProductDescription").html("");
document.getElementById("#Html.FieldIdFor(model => model.IsSpecialOrder)").checked = false;
//$("#IsSpecialOrder").prop("checked", false);
return false;
}
//Record ProductId
$("#ProductId").val(ui.item.id);
//Fill RequestorExt with correct data
var description = GetData(productData, ui.item.id, "desc");
var name = GetData(productData, ui.item.id, "name");
var isSpecialOrder = GetData(productData, ui.item.id, "is");
$(".ProductDescription").html(description);
$("#Name").val(name);
document.getElementById("#Html.FieldIdFor(model => model.IsSpecialOrder)").checked = isSpecialOrder;
//$("#IsSpecialOrder").prop("checked", isSpecialOrder);
}
});
...
</script>
From what I've been reading, disabled fields cannot be changed without enabling. I'm guessing that is the only way to fix this but wanted to make sure first. Any ideas?
From what I've been reading, disabled fields cannot be changed without
enabling. I'm guessing that is the only way to fix this but wanted to
make sure first. Any ideas?
Disabled fields can sure be changed see this fiddle. Double check that you have the right value in your js code.
For reference (same code that's on fiddle):
<input type="checkbox" disabled="disabled" checked="checked" id="chkbox"/>
<input type="button" value="Toggle" id="toggle"/>
var chkBox = $("#chkbox");
$("#toggle").click(function(){
if (chkBox.is(':checked')) {
chkBox.prop('checked', false);
}
else {
chkBox.prop('checked', true);
}
});
It does not matter if checkbox is enabled or disabled. You should remove checked attribute from checkbox instead of setting it's checked property to false, otherwise it will remain checked:
document.getElementById("#Html.FieldIdFor(model => model.IsSpecialOrder)").removeAttribute('checked');
Example: http://jsbin.com/izonur/2/edit
disabled items are not submited by the form http://www.w3.org/TR/html401/interact/forms.html#h-17.12
you can have readonly items that are submited with the form (exactly the opposite of what you want)
I guess you are submitting form via a javascript somehow not properly. You must EXCLUDE disabled items from form when submitting, so it will work accordingly.

How to filter table rows based on a not displayed attribute into span

I have a table where each row is an address. Each row has, as well, a zip code but it's hidden.
I need a textbox to filter the address rows that matches with the zip entered. The field to search is named as "zip".
Here's my table:
<asp:DataList
id="list1"
runat="server">
<ItemTemplate>
<cc1:SWCLabel
runat="server"
Text ='<%# Eval("address")%>'
zip='<%# Eval("zip")%>'
/>
</ItemTemplate>
Each table rows is rendered like this, note the zip attribute into the span:
<tr>
<td>
<span zip="11">address mmomo</span>
</td>
</tr>
UPDATED DEMO:
Here's the demo: The zip textbox matches the zip entirely but I need that matches zips that contains or starts with the text entered:
http://jsfiddle.net/QFQ5k/83/
$.expr[':'].containsIgnoreCase = function (n, i, m) {
return jQuery(n).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};
var gridAddr = $("#t1");
var filtroCP = $('#txtbox');
$("#txtbox").keyup(function () {
gridAddr .find("tr").hide();
var data = this.value.split(" ");
var jo = gridAddr .find("tr");
if ($(this).val().length != 0) {
$.each(data, function (i, v) {
jo = jo.filter(function(index){
return $(this).find("span").attr("zip").search($("#txtbox").val())!=-1;
});
});
jo.show();
}
else {
jo.show();
}
});​
Update
If you're sure that any one of the child elements of the row contains the attribute "zip" then use this to filter the rows regardless of their rendering:
instead of
return $(this).find("span").attr("zip").search($("#txtbox").val())!=-1;
write
return $(this).find("[zip*='"+$("#txtbox").val()+"']").length>0;
Check it here: http://jsfiddle.net/QFQ5k/89/
Use linq.js http://linqjs.codeplex.com/
<!DOCTYPE>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.linq.min.js"></script>
</head>
<body>
<table border="1">
<tr><td zip="112233">112233</td></tr>
<tr><td zip="232323">232323</td></tr>
<tr><td zip="454567">454567</td></tr>
</table>
<input type="text" id="filter">
<script>
$('#filter').change(function(){
$("[zip]").show();
$("[zip]").toEnumerable()
.Select( function(x){ return x.attr('zip').indexOf($('#filter').val())==-1 ? x : null})
.TojQuery()
.each(function(){
$(this).hide();
});
});
</script>
</body>
</html>

Apply value to a jquery generated input field

my TD's are generated by grid object on a fly
i'm trying to change value of the fist empty input that is positioned inside :
$("#get_isrc").click(function(){
$.ajax({
url: 'xtras/isrc.php',
success: function(data){
$("#new_isrc").val(data);
$("#get_isrc").val('Apply');
$("#get_isrc").addClass('apply');
}
}).error(function(){
alert('Error');
});
});
$(".apply").live("click", function(){
var s = $("td[col=ISRC] input").val();
if (s === "") {
$(this).val(($("#new_isrc").val()));
}
});
html - static:
<h3>Generate next ISRC</h3>
<input id="new_isrc" type="text" />
<input id="get_isrc" type="button" value="Get next ISRC" />
html generated by jquery:
<tr id="4"><td><input class="editableInput" type="text" /></td><td col="ISRC" class="editableCell"><input class="editableInput " type="text"></td></tr>
<tr id="1"><td><input class="editableInput" type="text" /></td><td col="ISRC" class="editableCell"><input class="editableInput " type="text"></td></tr>
<tr id="2"><td><input class="editableInput" type="text" /></td><td col="ISRC" class="editableCell"><input class="editableInput " type="text"></td></tr>
<tr id="3"><td><input class="editableInput" type="text" /></td><td col="ISRC" class="editableCell"><input class="editableInput " type="text"></td></tr>
tr's 1 and 2 have ISRC values from database, tr 3 is empty, but positioned last
tr 4 - is newly added empty line and i want a generated isrc applied to it...
code i provided above doesn't work. why?
You are calling .val() into an array of inputs, do this:
$("td[col=ISRC] input").each(function() {
// each iteration function
var s = $(this).val();
if (s === "") {
$(this).val(($("#new_isrc").val()));
return false; // stops each iteration
}
});
Edit:
If you want to add the same value to all inputs, do this:
$("td[col=ISRC] input").each(function() {
var s = $(this).val();
if (s === "") {
$(this).val(($("#new_isrc").val()));
}
});
If you want to add dynamic values to all inputs, do this:
$("td[col=ISRC] input").each(function() {
var s = $(this).val();
if (s === "") {
$(this).val(getNextValue());
}
});
function getNextValue() {
// your business implementation here
}

Categories

Resources