html Select not saving data after history.back() is callled - javascript

I am building a form using phpmailer, witch consists of 3 steps: the form itself, information confirmation page and mail sent message page. When the user is on the information confirmation page, he is able to go back and correct the information that was written, by busing onclick="history.back();". Everything is working fine, all fields remain written as the user did, with exception of a select button for years that is using the following code:
<select id="f_year" name="f_year" data-validation-engine="validate[required]" class="validate[required]"></select>
<script>
var start = 1900;
var end = new Date().getFullYear();
var options = "<option disabled selected value>年</option>";
for(var year = start ; year <=end; year++){
options += "<option>"+ year + "年" + "</option>";
}
document.getElementById("f_year").innerHTML = options;
</script>
When its clicked to correct the information, the data from this select element is not saved at all.
What should I do?

Check the following out. This is a Minimal, Complete and Verifiable Example of your problem scenario.
As you can see, there are two SELECT elements, that one is hard-coded and the other is dynamically generated (the same script that you have provided).
<html>
<body>
<select>
<option value="Val1">V1</option>
<option value="Val2">V2</option>
<option value="Val3">V3</option>
<option value="Val4">V4</option>
<option value="Val5">V5</option>
</select>
<select id="f_year" name="f_year" data-validation-engine="validate[required]" class="validate[required]"></select>
<script>
var start = 1900;
var end = new Date().getFullYear();
var options = "<option disabled selected value>年</option>";
for(var year = start ; year <=end; year++){
options += "<option>"+ year + "年" + "</option>";
}
document.getElementById("f_year").innerHTML = options;
</script>
<button onclick="window.location='confirm.php'">Proceed</button>
</body>
</html>
When you try running this, you'd see that the hard-coded one stays intact, while the dynamically generated one resets, when you navigate back to the same, from the confirm page.
What happens is, when you navigate back, the scripts on the page will execute from the beginning, changing the values, hence the dynamically generated inputs will be reset. Only the static content could be kept intact. To keep the dynamic stuff intact, you will need some extra work.
This question looks similar to your problem scenario, which is suggesting something for those extra work you need to do to preserve the dynamic content.

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>

Javascript change currency always choosing first <option> from <select> dropdown list

