html/js: Refresh 'Select' options - javascript

There's a class 'Car' with brand and model as properties. I have a list of items of this class List<Car> myCars. I need to represent 2 dropdowns in a JSP page, one for brand and another for model, that when you select the brand, in the model list only appear the ones from that brand. I don't know how to do this in a dynamic way.
Any suggestion on where to start?
Update
Ok, what I do now is send in the request a list with all the brand names, and a list of the items. The JSP code is like:
<select name="manufacturer" id="id_manufacturer" onchange="return getManufacturer();">
<option value=""></option>
<c:forEach items="${manufacturers}" var="man">
<option value="${man}" >${man}</option>
</c:forEach>
</select>
<select name="model" id="id_model">
<c:forEach items="${mycars}" var="car">
<c:if test="${car.manufacturer eq man_selected}">
<option value="${car.id}">${car.model}</option>
</c:if>
</c:forEach>
</select>
<script>
function getManufacturer()
{
man_selected = document.getElementById('id_manufacturer').value;
}
</script>
How do I do to refresh the 'model' select options according to the selected 'man_selected' ?

There are basically 3 ways to achieve this:
Use JavaScript to submit the form to the server side on change of the dropdown and let the JSP/Servlet load and display the child dropdown accordingly based on the request parameter. Technically the simplest way, but also the least user friendly way. You probably also want to revive all other input values of the form.
Let JSP populate the values in a JavaScript array and use a JavaScript function to load and display the child dropdown. A little bit trickier, certainly if you don't know JavaScript yet, but this is more user friendly. Only caveat is that this is bandwidth and memory inefficient when you have relatively a lot of dropdown items.
Let JavaScript fire an asynchronous HTTP request to the server side and display the child dropdown accordingly. Combines the best of options 1 and 2. Efficient and user friendly.
I've posted an extended answer with code samples here: Populating child dropdownlists in JSP/Servlet.

Related

Clear dropdown Select2 populated from JSP / Ajax with a button only works once

