How to display form inputs without loosing data entered before refresh the page? I mean After refresh my page I want to display all the values entered in forms.
I have 2 inputs One is select option and one is text.
<input type="text" name="worked_month" value="<?php echo $_SESSION['worked_month']; ?>" />
<select name="sex">
<option value="">Select Sex</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
I am using following PHP code to display text enter before I refresh the page
isset($_POST['worked_month'])?$_SESSION['worked_month'] = $_POST['worked_month']:$_SESSION['worked_month']="";
It works fine but don't know how to select the option that are selected before refresh. But I don't have to always select same default value. User can select any value
Explanation. For each option, check if the post variable matches the value and then use selected attribute to select the matched option.
<select name="sex">
<option value="">Select Sex</option>
<option <?php echo isset($_POST['sex']) && $_POST['sex']=='male'? 'selected="selected"' = '' ?> value="male">Male</option>
<option <?php echo isset($_POST['sex']) && $_POST['sex']=='female'? 'selected="selected"' = '' ?> value="female">Female</option>
</select>
To select option you have to use PHP dynamic variable.Check this reference
<?php
$sex = $_SESSION['sex'];
${$sex.'_checked'} = "selected";
?>
<select name="sex">
<option value="">Select Sex</option><option value="male" <?php echo $male_checked; ?> >Male</option><option value="female" <?php echo $female_checked; ?>>Female</option></select>
Dynamic variable: automatic convert your selected value into variable whose value is "selected".
I just made something like that saving the values at Local Storage and then retrieving them:
//Saving the input values at local storage
var temp = [];
$('.keep-values').each(function(){
temp.push({
id:$(this).attr('id'),
value:$(this).val().trim(),
checked:$(this).is(':checked')
});
});
localStorage['valuesCache'] = JSON.stringify(temp);
Then i retrive the values and i populate the fields:
//Retrieving the values from local Storage and populating the inputs
var tmp = JSON.parse(localStorage['valuesCache']);
for(i in tmp) {
$('#'+tmp[i].id).val(tmp[i].value);
if(tmp[i].checked){
$('#'+tmp[i].id).attr('checked','');
}
}
I think thats a good start for your final solution, read more about Local Storage
Related
I’m making an interface with 2 select lists that are interconnected with each other, so what I want is:
If the user selects an option in the category dropbox the second select list will show all the options in that category.
<hmtl>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option>
<?php }
?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) {?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option> <?php }
?>
</select>
</hmtl>
I took some to write some code according to your problem. While writing this, I assumed that you have a relationship between the two tables where you have stored the categories and the options. I assumed that the relationship is using "Gradelvl_ID". I also assume that you have some knowledge in JavaScript, jQuery, and AJAX.
Based on that, I created the code below.
This would be your selection area.
<hmtl>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="cat" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php } ?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="options" ></select>
</body>
</html>
This script is using jQuery, so you need to link the jQuery library to you above page. Also you can have this script inside the first page using <script></script> tags or attached as a .js file separately.
$(document).ready(function(){
$(document).on('change', '#cat', function(){
$.ajax({
url: 'getOptions.php',
type: 'get',
data: {
catId: $(this).prop('id')
}
}).then(function (response) {
$('#options').html(response);
});
});
})
The code above will send the selected ID to the getOptions.php which will contain the PHPto select all the options according to the sent ID number from you options table. Then, if the selection is successful, it will send the data back which will be captured by the AJAX code above and draw the options inside the second drop down.
<?php
include_once('dbconnect.php');
//I'm not a big mysqli user
if(!empty($_GET["id"])){
$results = $conn -> prepare("SELECT * FROM <your table name> WHERE id = ?");
$results -> bind_param('i', $_GET["id"]);
$results -> execute();
$rowNum = $results -> num_rows;
if ($rowNum > 0){
while($optRows = $results -> fetch_assoc()){ ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php
}
}
}?>
Also, pay attention to the code above. I'm using prepared statements, which is a very good habit to get into. Look it up here.
As I said, I was assuming some part of the code and used the information given by you, and I hope you do some more research and make the code above work for you.
Try This Code:
$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
Do one thing
1-Keep your second dropdown empty.
2-Call jquery ajax to get the first dropdown value on change
create a new page where only db connection is defied after that process the sql with respect to the first dropdown selected value
3-get the response to ajax method and get the output
I have multiple dropdowns and want to filter the contents of the second dropdown based on what is selected in the first dropdown. Here is the following code that I have so far. How could I do this?
HTML/PHP:
<td>
<select id="major" onChange="updateCat();">
<?php foreach ($dropdown_major->fetchAll() as $drop_major): ?>
<option
value=""
data-name="<?php echo $drop_major ['Major Category'];?>"
>
<?php echo $drop_major ['Major Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<select id="minor">
<?php foreach ($dropdown_minor->fetchAll() as $drop_minor): ?>
<option
value=""
data-name="<?php echo $drop_minor ['Minor Category'];?>"
>
<?php echo $drop_minor ['Minor Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
JavaScript:
function updateCat() {
var e = document.getElementById("major");
var majorSelected = e.options[e.selectedIndex];
document.getElementById("minor").value = majorSelected.dataset.name;
}
Database connection and SQL statements:
<?php
$host="xxxxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxxxx";
$dbPass="xxxxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql_major = "SELECT DISTINCT [Major Category] FROM ProductTable ORDER BY [Major Category] ASC";
$sql_minor = "SELECT DISTINCT [Minor Category] FROM ProductTable ORDER BY [Minor Category] ASC";
$dropdown_major = $dbh->query($sql_major);
$dropdown_minor = $dbh->query($sql_minor);
?>
Sorry don't have much time can't make your answer for your code but giving you an example which will surely help you. run snippet below.
HTML
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br>
<select id="second"></select>
and Javascript
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
this code will work for you but try to use JSON for sending options to user and then apply some if else statement according to user selection of first drop down.
Tip: If you have large no. of options in select statement or large no. of select statements in your code then go and learn AJAX First. its easy and simple you can learn it easily. JSON and AJAX hardly takes 2-3 days.In Ajax call function according to user selection and send data using JSON. Although Ajax increases no. of request to server but it will decrease code length. which decreases page load time, easy to maintain, and good for search engine. Google love pages with less code and more information and will help you in future too to solve lots of problems easily.
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br><br>
<select id="second"></select>
I have this script for money conversion so user can choose it's currency from the list like Us to Euro so I want to make it remain same after page refresh like if user have chosen Euro and he refresh the page it should remain same.
Here is my Javascript and Code
<script>
function updatePrice(val) {
p = document.getElementById("original_price").value;
newp = p * val;
document.getElementById("calculated_price").value = newp;
}
</script>
Php Code:
<?php
$pr = 180;
?>
<select onchange="updatePrice(this.value)">
<option value="1">US</option>
<option value="98">RS</option>
<option value="61">Ind</option>
</select>
<input type="hidden" id="original_price" value="<?php echo $pr; ?>" />
Price: <input type="text" id="calculated_price" value="<?php echo $pr; ?>" />
Update 1 After Implementing Session
<?php
session_start();
// store session data
$_SESSION['value']=".updatePrice(this.value).";
if(isset($_SESSION['value']));
?>
<?php
$pr = 180;
?>
<select onchange="<?php echo $_SESSION['value']; ?>">
<option value="1">US</option>
<option value="98">RS</option>
<option value="61">Ind</option>
</select>
<br>
<hr>
<input type="hidden" id="original_price" value="<?php echo $pr; ?>" />
Price: <input type="text" id="calculated_price" value="<?php echo $pr; ?>" />
<script>
function updatePrice(val) {
p = document.getElementById("original_price").value;
newp = p * val;
document.getElementById("calculated_price").value = newp;
}
</script>
Actually PHP dosent offer any viewstate mechanism, as far as i know , So what you can do is store this in some hidden field.The best way and my personal recommendation is to use a session variable for this purpose
http://www.w3schools.com/Php/php_sessions.asp
And if you need to solve this issue using javascript, You can use Cookies too
http://www.w3schools.com/js/js_cookies.asp
I have done this using jquery and javascript by setting a cookie, hence i dont want you to get confused with jquery plugin for cookie. You can do this in a much more simpler way using jquery plugin for cookie.
Here's the code
HTML
<select id="selectCurrency">
<option value="1">US</option>
<option value="98">RS</option>
<option value="61">Ind</option>
</select>
jquery/javascript
$(document).ready(function(e){
var name = "Currency=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++){
var c = ca[i].trim();
if (c.indexOf(name)==0) $('#selectCurrency').val(c.substring(name.length,c.length));
}
});
$('#selectCurrency').change(function(e){
var cookieVal = "Currency="+$(this).val();
document.cookie = cookieVal ;
});
Fiddle
http://jsfiddle.net/AmarnathRShenoy/HM3Zj/
You can use session or store the selected values somewhere in database, inUpdate price function make an ajax call which stores, your selected value and keep pdating at, on onchange event. now, each time your page gets refreshed, the previuosly selected value will get fetched from the database and you can show it seleted.
I currently have a javascript function, which changes a select option to 1 if a checkbox is checked. What I can't seem to figure out, is how to automatically check the box if the user fails to tick the checkbox and just chooses a value (other than 0) from the select dropdown. The script has ID's and names that are generated with php array values.
Thank you for taking the time to look at this.
function quantityChangeHandler(source) {
var qtyElem = document.getElementById(source.getAttribute('rel'));
if (source.checked) {
if (qtyElem.value == 0)
qtyElem.value = 1;
}
else
qtyElem.value = 0;
}
<input type="checkbox" onclick="quantityChangeHandler(this)"
name="prodid[<?php echo $prodid;?>][]" rel="prodqty_<?php echo $prodid . '_' . $contactid; ?>"
value="<?php echo $contactid; ?>" /><br />
Qty
<select id="prodqty_<?php echo $prodid . '_' . $contactid; ?>"
name="prodqty[<?php echo $prodid; ?>][<?php echo $contactid; ?>]">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
You should add a similar handler and rel attribute to the select tag, and set source.checked based on the value of the select element.
Add this to your Javascript:
function selectChangeHandler(source) {
var checkboxElem = document.getElementById(source.getAttribute('rel'));
checkboxElem.checked = source.value != 0;
}
Example changes to HTML:
<input id="checkbox_0" ... />
...
<select ... rel="checkbox_0" onchange="selectChangeHandler(this)">
...
Working JSFiddle
From my understanding manually trigger the checkbox selection is by triggering the click event.
say you checkbox id = "mychkbox"
then using the jquery you can do by $('#mychkbox').trigger('click');
this makes the check box selected selected.
and your check condition for if checkbox is selected or not.
I have a problem with my javascript. First of all here is my code partitions:
<select class="inputTxt" style="width: 120px;" id="yearCombo" name="yearCombo">
<option value="0">2013</option>
<option value="1">2012</option>
<option value="2">2011</option>
</select>
function searchClicked() {
var operationField = document.getElementById("<%=FeedbackReportCtrl.PARAM_OPERATION%>");
operationField.value = "<%=FeedbackReportCtrl.OPERATION_SEARCH%>";
var yearFilter = document.getElementById("<%=FeedbackReportCtrl.PARAM_YEARFILTER%>");
yearFilter.value = document.getElementById("yearCombo").options[document.getElementById("yearCombo").selectedIndex].text;
var mainForm = document.getElementById("main");
mainForm.submit();
}
Here what goes wrong is the following;
For example, when I choose the year 2011 from the combo box and then hit the search button, it brings me the desired results;however, the selected index of the box returns back to 2013. How can I sustain my selection after search function?
The issue you have isn't a javascript one. When you submit a form you refresh the whole page, removing any client-side (user or javascript) adjustments to it.
It should be set by the php/java that is generating the page you post your form to, to set a selected="selected" or relevant, based on the value you just posted.
In php this would be
if($_POST['year'] == '2013') echo ' selected="selected"';
In java or jsp there are similar ways of doing this. Javascript itself could do the same probably.
Submitting the form refreshes the page (unless done via AJAX), thus returning to the default selected value, i.e the first one.
To overcome this you need to send along with the form the chosen year - assuming that you are self-submitting - and explicitly mark this year as the selected option.
In PHP Your code would then be something like:
<?php $year = $_POST['year']; ?>
<select class="inputTxt" style="width: 120px;" id="yearCombo" name="yearCombo">
<?php for ($i=2013;$i>2010;$i--): ?>
<option value="<?php echo $i; ?>" <?php if ($year==$i) echo "selected"; ?> >
<?php echo $i; ?>
</option>
<?php endfor; ?>
</select>