Hi I've been modifying a script that got the data from <span id=> to instead use a <option value=> from a dropdown list and it seems to work except for always choosing the first <option value=> in the list. If i arrange the order of the html list the first currency will be what it converts to onChange.
Here is the script and html
function ChangeCurrency() { $('select').click(function () {
var cc = $(this).children('option').attr('value').substring(1);
document.cookie = 'CurrencyId=' + cc + ';path=/';
var s = location.pathname;
if (s.length > 3 && s.substring(3, 4) == '/')
s = s.substring(3);
location.pathname = s;
})};
<select onchange="ChangeCurrency()">
<option value="c1">USD</option>
<option value="c2">EUR</option>
<option value="c3">AUD</option>
etc...
</select>
I don't know what I'm doing wrong? How can I get it to actually process a user selected option from the list (and hopefully keep that option displayed so the list doesn't show USD when the currency on the store is changed to AUD for example)
EDIT:
I need to keep how this code gathers data to "build" the cookie, I don't understand enough to know what string it is putting together from the option list to name the cookie but it is important for the store currency to work. This is the code that worked but the list was a div with span id for the option value. It took me a while to get it sort of working using option values rather than span id's except for being stuck on the first option in the list.
Your code just fetches the first option, not the selected one.
Change the:
var cc = $(this).children('option').attr('value').substring(1);
to:
var cc = $(this).val();

Pass Selected Radio Value to PHP using onclick, then opening php file to use value in SQL query

I am pretty new to coding php and javascript but have manged to scrape my way through so far. However, I have hit a wall. I'm not 100% sure that what I'm trying to do can be done, or that I'm even attempting it in an effective way.
I have a dynamically filled table, made of rows from a SQL statement using php. On each row is a radio button, each one given a unique value based on the row number (a unique value in one of the database columns). I am attempting to program a button that enables the user to pass a selected radio button value to a separate php enabled page that will allow the user to edit the row information using the unique row value. Also, i used the confirm option, because I would also like to add an if else statement that allows the user to cancel, if the wrong row was selected (I haven't attempted that yet because I haven't been able to get the value to pass).
Page button
<input type="button" id="edit_order_button" value="Edit Order"></input>
JQuery page
$(document).ready(function(){
$("#edit_order_button").click(function(){
var selected = $("input[name ='order_edit_select']:checked").val();
var r = confirm("Confirm Order Number to edit: " + selected);
$.post("php/editOrder.php", {
selected1: selected
}, function(data,status) {
//alert("Data: " + data + "\nStatus: " + status);
window.open("php/editOrder.php","Edit Order","menubar=1,resizable=1,width=750,height=600, left=250, top=50");
});
});
});
PHP end destination
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
require('config.php');
$selected2= isset($_POST['selected1']) ? $_POST['selected1'] : ''; // Fetching Values from URL
echo "Selected Row number is ".$selected2.".";
mysqli_close($connection); // Connection Closed.
?>
I have tried a few things but have so far been unsuccessful in getting the new window to load with the value of the radio button passed. Currently, the window loads, but the new window only displays the echo text, no variable. When I run with the alert popup, the data shows me the value of the selected row but it does not seem to be posting to the new page prior to the window.open command. Any tips would be appreciated, or if i'm approaching the problem from a wrong angle, any insights would also be great. I have also tried debugging, thinking I was missing a parentheses or semicolon but I wasn't able to find anything. Thanks
Looks to me like you can get rid of the post statement altogether and just pass the selection to the newly opened window.
$(document).ready(function(){
$("#edit_order_button").click(function(){
var selected = $("input[name ='order_edit_select']:checked").val();
// only open window if order okayed
if ( confirm("Confirm Order Number to edit: " + selected) ) {
window.open("php/editOrder.php?selected1=" + selected,"Edit Order","menubar=1,resizable=1,width=750,height=600, left=250, top=50");
}
});
});
php/editOrder.php:
$selected2 = $_GET['selected1'];
echo "Selected Row number is $selected2.";

Javascript to pass var onclick select and checkbox

So my page has two columns. On the right column the results are displayed.
The results include all the elements. On the right column i have a and few check boxes. I am able to populate the checkboxes depending on the option selected in .
I have to click submit to get the data on the right column. I don't want AJAX. I want the page to be refreshed with the option in selected and the results to be displayed based on that. I am able to code the php part. To GET the value of the option selected in
So my code is :
<select id="theselect" onclick = "afterChange()">
<option value="0"> Select the Department </option>
<option value="11"> Department11 </option>
<option value="22"> Department22 </option>
<option value="33"> Department33 </option>
</select>
var url = location.href;
document.getElementById("mydiv").innerHTML = url;
function afterChange(){
var dept = document.getElementById("theselect").value;
if (dept && dept!= 0) {
var myline = url + "&dept=" + dept;
document.getElementById("mynewdiv").innerHTML = myline;
window.location= myline;
}
}
<p id='mydiv'> </p> <br />
<p id='mynewdiv'> </p>
<?php
if(isset($_GET['dept'])) {
$cat = $_GET['dept'];
echo "You are now searching in $cat";
//code to show content from database for that department
?>
I know that there is a better way to do this which m unaware of. So far the code works fine for the first time. I am able to get the results from the DB according to the SELECT option.
But when i change the select, it takes the entire URL again and adds the new value of SELECT to the URL, that confuses PHP.
So if my site URL is :
http://mysite.php?dept=22
After changing SELECT 2nd time, it changes to
http://mysite.php?dept=22&dept=33
I also have few checkboxes after the SELECT.
I want the results to be sorted based on the select and the checkboxes.
I know there must be an easy way to do it, but i am struggling to find it.
Please help me in understanding this concept. Thank you so very much.
With
var url = location.href;
You will always get the current url. Means on 2nd refresh the url will be http://mysite.php?dept=22 now you add your dept again:
var myline = url + "&dept=" + dept;
Which produces the error you described.
To handle this problem you have to strip the old parameter first or if you only need one parameter do something like:
var url = location.origin + location.pathname
instead of location.href for more information you can read this

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