I have a page in which to make a query to the database, 12 filters are applied (each filter corresponds to a select2 dropdown).
When the page loads, the selects are filled by default with data from the java controller.
Example from a jsp page:
<select id="selectFPA" name="selectFPA" form="formResult" class="form-control">
<option selected>All the results</option>
<c:forEach items="${fpaList}" var="fpaList">
<option><c:out value="${fpaList.fpaname}" /></option>
</c:forEach>
</select>
But, if the user selects any value in any of the filters, all the filters are updated based on the chosen selection, through an AJAX call.
For example, suppose we have two select filters (dropdown):
Select 1 (Animal group):
- Birds
- Mammals
Select 2 (Animal name):
- Parrot
- Dog
If the user chooses mammals, an AJAX function will be called that will query the database and update the content of the select 2, eliminating the Parrot option. (And so on with up to 12 filters).
The problem comes when I want to clear the applied filters and return to the original select content (the content that appears by default every time the page is loaded from the java controller).
I have tried many things, from similar Stackoverflow questions without success.
The last thing I tried was:
Save the initial content of the select in a variable:
const fpa = $("#selectFPA").find("option").clone();
Onclick event (Reset filters button)
$("#ResetFilters").on("click",function() {
//first we empty the content
$('#selectFPA').empty().trigger('change.select2');
//original value injection
$("#selectFPA").html(fpa),
$('#selectFPA').trigger('change.select2')
})
This works fine if I press the button once, if I press the button a second time, the selects randomly select different values by default and they behave strangely.
I know this is a very specific question, but could someone help me? What am I doing wrong?
Thank you.
I think as per this answer you cannot create constant in jquery that's the reason only first time it works and next time it doesn't .Alternate, solution might be assign that clone value to some div and fetch it anytime when needed.Like below :
//call when page loads for the first time
$(document).ready(function() {
//cloning
var fpa = $("#selectFPA").find("option").clone();
//assigning value to div
$("#abc").html(fpa);
$("#ResetFilters").on("click", function() {
//getting clone value from div
var c = $("#abc").find("option").clone();
//first we empty the content
// $('#selectFPA').empty().trigger('change.select2');
//original value injection
$("#selectFPA").html(c);
//$('#selectFPA').trigger('change.select2')
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectFPA" name="selectFPA" form="formResult" class="form-control">
<option selected>All the results</option>
<option>1</option>
<option>2</option>
</select>
<button id="ResetFilters">Reset</button>
<div id="abc" style="display:none"></div>

The best way to develope dependet form fields with PHP/JS

I am looking for best nice, easy and fast solution for dependent fields in form.
Eg. When I choose Car A in next select list (or any other form filed) I want to see Type A or B, when I choose Car B in next select list I want to see Type C or D. (Not A, B, C, D together in second list in two cases).
I implement case with JS to automatically send form after select item in first list, and process selected value with PHP to display correct select list after page load.
I also implement this case with PHP and divide the process to few steps. And I store the values selected in previous rows in session.
What is the best way to solve this problem, is storing values in session a good practise, meaby I should use get ?
The best way (for me) is to send ajax request on select value in first list, and after ajax-response just put the answert in second list
(php script must restore options tags for your list)
Ex. (with JQuery)
HTML
<select id="A" >
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="B" ></select>
JS
$('#A').change(function(){
var value = $(this).val();
$.post('/path/to/ajax.php',{aValue:value}, function(optionsHtml){
$('#B').html(optionsHtml);
},'html')
});
PHP
<?php
$values = [
1=>['L1','L2'],
2=>['L3','L4']
];
foreach($values[$_POST['aValue']] as $l){
echo '<option value="'.$l.'">'.$l.'</option>';
}

Getting Chosen.JS values back in to field from Database after page update[Classic ASP]

So I have a form that is using a chosen multiple select field. The user is able to edit this page and save to a DB, I want to set it up in a way so when the user gets to this edit page, all of those multiple selects that wrote to the db earler will display on this edit page. I am able to get one value to show up but im not sure how I can get multiple values, and what format the chosen field needs to display these values. Thanks for any help or advice. Due to the length of my page I will include the portion that is getting info from the Database.
<select name="Form-Dropdown-businessUnit" multiple id="Form-Dropdown-businessUnit" form="Form">
<option value="consumer" <%If (Not isNull((RS_Edit.Fields.Item("Business_Unit").Value))) Then If ("consumer" = CStr((RS_Edit.Fields.Item("Business_Unit").Value))) Then Response.Write("selected=""selected""") : Response.Write("")%>>Consumer</option>
<option value="business" <%If (Not isNull((RS_Edit.Fields.Item("Business_Unit").Value))) Then If ("business" = CStr((RS_Edit.Fields.Item("Business_Unit").Value))) Then Response.Write("selected=""selected""") : Response.Write("")%>>Business</option>
<option value="cfs" <%If (Not isNull((RS_Edit.Fields.Item("Business_Unit").Value))) Then If ("cfs" = CStr((RS_Edit.Fields.Item("Business_Unit").Value))) Then Response.Write("selected=""selected""") : Response.Write("")%>>CFS</option>
</select>
What I have listed in my DB in my Business Unit Table:
consumer, business, cfs (one cell)
So it seems that its not able to check the logic because the data in the db is in a comma delimited list, there is no consumer,business,cfs conditional check and I would need to create an intermediary table that one pull one value at a time, i.e. Consumer, then Business, that would check this against the logic in my ASP?

Drop Down Option Value resets are page reloading

Hy Stackoverflow members.
Here is my little problem, I have a page that I'm saving some values in sessions. For example I have a sorting drop down option for my users.
<form id="formName" action="Index.php" method="POST">
<select name="Sort_Ads" id="Sort_Ads" onchange="document.getElementById('formName').submit()">
<option>Most Recent Ads</option>
<option>Price: Low to High</option>
<option>Price: High to Low</option>
</select>
</form>
Once a option is selected the page reloads and the users can see the ads by the selected sorting option.Some php code is working behind it. But with javascript I want to create a function which will set the selected option by users after page reloads. please my javascript skills aren't good enough. Could someone do it I'll be really thank full!
You will need to cookie the user to maintain state or use php to parse the selected option as selected. HTTP is state-less.
ie, you can do something like:
var myselection;
$("#Sort_Ads").change(function(){
myselection = $("Sort_Ads option:selected").val();
});
call and have a set and read cookie function passing in the myselection var. w3 schools has a good example of this.
Or, what i would say is the better method, you can use php to print the form, but you'll need to give your options values, and then iterate through each value and if value == selected, change
<option value='x'>
to
<option value='x' selected>
when printing the form.

Selecting options from a drop down

I'm building a recipe-finder for a new food blog. The design I have basically involves the user selecting ingredients, one at a time, from a drop down <select>, the option disappearing from the list (so they can't select it again) and appearing on another HTML list with a link to remove it from the list. Once they're done, they click a button and that takes them through to a results page.
Here's the select markup as generated by the PHP:
<select>
<option value="">Please select</option>
<option value="beef-mince">Beef mince</option>
<option value="carrots">Carrots</option>
...
</select>
It's not drastically complex but it does raise a few questions on how I'm going to do some of these things. I'm using jquery.
I need to store the selected items in memory so I know what to send to the search page when they've done selecting items. What's the best way of doing that in your opinion as each item has two values (its "real" value and its database-value)?
How do I make "Please select" the selected option after they've selected something (preferable without triggering the onchange event)?
Once I've stored it in memory and added it to the displayed list of things they're searching for, how do I delete that item from the available items? Can I just "hide" or disable it (safely)?
If in #3 I have to delete it from the DOM, when I add it again, can I sort the list (based on either value) and keep the please-select option at the top?
1.) You can append hidden form elements to the page whose value is the value of the selected option.
2.)
jQuery("#select-list")[0].options[0].selected = true // assuming it's the first item
3.) I would remove the element from the DOM using jQuery("#select-list option:selected").remove()
4.) You can use before(). jQuery(your_default_option).before("#select-list option:first");
You can store the 'two values' in a hidden form field as an object in JSON notation. This will make it easy to modify in jQuery as the user interacts with the page.
You will need to use a combination of the onchange, keyup and keydown event to capture possible changes to the form so that you can re-select the 'Please Select' option.
You will need to remove the option from the dom and re-add it later. You can easily do this through jquery through something like this:
$("select option:selected").remove();
You can write a sorting function for the options starting with index 1, and keep the 'Please Select' as the first option.
1)
Basic idea, you need to check to make sure the first is not picked
var selections = [];
var mySel = document.getElementById("mySelectId");
var ind = mySel.selectedIndex;
selections.push( mySel.options[ind].value ); //add to a list for you to remember
mySel.options[ind] = null; //remove
2)
mySel.selectedIndex = 0;
3)
See #1
4) Yes you can add it anywhere you want by using insertBefore
Example here: http://www.pascarello.com/lessons/forms/moveSelectOptions.html
Will leave this answer here but I think I failed to read your whole post, so it might not help much.
You need to give your select a id like this:
<select id="MySelect">
<option value="">Please select</option>
<option value="beef-mince">Beef mince</option>
<option value="carrots">Carrots</option>
...
</select>
And to get it is just something like this:
<?php
$value = $_REQUEST["MySelect"];
echo $value;
?>
Code is not tested and $_REQUEST can be replaced by $_GET or $_POST regarding what you have specified as action on your form. $_REQUEST will eat it all though.

Categories