Dynamically populate drop down menu with selection from previous drop down menu - javascript

I have a cgi script written in Python. There are two drop down menus and then a submit button. I'd like to be able to make a selection from the first menu, and based off that choice, have the second drop down menu dynamically populate new choices. The second menu should populate without having to click any button, but simply from making a selection from the first menu. The second menu should also repopulate continually every time I select a new item on the first menu - again, without clicking submit.
What's the general idea to getting this done? I already have implemented some of the code. It uses if/else statements on conditions of whether the inputs have been provided. So after the first drop down menu selection is made, the page submits, and an if/else statement directs to code that displays the same form but with the selection maintained in the drop down menu. I'm using onchange='this.form.submit() to submit the form without having to use the submit button. The current problem is that while making a selection submits the form automatically the first time, reselecting on this form does not seem to work. So, I'm not sure if onchange='this.form.submit() submits the form after the first time.
Here is a prototype. Am I going in the right direction? Or should I be using Ajax? (not familiar with this at all yet):
firstChoicesList = firstChoices()
print(""" <form method="post" action="/cgi-bin/thisScript.py">""")
# if both choices are not selected yet
if "firstChoice" not in form and "secondChoice" not in form:
# first choice drop down menu
print("""<p>first choice <select name="firstChoice">""")
for f in fristChoicesList:
print("""<option value='""" + f + """'>""" + f + """</option>""")
# second choice drop down menu
print("""</select></p>""")
print("""<p>second choice <select name="secondChoice">""")
for f in secondChoicesList: # currently contains 1 empty string
print("""<option value='""" + f + """'>""" + f + """</option>""")
print("""</select></p>""")
print("""
<p><input type="submit" />
</form>
""")
print("Please fill in the forms.")
sys.exit(1) # don't proceed with rest of code below these if/else statements
# if first choice has been selected but not the second
elif "firstChoice" in form and "secondChoice" not in form:
# <code for first drop down menu again with choice selected>
# this function takes the first choice as an argument and returns selections for the second menu
secondChoicesList = secondChoices(form["firstChoice"].value)
# <code for second drop down menu with choices populated from secondChoicesList>
print("""
<p><input type="submit" />
</form>
""")
print("Please fill in the forms.")
sys.exit(1)
# if both are selected
else:
# <same code as above except have both drop down menus save previous selections>
# proceed to run rest of cgi script

