Create google suggest effect with asp.net mvc and jquery - asp.net-mvc-3

What I want to achieve, is not the autocomplete effect. What I want to achieve is that when you type on google the search results come up almost inmediately without cliking on a search button.
I already did the ajax example with a search button, but I would like it to make it work while you type it shows the results in a table.
The problem is I have no idea where to start.
EDIT: To ask it in another way.
Lets suppose I have a grid with 1000 names. The grid is already present on the page.
I have a textbox, that when typing must filter that grid using AJAX, no search button needed.
Thanks

Use a PartialView and jQuery.ajax.
$(document).ready(function () {
$("#INPUTID").bind("keypress", function () {
if($(this).val().length > 2) {
$.ajax({
url: "URL TO CONTROLLER ACTION",
type: "POST|GET",
data: {query: $("#INPUTID").val(),
success: function (data, responseStatus, jQXHR)
{
$("#WRAPPERDIVID").html(data);
}
});
}
});
});
Then in your view:
<div>
<input type="text" id="INPUTID" />
</div>
<div id="WRAPPERDIVID"></div>
Edit
Also, you could build in some sort of timer solution that submits the request after say 1 second of no typing, so you don't get a request on every key press event.

Theres a good example you can check here try to type 's' in the search
if thats what you want
then the code and the tutorial is here
another good example here

If you are working on "filtering" a set already located on the page, then you seem to want to set the visibility of the items in the list, based upon the search criteria.
If so, then first, you need to first establish your HTML for each item. You can use the following for each item:
<div class="grid">
<div class="item"><input type="text" value="{name goes here}" readonly="readonly" /></div>
{ 999 other rows }
</div>
Then, you must use some jquery to set each row visible/invisible based on the search criteria:
$("#searchBox").live("change", function () {
$("div[class='grid'] input").each(function () {
var search = $("#searchBox").val();
if ($(this).val().toString().indexOf(search) != -1)
$(this).parent().show();
else
$(this).parent().hide();
});
});
This will cause the visibility of each item to change, depending on whether or not the text in the search box matches any text in the item.

Related

how to refresh only data in ajax?

here, when i m going to replace my div i want to refresh only data not whole html design at 7 line
function func_name(id_1,id_2)
{
$.ajax({
type :"GET",
url:''<?php echo site_url('controller/function');?>/'+id_1+'/'+id_2,<br />
success: function(data){
$('#right').html(data); // id where do you want to replace div
}
});
}
If you want to refresh data, you'll need to define some HTML document element identifiers and set them one by one.
For example, in the $.ajax success callback, instead of calling $('#right').html(data);, if your right container has 2 spans to show first and second name of some user, you would do this:
$("#right #name").text(data.name);
$("#right #secondName").text(data.name);
...and your HTML should look as follows:
<div id="right">
<span id="name"></span>
<span id="secondName"></span>
</div>

How to initialize select2 that uses a query for data when I already have a value

I have a view with 2 select boxes which are "cascading". A user selects a value from the first box and the second is populated based on the new value. This is done with Select2's query option, and works fine on the first load of the page. However, when I post the page and then render it, both select boxes already have values (say A and 1), but the dependent checkbox is not initialized. I have done a few things with initSelection and it didn't help much, sometimes just getting me into an loop.
What I am trying to do is this:
Link the two boxes
When the first box changes, reset the data in the second box and clear the value
When the page is re-drawn, and a value has already been selected (e.g. response to POST)
Go to server and get the data
Show the correct value for the existing <input type='hidden' value='xxx'>
if that value exists in the list, of course
if not, set value to blank (optionally fire jquery validation
Searching/constant querying is not needed. Just load once on change
I am thinking about changing this entire, so if this is really the wrong way to go about this, I'd be happy to know.
// caches ajax result based on `data`
// if data has been requested before, retrieves from the cache (nothing special)
// based on other code that did it all inside the `query` function directly
var locationsCache = new AjaxCacheClassThing( {
url: '...',
data: function() { return { masterId: $('#ParentBox').val(); } }
});
$(function() {
$('#ParentBox').change(function () {
$('#ChildBox').select2('data', null);
});
$('#ChildBox').select2({
query: locationsCache.queryCallbackHandler,
selectOnBlur: true,
});
});
The HTML uses the standard MVC helpers, and the HTML is rendered just fine.
#Html.DropDownListFor(m => m.ParentBox, SelectListOfStuff) // standard <select>
#Html.HiddenFor(m => m.ChildBox)
Here is how this scenario goes:
ParentBox is required (no empty option)
First Load: there is no value selected
Open the DependentBox
Ajax query issues correctly
Dropdown populates as expected
Second Load
Master box selects value just fine
ChildBox hidden input has value="xx" just fine
It does not show a selected item
Clicking dropdown populates the box as expected (from cache)
After some time spent, and lots of time on here and other places, I figured out how this all works (at least some parts of it!). Way simpler than I thought it was, but still surprised this isn't supported out of the box in some way. Seems like a really common request.
query and ajax and initselection aren't that useful in this scenario
They query each time a the search box changes (not desired)
They complicate everything
You need to init the select2 manually
If you use { data: ... } then you don't need query or ajax
Set the "value" on your hidden input if you have one, so the item gets selected
You have to recreate the box when you get new data
It is really simple. This is the simplest case, using no extra features or attributes
Javascript:
$(function() {
$('#ParentBox').change(createChildSelect2);
createChildSelect2();
});
function createChildSelect2() {
makeAjaxRequest( function( newData ) {
$('#ChildBox').select2( { data: newData } );
});
}
function makeAjaxRequest(callback) {
// calls a.jsp?parentId={?} and then the callback when done.
jQuery.ajax({
url: 'a.jsp', dataType: 'json',
data: function() {
return { parentId: $("#parentBox").val() };
}
})
.done(function (data) {
callback(data);
});
}
The HTML is all the same. A type=text and type=hidden both work:
<select id="ParentBox">
<option ... >
<option ... >
<select>
<input id="ChildBox" type="hidden" class="input-medium" value="1"/>
Or using Razor:
#Html.DropDownListFor(m => m.MasterBox, SelectListOfStuff) // standard <select>
#Html.HiddenFor(m => m.DependentBox)

iframe replacement

I need to make a page with a sidebar on the left, and a search page on the right. I need to be able to perform a search and have the results appear without refreshing the content in the chat frame on the left. Ideally, I need these pages to be able to talk to each other so that a link from the frame on the left can invoke a search on the right. Right now I'm using PHP to handle the search functionality on the right, but I can use any language really.
I looked at iframes, but I was really hoping to have the "search" page be the main page so that the scrollbar in the browser reflects the position on the search page.
I also thought maybe this could be done with AJAX, but since my search box is a form, I wasn't sure how to pass parameters to the page that shows the results.
Hopefully this makes sense, I'll clarify what I can. Thank you!
You can still use ajax. Consider jQuery:
HTML Search Form:
<form id="searchForm">
<input name="searchterm" />
<input type="submit" value="Search" >
</form>
HTML Search Results Container:
<div id="searchResults"></div>
jQuery:
$('#searchForm').on('submit', function(e) {
var $form = $(this);
e.preventDefault();
$.ajax({
url : '/path/to/search.php',
type : 'post',
data : $form.serialize(),
success : function (data) {
$('#searchResults').html(data); // or parse out your data into HTML if it isnt already sent that way
}
});
});

How can I change the style of a div on return from a form submit action in Razor MVC3?

I have a Razor/ASP/MVC3 web application with a form and a Submit button, which results in some action on the server and then posts back to the form. There is often some delay, and it's important that users know they should wait for it to complete and confirm before closing the page or doing other things on the site, because it seems users are doing that and sometimes their work has not been processed when they assume it has.
So, I added a "Saving, Please Wait..." spinner in a hidden Div that becomes visible when they press the Submit button, which works very nicely, but I haven't been able to find a way to get the Div re-hidden when the action is complete.
My spinner Div is:
<div id="hahuloading" runat="server">
<div id="hahuloadingcontent">
<p id="hahuloadingspinner">
Saving, Please Wait...<br />
<img src="../../Content/Images/progSpin.gif" />
</p>
</div>
</div>
Its CSS is:
#hahuloading
{
display:none;
background:rgba(255,255,255,0.8);
z-index:1000;
}
I get the "please wait" spinner to appear in a JS method for the visible button, which calls the actual submit button like this:
$(document).ready(function () {
$("#submitVisibleButton").click(function () {
$(this).prop('disabled', true);
$("#myUserMessage").html("Saving...");
$("#myUserMessage").show();
$("#hahuloading").show();
document.getElementById("submitHiddenButton").click();
});
});
And my view model code gets called, does things, and returns a string which sets the usermessage content which shows up fine, but when I tried doing some code in examples I saw such as:
// Re-hide the spinner:
Response.write (hahuloading.Attributes.Add("style", "visibility:hiddden"));
It tells me "hahuloading does not exist in the current context".
Is there some way I am supposed to define a variable in the view model which will correspond to the Div in a way that I can set its visibility back from the server's action handler?
Or, can I make the div display conditional on some value, in a way that will work when the page returns from the action?
Or, in any way, could anyone help me figure out how to get my div re-hidden after the server action completes?
Thanks!
Is this done with ajax? I would assume so because the page is not being redirected. Try this:
$(document).ready(function () {
$("#submitVisibleButton").click(function () {
$(this).prop('disabled', true);
$("#myUserMessage").html("Saving...");
$("#myUserMessage").show();
$("#hahuloading").show();
document.getElementById("submitHiddenButton").click();
});
$("#hahuloading").ajaxStop(function () {
$(this).hide();
});
});
As an aside, you no longer need runat=server.

Select box populated dynamically with AJAX doesn't post on form submission

This is my first attempt at chaining select boxes in a web form using ajax and I I'm obviously missing something. I'm simply at a loss for what that is, exactly. Here is my issue:
A user selects a Country from one select box and an ajax request is made and options (containing names of States and Territories) are returned to a select box below. While the options are returned into the form select field, the user-selected option is NOT sent when the form is submitted.
Here is the code I've cooked up:
<script type="text/javascript">
jQuery(document).ready(function($){
$("select#state").attr("disabled","disabled");
$("select#country").change(function(){
$("select#state").attr("disabled","disabled");
$("select#state").html("<option>Loading States...</option>");
var id = $("select#country option:selected").attr('value');
$.post("http://example.com/terms.php", {id:id}, function(data){
$("select#state").removeAttr("disabled");
$("select#state").html(data);
});
});
});
</script>
You can see the live example here (see the Country/State section):
http://shredtopia.com/add/
Any ideas what is needed to get this working?
As far i can see, the user input is sent
input_32 79
input_29 alberta
Being 79 the country canada and alberta the state.
<select tabindex="11" class="medium gfield_select" id="input_1_32" name="input_32"></select>
<select tabindex="12" class="medium gfield_select" id="input_1_29" name="input_29" disabled=""></select>
Maybe i misunderstood the issue?
Try .live( eventType,handler )
Description: Attach a handler to the event for all elements which match the current selector, now and in the future.
http://api.jquery.com/live/
Add to your code and try it~
$('select#state').live('change', function() {
var id = $("select#state option:selected").attr('value');
alert(id);
});
Or try this:
add a hidden in form:
<input type="hidden" id="hiddenValue">
alter your select#state like this:
<select onchange='innerValue(this.options[this.options.selectedIndex].value)'></select>
and create a javascript function
function innerValue(value){
$("#hiddenValue").val(value)
}
then,click submitbutton,$("#hiddenValue").val() is you need
$("#submitbutton").click(function(){
alert($("#hiddenValue").val())
})
but,I think this is not the best solution...

Resources