Dropdown based on another dropdown in jsp Struts - javascript

I'm very new to Ajax. Currently I'm working on a new project. For that project one of the requirements is, populating a second dropdown based on the input from the first dropdown. I'm using Struts to do that. I don't want the page to be refreshed, so I need to use Ajax for calling the second dropdown content in the backend and populate in the second dropdown. I don't know how to write code for that.
What should be included (jars,tags) in my struts project?
What entries should come in my JSP (I am using <html:select>)?
What will come in JavaScript?
What will come in action class (in action class I can fetch the list values from the DB based on the selection from the first dropdown)?

Instead of ajax, I used struts only to acheive this. I have assigned all variables to form to keep values when submitting form.

The answer to this question would probably a thesis ;)
I will just guide you in here.
1]Use a javascript framework like jquery. It will help you make ajax calls to your controller URL
Check an easy tutorial on http://www.tutorialspoint.com/jquery/jquery-ajax.htm
2] For the controllers lets have two urls mapped:
urapp/poplateDropdown1 to controller which return values/list target at ur first drop down
urapp/poplateDropdown2 to a another controller(or method within same controller) which responds to a GET request and receives a parameter say name SEL_VALUE for the selected value.
3] onchange events.
Have an onchange or similar best suited even on your first dropdoww.
In your event call a js function; like <select onchange=callDropDown2Controller(this.value) >
in your callDropDown2Controller() method:
//pseudo implementation
callDropDown2Controller(var selectedValue){
// now generate an AJAX get request using jquery with the following url
urlToCall = '/urapp/poplateDropdown2?SEL_VALUE=' + selectedValue
}
The rest buddy u need to do some homework and research.

Related

Javascript or jQuery Gridview Filter

I have an ASP.NET GridView and multiple ListBoxes as Departments, Categories, Faculties etc. ListBoxes and GridView are filled from a database (MSSQL) in codebehind.
I need a JS or jQuery function that takes selected item's value and filters gridview rows by this value. For example, when a department selected from department listbox, it will show only the entries in that department (hide others).
I know, it is not a proper question without sample codes but i really need some hints in this case.
Thanks for help.
This might get you started.
jQuery
$("#ListBoxID").change(function() {
$("#" + GridViewID).find('td').not(':contains("' + $(this).val() + '")').parents('tr').hide();
});
Not that if your ListBox.SelectionMode is set to Multiple, $(this).val() will contain an array of selected items and you have to handle that as well.
You have a couple of options:
You could utilize jQuery Datatables (which takes your existing <table> markup that your gridview generates and powers it up with various useful options). Then you could make use of their API to add in your filtering logic. Here is an example:
http://www.datatables.net/release-datatables/examples/plug-ins/range_filtering.html
Another option is to code your own jQuery ajax call, that will fire when clicking on a list box item. It would then call a static Web Method (that returns string) in your code behind (and send the selected list box option as a parameter). Your static web method would re-query the database using the parameter value to filter the result. Then you would build a gridview in your code behind, data bind it with the query results, turn the gridview into a html string and return it as a response to your initial jQuery Ajax call. In the success: callback of your AJAX call you would grab the response html string and place it into the container html element that holds your Gridview on the page. More about this approach:
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/ (explains calling the page method with jQuery)
http://encosia.com/boost-aspnet-performance-with-deferred-content-loading/ (slightly different example, it uses ASP.NET AJAX instead of jQuery AJAX to populate html on the page - but pay attention to the static Web Method - it demonstrates how to create a html string.)
If this all seems complex, you can use regular postback (not AJAX), by creating a selected index changed event on your listbox, that will re-query the database with the filtered option and rebind the existing gridview.
Hope that this helps

Changing the source of struts select tag dynamically using javascript/Jquery

In my code I have a Struts2 select tag(<s:select>). It reads something like this :
<s:select id="s" list="list" listKey="id" listValue="displayValue">
On some selection made by the user, I want to change the value of list attibute to point to some other list.(possibly using javascript/jquery)
What have you tried ? *
You have at least two ways to do this:
1) Perform an AJAX operation to get the new data (in JSON for example, like a List of 'id' and 'description');
then alter the HTML with Javascript, removing the old Options from the Select,
building and adding the new Options to the Select,
and eventually changing some Select attributes;
2) Perform an AJAX operation to get a completely new Select, elaborated server side, returned as a HTML snippet (a JSP with only one <s:select> inside);
then replace it to the original one on the page, for example using its container (like a div) as target of the AJAX operation.
* #AshishGupta suggested me to remove the "What have you tried ?" part to keep the tone positive. Please read the article, it is a must to understand why this should be always the first (positive and legit) question to askers who doesn't post code (for their own good in first place).
Hope that helps, as the rest of my answer.

populate textfield on selecting dropdown struts2

