keep spring form select value - javascript

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.

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>

Re-select option value after AJAX response

I have a pretty simple form I'm building out using PHP, AJAX and jQuery. The form consists of a select box of the existing people that is populated from the database. Underneath is common contact information (Address, City, Phone, etc.) When the page is loaded, the form is empty except for the select box containing the people.
The basic idea is that when the user selects a person, it should populate that person's contact info into the form. The form appears as a modal window, so I do not want the page to refresh, so I'm sending an AJAX request to the server passing the unique ID and in turn, the server responds with a JSON-encoded PHP array with that person's contact info. I am taking that information and populating the form.
All of this is working as I need except for the data that should go into select boxes (e.g. State). I am successfully retrieving the proper state value and have validated that value matches the options in the select, but I cannot get it to change the selected value in the select box.
Here are the highlights of my code:
<!-- abridged generated HTML -->
<select name="PersonID" id="PersonID">
<option value="1">Mike</option>
<option value="2">Jim</option>
<!-- etc... -->
</select>
<input type="text" id="City" />
<select name="AttState" class="selectpicker" id="AttState">
<option>State</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<!--And so on... -->
</select>
<!-- etc... -->
And then the Javascript...
$(document).ready(function() {
// This will pre-select when the form is initially loaded
var selState = "TX";
$("#PersonID").on('change', function(e) {
personId = $("#PersonID").val();
$.getJSON('GetPersonInfo.php?q=' + personId, function(data) {
$.each(data, function(key, val) {
$("#City").val(val.City);
selState = val(val.State);
// Plus all of the others...
});
});
$("AttState").val(selState);
});
When the form initially loads, the State is getting preselected to Texas; however, when the person is chosen and selState changes (validated by an alert), it doesn't get set to the correct value. I have read some posts that seem to revolve around ensuring that the JavaScript code living inside of the $(document).ready(function() function, so I suspect that the AJAX call doesn't retrigger the function. I cannot figure out how to make it work.
You should placed this code $("AttState").val(selState); inside success callback of AJAX request like so :
$.getJSON('GetPersonInfo.php?q=' + personId, function(data) {
$.each(data, function(key, val) {
$("#City").val(val.City);
selState = val(val.State);
// Plus all of the others...
});
// its depend on your code whether inside .each() or not
$("#AttState").val(selState);
});

jQuery how to keep selected option for dynamically created list on page reload

Got a select list that populates using javascript, each time the page reloads the list is reset. and the selection selected by the user is lost, however for all other input options such as radio button, checkboxes or text fields no data is lost.
//example of dynamcially generated options for a dropdown list
<p id="question">How old are you (in years)?</p>
<select id="q1" name="age" style="width:157px;"></select>
<script language="Javascript"> initializeAgeList("Select Your Age",100); </script>
//example of static options for a radio button set
<p id="question">Are you male or female?</p>
<input type = 'radio' name ='q3' value= 'male' required>Male<BR>
<input type = 'radio' name ='q3' value= 'female'>Female
Tried using a global var to determine if the list was already set, but that proved not to work
var isAgeSet = false; //global var
function initializeAgeList(default_selection,limit ){
if(!isAgeSet){ //checks to see if list has already been set, on page refresh is set to zero
var i = 0;
while (i <= limit){ //adds options until limit is reached
if(i==0){
$("#q1").append(new Option(default_selection,i));
}else{
$("#q1").append(new Option(i,i));
}
i++;
}
isAgeSet = true;
}
};
How can I prevent the loss of the user's selected option in a dropdownlist using jQuery?
It sounds like you want to persist your data between page postbacks.
You should save your selected data and read it when page loads (if there is saved data).
The data can be saved to a server (database / file) or on the client (local storage).
Hope this is what you needed...
Yaniv

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

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>

How do I refresh an html element?

I've tried searching for any possible solutions to my question but none of what I've seen so far works. Anyway, I'm using MVC 3 and I have a form called Add Event. On that page, I have a dropdownlist that contains a list of locations that the user can choose from. I have a link just below that dropdownlist that would allow a user to add a new location. Now, I have the textboxes, dropdowns, etc for creating a new location in a partial view which would appear below the dropdownlist when I click on the link.
Anyway, I need to refresh, just the dropdownlist so that when I add a new Location, it goes right on the list. What happens right now is after I click on save, the partial view hides itself and I still need to refresh the entire page to get the new location on the dropdown list which would then, remove everything I typed in on texboxes and dropdownlists on the same page.
How can I do this using javascript/ajax?
With jQuery you can reload only the element you want:
$('#menu').load("myServerScript.php #menu");
http://api.jquery.com/load/
This might help you..
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = Text;
opt.value = Value;
// Add an Option object to Drop Down
document.getElementById("YourDropDownID").options.add(opt,null);
this can be done with jQuery.
My way of doing it would be like this. Assuming that you have a form that looks something like this:
<form method="post" action="#">
<select id="myList" name="myList">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>
<input type="text" id="newValue" name="newValue" />
add new value
<input type="submit" value="Submit">
</form>
Where myList is dropdown you want to add a new value and refresh, newValue is the text field to receive the new values to be added to the dropdown (myList) and the link with id btn is the add button. You can add a jQuery that would look something like this:
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function (event) {
event.preventDefault();
$.post("/home/addvalue", { value: $("#newValue").val() }, function (result) {
if (result != null) {
$("#myList").append("<option value='" + result.id + "' selected='selected'>" + result.text + "</option>");
}
});
});
});
</script>
What I'm is when you click on the link (btn) I collect the value (and just that value) from the text box and do POST (a form submit) to the server.
I'm guessing you're expecting the server to give some sort of answer that includes the newly inserted value's id.
If the server sends back that new id, I then append the the new result to list (and set it as the selected one)
On the server side you code could look something like this
[HttpPost]
public JsonResult AddValue(FormCollection collection)
{
//do database inser for the new value and get the id
var response = new Dictionary<string, object>();
response.Add("id", 3);//3 here represents that last id
response.Add("text", collection["value"]); //the value you sent for the new option
return Json(response);
}
you receive the the POST(ed) data and do save to the database. Once the value is saved and you have the new id save in into a dictionary that you'll then serialize and send back as json the javascript above.
This would update your form, so you when you actually hit submit myList value would be the new value.
Hope this helps (and if does, please accept the answer)

Categories