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>
Related
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 a form with an option menu with Staff_Names that gets its data from "Staff" table:
<select class="form-control" name="Name" id="Name">
<option value="">select staff</option>
<?php do { ?>
<option value="<?php echo $row_Staff['Staff_Name'] ?>">
<?php echo $row_Staff['Staff_Name']?></option>
<?php } while ($row_Staff = mysql_fetch_assoc($Staff));
$rows = mysql_num_rows($Staff);
if($rows > 0) {
mysql_data_seek($Categories, 0);
$row_Staff = mysql_fetch_assoc($Staff);
}
?>
</select>
The "Staff" table also has the staff member's Email. The form elements are inserted into a new table called "Training". I would like to select the Staff_Name from the option menu and insert the Staff_Name and Email in separate fields in the Training table. I have tried explode("-", $_POST['Name'] method from How to post two values in an option field? but feel there has to be a more efficient way. I don't want to continue to explode every time I need to echo in subsequent pages. Also, explode only works in this method by exploding on another page. Would like to store both fields from form when inserting into Training table. Does anyone have an efficient method?
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
Building a football prediction website. I am getting thee Home_team names and away team a names from fixtures table in DBMS, with corresponding drop down boxes for each fixture so that the user can predict the score. I cant get it to work. Grateful for any help!
//establish connection
<?php
$connection = mysql_connect('localhost', 'root', 'password');
mysql_select_db('mls');
$query = "SELECT * FROM fixtures WHERE Fixture_ID BETWEEN '1' and '10' ";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if($num>0){
echo"<table>";
echo "<th>Home Team</th>";
echo "<th>Home Score</th>";
echo "<th>Away Score</th>";
echo "<th>Away Team</th>";
for($count=0;$count<$num; $count++){
$row = mysql_fetch_array($result);
echo"<tr>
<td>".$row['Home_Team']."</td>
<td>
<form id="myForm" method="post" action="process3.php">
<select name="Home_Score">
<select id='H".$count."'>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select >
</td>
<td>
<form id="myForm" method="post" action="process3.php">
<select name="Home_Score">
<select id='A".$count."'>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
<td>".$row['Away_Team']."</td>
</tr>";
}
echo"</table>";
<input type="submit" title="Submit the form">
</form>
}
?>
<html>
<?php
//process3.php file
<?php
include_once('db.php');
$Home_Score = $_POST['Home_Score'];
$Away_Score = $_POST['Away_Score'];
if(mysql_query("INSERT INTO user_prediction VALUES('$Home_Score', '$Away_Score')")){
$result = "Successfully Inserted";
else
$result = "Insert failed";
?>
//myscript.js file
?>
$("#sub").click(function(){
$.post( $("#myForm).attr("action"), $("#myForm:input").serializeArray(),
function (info){$("#result").html(info);});
});
$("#myForm").submit(function(){
return false;
});
While there is plenty of things that could be causing problems, notice here:
<select name="Away_Score">
//count id for unique values in dropdown
<select id='A".$count."'>
$count will literally be represented here as the string "$count", due to this code not being contained in PHP tags. Try correcting instances of code similar to this to something like below:
<?php
echo '<select name="Away_Score">';
//count id for unique values in dropdown
echo '<select id="A' . $count . '">';
?>
I see some problems there..
you switch between PHP and HTML appearently without knowing what
is what or how you start PHP and end it.
Your table is messed
up. You open a table, but in mid you just forget about it. you dont
close your td-tags or your table.
your select is messed up. You
have 2 select tags, one of which has even unescaped php-code written
in it.
your JS click-event does not trigger, because you named
it wrong.
Apart from you using mysql_-functions, which are deprecated and will stop working in newer PHP vewrsions, the list goes on...
In short: This code is a complete mess. Erasing this and starting all over with a clear head would be the best option.
To digress a bit, I honestly think that for an app of that size you should be employing some open source PHP packages. Sorry I can't comment yet so had to leave as an answer
I had two chained Select Boxes "pr_cat" and "sl_num" . The second select box values depend on the value selected in the first select box.
<tr>
<td width="257">Select Product Category:</td>
<td width="197">
<select name="pr_cat" id="Validprcat" onChange="reload(this.form)"><option value="">< Select one ></option>
<?php while($prd=mysql_fetch_object($select_query1)) {
if ($prd->cat_id==$pcat) { ?>
<option selected value="<?php echo $prd->cat_id?>"><?php echo $prd->category_name?> </option>
<?php } else { ?>
<option value="<?php echo $prd->cat_id?>"><?php echo $prd->category_name?></option>
<?php }}?>
</select>
</td>
</tr>
<tr>
<td>Select Serial Number:</td>
<td>
<select name="sl_num" id="Validslnum" onChange="reload2(this.form)"><option value="">< Select one ></option>
<?php while($slnum=mysql_fetch_object($quer)) {
if ($slnum->serialno==$pcat2) { ?>
<option selected value="<?php echo $slnum->serialno?>"><?php echo $slnum->serialno?> </option>
<?php } else {
?>
<option value="<?php echo $slnum->serialno?>"><?php echo $slnum->serialno?></option>
<?php }} ?>
</select>
</td>
</tr>
<tr>
I used the form reload javascript to reload the page with the value selected in the Select Box. I used GET method.
<script language=JavaScript>
function reload(form)
{
var val=form.pr_cat.options[form.pr_cat.options.selectedIndex].value;
self.location='delivery.php?pcat=' + val ;
}
function reload2(form)
{
var val=form.pr_cat.options[form.pr_cat.options.selectedIndex].value;
var val2=form.sl_num.options[form.sl_num.options.selectedIndex].value;
self.location='delivery.php?pcat=' + val + '&pcat2=' + val2 ;
}
</script>
But I want to do it using POST method how to do this ?
If you don't want to use ajax, and do it via POST method, so instead of
onChange="reload(this.form)"
call
onChange="formSubmit();"
<script>
function formSubmit()
{
document.getElementById("frm1").submit(); //frm1 is form id
//OR you can use
//document.frm1.submit(); //frm1 is form name
}
</script>
Note :- if you have any submit button in this form, don't keep it's name as submit, else you will have issues in your code.
I think what you're asking is pretty much this: JavaScript post request like a form submit
However, why do you want to reload the page at all instead of doing an AJAX call?
I give you the most simple and fastest way to do what you wanted,
AJAX:
cover both select box with '' tag,
<div id='first_select'>
<select id='first' onchange='populate_second_select(this.value)'>
<option>Select</option>
</select>
</div>
<div id='second_select'>
<select>
<option>Select</option>
</select>
</div>
call populate_second_select() function upon change done in first select box.
No in ajax,
function populate_second_select(value)
{
$.ajax({
method:'POST',
url:'ajax.php',
data: {value:value},
success:function(result)
{
document.getElementById("second_select").innerHTML=result;
showLightBox();
}
});
}
This is how your javascript function should look like,
on your ajax.php file, process the DB based on chosen value and 'echo' the whole select tag (second tag). That's it.
Here are few links would help you to get this done.
Link_1Link_2