I have a text <s:select> in my jsp page .
Now what i have to do is when someone selects a value from this dropdown ,
i need to call my action class to get some value based on dropdown selection.
Now this value (which i got from my actionclass) should be shown in the <s:textfield> below this dropdown .
Please help !!
Well all you have to use the power of Ajax.You have multiple options to do this.
User simple Javascript.
User any javascript frameowrk like jquery,DOJO etc
Bind you code with on-click/change even of the Select tag and send a simple request to the S2 action.you can either use Stream result to send data back from the S2 action or better (in my opinion) send back JSON data from your action class and user Jquery build in functionality to parse the JSON data at JSP
user S2 JSON plugin to send and receive JSON data from Action and JSP to make life more easy.
Please follow this tutorial to know how to use JQuery with JSON and struts2
using-struts-2-json-and-jquery
Update
You need to do something like this in your JSP code for Ajax and JQuery
var selectedState = document.getElementById("selectboxid");
var statedata = selectedState.options[selectedState.selectedIndex].value;
var formInput='state='+statedata;
$.getJSON('search/dropDownRenderer',formInput,function(data) {
}

Best way to filter a list-view in asp.net MVC

I have a list of data coming from the database and displaying in a table, that works exactly how I want.
What I would like to do, is add a DropDownList to the page that "filters" the data in the table, based on the value of the selected item in the DropDonwList.
For example, the DropDown has these values
Assigned To Me
Assigned To Others
and the list of data, has an "assignedTo" field. When the value in the dropdown changes, I would like to update the list of data.
In WebForms, I would use an UpdatePanel and a DropDownList with autoPostBack=True, how can I get the same effect in MVC?
You use JavaScript/jQuery to bind to onchange/onclick event, and there do a postback:
$(function() {
$("#myelement").click(function(){
$("#secondelement").load('<%= Url.Action("Source") %>?selected=' + $(this).val());
});
}
There're jQuery plugins that do similar things, for example http://dev.chayachronicles.com/jquery/cascade/index.html (not the best one, the first I found).
You have a few options. One way is to create a Controller method that manages the process of grabbing your data (say as a IList), and then uses the Json(...) method of the Controller to serialize it and send it back as JsonResult (here's an example: http://weblogs.asp.net/mehfuzh/archive/2009/04/28/using-of-json-result-in-asp-net-mvc-1-0.aspx).
On your front end, you can wire up some javascript on the dropdown list that uses jQuery to make a $.get (http://api.jquery.com/jQuery.get/) passing back an id of sorts to determine your filter criteria.
Then you use the callback function of the $.get(...) call to manipulate your DOM as you see fit to visually depict the new list of data.

Need sample JavaScript to query MySQL and display result upon combo box update

I have a combo box that will be loaded with a list of choices. When the user selects a choice, I need a JavaScript to simply run a query of MySql (obviously based on the user choice in the combo box) which will return a simple, discrete value that then needs to be displayed on the page next to the combo box.
The query is nothing more than SELECT foo FROM tblexample WHERE id = blah (where blah is the combo box value). The value will be a simple number. If the user chooses a new value, then it should just re-query and display the result.
I'm open to reading the whole table in upon page load into an array or something too. I work in PHP but I don't know Javascript; I was only hoping for a sample code bit; I can read and extrapolate most of the time.
I just didn't want to put a submit button in a form and force the user to do that each time they look at a new combo box choice. I wanted a more seamless, quick display for them.
JavaScript is a client-side language. It will not run MySQL queries (safely, at least). Use PHP to dynamically create the HTML and JavaScript for the combo box.
PHP has an entire section of their documentation reserved for MySQL.
I think you are actually looking for a reference in Ajax programming using PHP on the backend and javascript on the front end.
My recommendation would be to look at using one of the excellent Javascript development frameworks. Great candidates would be JQuery or Prototype. They both give you solid libraries to simplify programming in javascript.
Rather than working with sample code, you'll probably get a lot further by developing javascript expertise. Ajax is complicated, and you'll need to at least get basic skills together before you can start to integrate javascript and PHP.
Here's a good query to get started- I'd recommend beginning with JQuery if you have to pick one.
http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=ajax+php+jquery+tutorial
Once you get started on jQuery as Tim mentioned you could do this,
The select box,
<form name="formName" action="" method="">
<select name="selName">
<option value={uniqueId}>Option 1</option>
</select>
</form>
<p class="displayMsg">No message to display.... yet</p>
The javascript and jQuery in a script tag of the head tag,
$(document).ready(function() {
$('select[name=selName]').change(function() {
function processData(data, success) {
...do something with the query results echoed into var data...such as
$('p.displayMsg').txt(data); // which will update the text node of the p tag class displayMsg
} // end function processData
var formData = $('form[name=formName]').serialize(); // this will encode the variables from the form to pass into post headers. You can access in your ajax called script with $_POST['selName']
$.post('phpAjaxProcessScript.php',formData,processDataClose); // sends data to script and when it's done it calls function processData
}); // end select change event function call
}); // end document ready event function call

Categories

Resources