This is an hint: you can populate the next menu with an ajax call to a server side page (that will give you back the data): this will let you:
- Avoid to send forms and pass values through pages (you will send the form only at the end)
- Let user changes his choise (if he need it), without surfing the history
I think that using ajax with jquery will be really simple to use, also if you don't know it.
Please, check short ajax jquery fiddle example to see how easy is to use jquery (here, for cross domain request, that shouln't be your case, you have to disable web security of your browser, e.g. for google chorme set google chrome to make cross domain request with ajax )
code of the fiddle:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<body>
<select name="a" id="a" onchange="func(this.value)">
<option value="">choose</option>
<option value="https://www.google.it/search?q=ajax+and+juery&oq=ajax+and+juery&aqs=chrome.0.57j0l3.7474j0&sourceid=chrome&ie=UTF-8#sclient=psy-ab&q=ajax+jquery&oq=ajax+jquery&gs_l=serp.3..0l10.2179.3578.2.3820.7.3.1.3.3.1.206.516.0j2j1.3.0...0.0.0..1c.1.15.serp.9gdUZUmAxcI&psj=1&bav=on.2,or.r_qf.&bvm=bv.47244034,d.ZGU&fp=41333c9f97f3f20a&biw=800&bih=505">google</option>
<option value="http://it.bing.com/search?q=ajax+jquery&go=&qs=n&form=QBLH&filt=all&pq=ajax+jquery&sc=0-0&sp=-1&sk=">bing</option>
</select>
</body>
<script>
function func(ak){
$.ajax({
url : ak,
success : function (data,state) {
$("body").html(data);
alert(state);
},
error : function (request,state,error) {
alert("Error. stato della chiamata: "+request+' '+error+' '+state);
console.log("Error. stato della chiamata: "+request+' '+error+' '+state);
}
});
}
</script>

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>

keep spring form select value

I use Spring MVC 4 bring a list and show on the website
<s:select path="almacenesByAlmOri.codAlm" id="select1" name="select1" onchange="tr_EnviarAlmacen('select1');" items="${listalmacen}" itemValue="codAlm" itemLabel="nomAlm" class="form-control input-sm"></s:select>
<script>
function tr_EnviarAlmacen(sel){
var cbox = document.getElementById(sel);
var valor = cbox.options[cbox.selectedIndex].value;
var red = "getprodxalm?cod_alm="+valor;
location.href = red;
}
</script>
As I can keep the option of a select spring form selected by reloading the page?
View is rendered by server everytime you refresh(I mean the 'hard refresh' without browser caching) the page, that means Model is refreshed and proper selected values are injected in to the view(the values wich were posted and saved).
To keep selected option while you refresh your page you have to use AJAX.
You need to HTTP POST selected options everytime user selects something in your select form.

jquery not showing live data unless refresh [duplicate]

This question already has an answer here:
refresh jquery data constantly
(1 answer)
Closed 8 years ago.
I am trying to count the amount of dropdowns that have a specific item selected in them. I have my code below, but it works like this:
select options in the drop downs, press refresh page, selected items in drop down remain there, and the script reads the amount of times each were selected.
The dropdown boxes are listed on the page with questions. there are about 100 dropdowns. every drop down has the same options.
this is a repeating code that lists all the drop down selections on the right side of the page, and shows the number of how many times each was used next to it. it works, just not dynamically. I want it to work instantly when an item is selected, without having to make selections and then refresh.
<%
mySQL="SELECT * FROM admins WHERE area="&parea&" AND type>2"
call getFromDatabase(mySQL, rstemp4, "addscheduleform5.asp")
do while Not rstemp4.EOF
pempidw=rstemp4("idadmin")
pempname1=rstemp4("firstname")
%>
<%=pempname%>=
<script type="text/javascript">
var scheduled = $("select").filter(function() {
return $(this).val() == "<%=pempidw%>";
});
document.write(scheduled.length);
</script>
<%rstemp4.movenext
loop%>
EXAMPLE:
For example, if you have 5 dropdowns. so if you select
X, A, B, X, A
in the drop downs, the code reads
X=2 A=2 B=1
Now it works, if you make your dropdown selections, and refresh the page, the drop down selections remain the same, and the code reads the amount of times each were selected.
Now if you change your first option from
X to A,
then the code still reads:
X=2 A=2 B=1
unless you refresh the page, then you see:
X=1 A=3 B=1.
For those that don't know asp, this javascript function has nothing to do with my site being asp. the "<%=pempidw%>" simply displays a number on the loaded page, referencing the select value.
see below what the loaded script would appear as.for reference on what "<%=pempidw%>" means only
<option value="2">2</option>
<script type="text/javascript">
var scheduled = $("select").filter(function() {
return $(this).val() == "2";
});
document.write(scheduled.length);
</script>
Given document.write really isn't a good way of doing this, I'm going to (for the sake of the example) place a <span id="result"></span> on thepage we can [re]reference with the output.
Having said that, the test code should be wrapped in a function so we can re-use it. Currently it's only executing on the initial visit to the page. To correct that, we're also going to execute our new function on a change to any of the dropdowns.
function getSelectedValues(){
var matches = $('select').filter(function(){
return $(this).val() == '<%=pempidw%>';
}).length;
// here's where we just update that new <span>
$('span#result').text(matches);
}
// call it on initial page visit
getSelectedValues();
// and here we bind to the change event for the selects
// and re-call our above function.
$('select').on('change', getSelectedValues);

Update database table

I am currently using grails and I am trying to figure out a way that I can update my database table utility with the two values selected from two drop down menus. My drop down menus are passed values from this table when a user selects a specific value from another drop down. I'm trying to figure out how to update my table so that I can load the newly changed values into the drop down menu upon reloading.
For example: I have mondayStart and mondayEnd drop down menus that are populated with times 9am-5pm based upon the values from the database. If the user changes the value from the drop down menu mondayStart from 9:00 am to 10:00 am the value 10:00:00 replaces the current database value 09:00:00 upon clicking the Update button I have created and will also update the other drop down menu mondayEnd upon being changed and will be overwritten in the database.
Currently I have my drop down menus which are populated from the users specific actions:
<td style="text-align: center; width: 115px;" onchange="e" >
<select name="mondayStart" id="mondayStart">
</select>
<select name="mondayEnd" id="mondayEnd">
</select>
</td>
And my test to see if the change alert is working:
$("#mondayStart").live('change', function(e){
alert($(this).val());
});
This is my update button:
<g:submitButton name="update" style="float: right; margin-right: 10px" type="button" id="update" value="Update" onchange="e" />
How can I set this up to allow my database to be updated with multiple values upon the click of my update button?
I think something along these lines should do the trick :-
$("#update").click(function() {
-- code for adding to the database would go here --
-- might be an idea to use $.post() --
});
Let me know if this helps and if it doesn't I will try and come up with something else.
You should submit the form (via ajax or normal way) and in your controller retrieve the values from params.
For example, you could have in your controller a method like the following:
def save(String mondayStart, String mondayEnd){
//Update your domain with those values
//render view, return values or redirect where you want
}
One note, you can define the parameters on the method parameters o just recover them from the params object

jQuery Mobile and MVC3 auto submit

The following code works perfectly if I take jQuery Mobile out of the question!
The form:
#using (Html.BeginForm("SearchTown", "Home", FormMethod.Post, new { id = "TheForm1" }))
{
#Html.DropDownList("TownID", (SelectList)ViewBag.TownId, "Select a Town")
}
The Javascript:
<script type="text/javascript">
$(function () {
$("#TownID").live('change', function () {
//$("#TownID").change(function () {
var actionUrl = $('#TheForm1').attr('action') + '/' + $('#TownID').val();
$('#TheForm1').attr('action', actionUrl);
$('#TheForm1').submit();
});
});
</script>
But if I wrap jQuery Mobile around the site, then every time I submit the form, in my log only it tacks the ID field again and again to the end of the URL string. This only happens in my log, not in the browser. In the browser it still looks like it’s doing the right thing! E.g..
www.mysite.com/Home/SearchTown/2 the first time
www.mysite.com/Home/SearchTown/2/2 the second time
www.mysite.com/Home/SearchTown/2/2/2 the third time
But in the browser it still looks correct www.mysite.com/Home/SearchTown/2
Why is jQuery Mobile doing this?
This is most likely happening because each time you POST the form, it uses AJAX to load the response and the loaded page has repeated element IDs in it.
I'm guessing here, but based on what you described it sounds like your form posts back to a page with the same form markup on it. Each time your form post renders the next page you'll get another #TheForm1 added to your DOM (as jQuery Mobile keeps previously loaded pages in the DOM and simply swaps between active data-role="page" elements). Due to this behavior, once you have more than one #TheForm1 on the page, the selector $('#TheForm') will only ever return the first element in the DOM matching that ID- which will be the form which you posted the very first time. Thus, each time you you post, your code will use the action attribute of the form element you modified originally- which is why you see multiple values appended to the URL.
In jQuery Mobile it is almost always better to identify elements using a class name and the active page as the container, as you never know how many times an ID might be repeated in the DOM across multiple page changes. So, instead of using $('#TheForm1'), assign a class name and use that in conjunction with $.mobile.activePage: $('.Form1', $.mobile.activePage). (The same goes for your select box).
As an alternative, you can tell jQuery Mobile to not enhance your form by adding data-ajax="false" to the form tag. This will cause it to behave like a normal full page postback without any AJAX.
Edit
The point I am making in paragraph 3 is that you need to make sure you're always selecting the correct form element for the currently visible page, rather than unintentionally returning one which is hidden from view. The $.mobile.activePage global variable will give you the context of the currently visible page, and then a class-based selector (rather than Id-based) will ensure that the correct form element is retrieved in the change handler. Something like this:
<form class="town-form" action="#">
<select class="town-selector">
<option value="1">Town A</option>
<option value="2">Town B</option>
<option value="3">Town C</option>
</select>
</form>
<script type="text/javascript">
$(function () {
$(".town-selector").live('change', function () {
var form = $('.town-form', $.mobile.activePage);
var actionUrl = form.attr('action') + '/' + $(this).val();
form.attr('action', actionUrl);
alert('submitting to: ' + form.attr('action'));
form.submit();
});
});
</script>
because you are submitting the hole page and jQuery mobile does not fancy such thing, and after each POST it just appends the ID into the document.location... I have learned that in some mobile projects...
instead of this line $('#TheForm1').submit(); do something like this:
var url = $('#TheForm1').attr('action') + '/' + $('#TownID').val();
$.post(url, $('#TheForm1').serialize(), function(data) {
// do something with data if you send back something...
// or just change page with jQuery Mobile API
});
return false;
Iv'e left this one up long enough and no one has an answer!

Categories