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

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...

Related

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)

Ajax html response to div

Hi I am printing the ajax html response to div element and giving radio input option to select the file. after selecting the specific file the another div should show the message. but the ajax html response is not working
Jquery script:
$(document).ready(function()
{
$('#upload').ajaxForm({
beforeSubmit: function() {
$('#Analysis').show();
$('#Content_column').hide();
$('#file_list').show();
$('#trait').show();
$('#trait').html('Submitting...');
},
success: function(data) {
var $out = $('#file_list');
$out.html('&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspFile list:');
$out.append('<div id="list">');
$('#list').html(data);
$out.append('</div>');
}
});
});
The output of this script is
<ul class="php-file-tree"><li class="pft-directory">Genotypic<ul><input id="Penotypic" type="radio" name="uploads/Genotypic/" value="uploads/Genotypic/jquery.txt" />jquery.txt<br><input id="Penotypic" type="radio" name="uploads/Genotypic/" value="uploads/Genotypic/marker.csv" />marker.csv<br></ul></li><li class="pft-directory">Other</li><li class="pft-directory">Penotypic<ul><input id="Penotypic" type="radio" name="uploads/Penotypic/" value="uploads/Penotypic/namPheno.csv" />namPheno.csv<br><input id="Penotypic" type="radio" name="uploads/Penotypic/" value="uploads/Penotypic/perl.pl" />perl.pl<br></ul></li></ul>
Jquery script:
$('#Penotypic').click(function() {
var $out1 = $('#trait');
$('#trait').show();
$out1.append('Submitted...');
});
this is not showing anything in the div trait. may be the html response is loading as a tesxt so the #Penotypic is not recognised. please help me to fix this.
Thanku
You have many inputs of id="Penotypic". Make every id unique or use classes as function trigger.
I wouldn't use "/" in the name attribute. See: http://www.w3.org/TR/html401/types.html#type-name
Then try if your ajax script does work. If it doesn't work, try if it works from static page (don't use your first jQuery script, but it's output as a static form). You probably need to bind your event trigger. Use jQuery's on().

Send form to server in jquery

I am learning ASP.NET MVC. I have to submit a to controller side after validation in client-side(in jquery). How this can be done? Should i use <form action="#" method="post"> instead of <form action="Controller/Method" method="post"> and add an event handler in click event of submit button of , to send via ajax etc? What should i do? pls help
You are on the right track, and what you suggested will work.
A better method would be to leave the original action intact, providing backwards compatibility to older browsers. You would then create the event handler as normal, and include code to prevent the default submit behavior, and use ajax instead.
$('#submitbutton').live('click', function(e){ e.preventDefault(); });
The easiest way to do this is to use the jQuery forms plugin.
This is my go-to plugin for this type of thing. Basically it will take your existing form, action url etc and convert the submission to an ajax call automatically. From the website:
The jQuery Form Plugin allows you to easily and unobtrusively upgrade
HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit,
gather information from the form element to determine how to manage
the submit process. Both of these methods support numerous options
which allows you to have full control over how the data is submitted.
It is extremely useful for sites hosted in low cost web hosting
providers with limited features and functionality. Submitting a form
with AJAX doesn't get any easier than this!
It will also degrade gracefully if, for some reason, javascript is disabled. Take a look at the website, there are a bunch of clear examples and demos.
This is how I do:
In jQuery:
$('document').ready(function() {
$('input[name=submit]').click(function(e) {
url = 'the link';
var dataToBeSent = $("form#myForm").serialize();
$.ajax({
url : url,
data : dataToBeSent,
success : function(response) {
alert('Success');
},
error : function(request, textStatus, errorThrown) {
alert('Something bad happened');
}
});
e.preventDefault();
});
In the other page I get the variables and process them. My form is
<form name = "myForm" method = "post">//AJAX does the calling part so action is not needed.
<input type = "text" name = "fname"/>
<input type= "submit" name = "submit"/>
<FORM>
In the action page have something like this
name = Request.QueryString("fname")
UPDATE: As one of your comment in David's post, you are not sure how to send values of the form. Try the below function you will get a clear idea how this code works. serialize() method does the trick.
$('input[name=submit]').click(function(e){
var dataToBeSent = $("form#myForm").serialize();
alert(dataToBeSent);
e.preventDefault();
})

How to update a label from a postback in MVC3/Razor

MVC/Razor/Javascript newbie question:
I have a MVC3/Razor form where the use can select a single product from a drop down list.
<div class="editor-label">
Product
</div>
<div class="editor-field">
#Html.DropDownList("ProductID", (IEnumerable<SelectListItem>)ViewBag.Products, "--Select One--")
#Html.ValidationMessageFor(model => model.ProductID)
</div>
What I then want is to display the price of the selected product on a label just below the drop down list (model property name is Amount).
This should be pretty easy, but I am pretty new at Razor, and know almost nothing about Javascript, so I would appreciate any verbose explanations of how do do it, and how it all hangs together.
Add a div/span under the Dropdown .
#Html.DropDownList("ProductID", (IEnumerable<SelectListItem>)ViewBag.Products, "--Select One--")
<div id="itemPrice"></div>
and in your Script, make an ajax call to one of your controller action where you return the price.
$(function(){
$("#ProductId").change(function(){
var val=$(this).val();
$("#itemPrice").load("#Url.Action("GetPrice","Product")", { itemId : val });
});
});
and have a controller action like this in your Product controller
public string GetPrice(int itemId)
{
decimal itemPrice=0.0M;
//using the Id, get the price of the product from your data layer and set that to itemPrice variable.
return itemPrice.ToString();
}
That is it ! Make sure you have jQuery loaded in your page and this will work fine.
EDIT : Include this line in your page to load jQuery library ( If it is not already loaded),
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
The Amount isn't available to your view when the user selects a product (remember the page is rendered on the server, but actually executes on the client; your model isn't available in the page on the client-side). So you would either have to render in a JavaScript array that contains a lookup of the amount based on the product which gets passed down to the client (so it's available via client-side JavaScript), or you would have to make a callback to the server to retrieve this information.
I would use jQuery to do this.
Here's a simple example of what the jQuery/Javascript code might look like if you used an array.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
// This code can easily be built up server side as a string, then
// embedded here using #Html.Raw(Model.NameOfPropertyWithString)
var list = new Array();
list[0] = "";
list[1] = "$1.00";
list[2] = "$1.25";
$("#ProductID").change(displayAmount).keypress(displayAmount);
function displayAmount() {
var amount = list[($(this).prop('selectedIndex'))];
$("#amount").html(amount);
}
});
</script>
<select id="ProductID" name="ProductID">
<option value="" selected>-- Select --</option>
<option value="1">First</option>
<option value="2">Second</option>
</select>
<div id="amount"></div>
You'll want to spend some time looking at the docs for jQuery. You'll end up using it quite a bit. The code basically "selects" the dropdown and attaches handlers to the change and keypress events. When they fire, it calls the displayAmount function. displayAmount() retrieves the selected index, then grabs the value out of the list. Finally it sets the HTML to the amount retrieved.
Instead of the local array, you could call your controller. You would create an action (method) on your controller that returned the value as a JsonResult. You would do a callback using jquery.ajax(). Do some searching here and the jQuery site, I'm sure you'll find a ton of examples on how to do this.

Create google suggest effect with asp.net mvc and jquery

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.

Resources