My drop down is showing blank then when i select the value of dropdown the same value is showing, but i have to show dropdown value as select first then when I click on button the respective value should show
I am doing a Php program
<form class="form-horizontal" name="form" method="post" action="<?php $_PHP_SELF?>">
<label for="courseDisp" class="col-sm-2" style="margin-top:10px;">Course : </label>
<?php
$course="SELECT * from course";
$res= $conn->query($course);
if($res->num_rows>0)
{
echo '<select name="courseDisp" id="courseDisp" class="form-control col-sm-3" style="margin-top:8px;display:inline;padding:10px;">';
echo '<option value="0" selected> -- SELECT --</option>';
while($row=$res->fetch_assoc())
{
echo '<option value='.$row["course_id"].'>'.$row['shortname'].'</option>';
}
echo '</select>';
} else {
echo "0 result";
}
?>
<label for="yearDisp" class="col-sm-2" style="margin-top:10px;">Year : </label>
<?php
$year="SELECT distinct(year) from syllabus";
$res= $conn->query($year);
if($res->num_rows>0)
{
echo '<select name="yearDisp" id="yearDisp" class="form-control col-sm-3" style="margin-top:8px;display:inline;padding:10px;">';
echo '<option value="0">-- SELECT --</option>';
while($row=$res->fetch_assoc())
{
echo '<option value='.$row["year"].'>'.$row['year'].'</option>';
}
echo '</select>';
} else {
echo "0 result";
}
?>
<script type="text/javascript">
document.getElementById('courseDisp').value = "<?php echo $_POST['courseDisp'];?>";
document.getElementById('yearDisp').value = "<?php echo $_POST['yearDisp'];?>";
<input type="submit" class="btn col-sm-2" style="margin-left:15px;margin-top:10px;width:60px;font-weight:bold;font-size:15px;" value="GO" name="btnGo" id="btnGo" />
</form>
I think you are doing it in a wrong way:
your code should look like this
<script type="text/JavaScript">
var valueSelected=document.getElementById('course').value;
alert(valueSelected);// do here according to the need
</script>
This is because there is no $_POST variables present before you submit a form.
$_POST variables can only be 'accessed' whenever a POST form is submitted, so when the form is not submitted, $_POST['course'] will be undefined. If you want to use persistant, but also relative variables, use $_GET.
This can be done the following way:
<script type="text/javascript">
document.getElementById('course').value =<?php echo $_GET['course'];?>";
</script>
(this will cause an error if value is not set, make sure to make exceptions for that, using if statements in PHP)
but the value also needs to be fetched from the URL.
so your url needs to have ?course=<course_value> in it, for example:
https://example.com/index.php?course=Course%201
Click here for more about POST vs GET requests
Instead of setting the value with javascript, you should directly write the selected attribute.
<select name="course">
<?php foreach ($options as $key => $value): ?>
<option value="<?= $key ?>"<?php if ($key == $_POST['course']) echo " selected" ?>>
<?= $value ?>
</option>
<?php endforeach; ?>
</select>
If you have to do this in javascript, keep sure, you use the correct syntax. Your example has a wrong " at the end of the line. Also you should use json_encode, if you want to output vars into javascript. And a last thing - if you don't put this inside the document ready event, the script has to be placed after the select element, which you wan't to manipulate
<select name="course">...</select>
...
<script type="text/javascript">
document.getElementById('course').value = <?= echo json_encode($_POST['course']) ?>;
</script>
Needed to keep the <option value="">-Select-</option>
Related
I'm having trouble setting the value of the dropdown after the form input refreshes the page. I can get the value but no matter what I try I'm unable to set the dropdown after the page refreshes. I've tried a number of different ideas I've found online too. I've tried both JavaScript and PHP solutions and all I can do is get the value but not set it. This is the code I have so far, which returns the drop down ID, I just need to know how to use it. I appreciate any help, thanks!
<?php
$pdo = new PDO('mysql:host=localhost; dbname=db', 'root', 'password')'
$sql = "SELECT divid, division FROM divisions ORDER BY division ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$divs = $stmt->fetchAll();
?>
<form method="post">
<select id="divi" name="divisions">
<?php foreach($divs as $div): ?>
<option value="<?= $div['divid'];?>"><?= $div['division']; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['divisions'])){
$selected = $_POST['divisions'];
echo 'Selected: " . $selected;
} else {
echo 'Select division.';
}
}
?>
It's not very clear to me what you really want, however it looks like you want to select default:
<select id="divi" name="divisions">
<?php foreach($divs as $div): ?>
<option <?php echo ("mycondition ex: 'id == 1'") ? "selected" : NULL ?> value="<?= $div['divid'];?>"><?= $div['division']; ?></option>
<?php endforeach; ?>
</select>
You are simply missing any code that sets 'selected="selected"' in the HTML for the select field.
Also, your code is very hard to read so I've cleaned up the loop a little bit.
<form method="post">
<?php
echo '<select id="divid" name="divid">';
foreach ($divs as $div) {
$selected = '';
if (isset ($_POST['divid']) && ($_POST['divid'] == $div['divid'])) {
$selected = 'selected="selected"';
}
echo '<option value="' . $div['divid'] . '" ' . $selected . '>' . $div['division'] . '</option>';
}
echo '</select>';
If I generate a select list using PHP from the results of a database query, for some reason I can't then use Javascript to get the value of the currently selected item. I tested this code with a static list and it works no problem. Here is my code:
<?php
require_once("config.php");
$sql="SELECT * FROM animals ORDER BY name ASC";
try
{
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_UNIQUE); //each column is addressed by the primary key
}
catch (Exception $ex)
{
echo $ex->getMessage();
}
?>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function(){
$("#animal_list").change(function(){
var animalValue = $(this).val();
window.location.href="animal_list.php?id=" + animalValue;
});
});
</script>
</head>
<body>
<select id="animal_list" name="animal_list">
<?php
foreach($results as $res)
{
?>
<?php echo '<option value="'. $res['id'] . '">' ?>
<?php echo $res['name'] ?>
</option>
<?php
}
?>
</select>
<br/><br/>
<?php
if(isset($_GET['id']))
{
echo '<input type="text" id="npsw_code" value="' . $_GET['id'] . '" readonly>';
}
else
echo '<input type="text" id="npsw_code" value="" readonly>';
?>
</body>
</html>
Testing with a static list works. Here is the example:
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function(){
$("#fruits").change(function(){
var fruitValue = $(this).val();
window.location.href="fruits.php?id=" + fruitValue;
});
});
</script>
</head>
<body>
Fruits
<select id="fruits" name="fruits">
<option value="0">Apple</option>
<option value="1">Pear</option>
<option value="2">Watermelon</option>
<option value="3">Orange</option>
</select>
<br/><br/>
<?php
if(isset($_GET['id']))
{
echo 'My Fruit <input type="text" id="myfruit" value="' . $_GET['id'] . '" readonly>';
}
else
echo 'My Fruit <input type="text" id="myfruit" value="" readonly>';
?>
</body>
</html>
remove onchange="listChange()" because is not defined and we dont need it.
and use $(this).find('option:selected').val(); for get value of option selected.
$("#animal_list").change(function(){
var animalValue = $(this).find('option:selected').val();
window.location.href="animal_list.php?id=" + animalValue;
});
First off I would clean this mess up.
<select id="animal_list" name="animal_list">
<?php
foreach($results as $res)
{
?>
<?php echo '<option value="'. $res['id'] . '">' ?>
<?php echo $res['name'] ?> <!-- missing ; -->
</option>
<?php
}
?>
</select>
<br/><br/>
<?php
if(isset($_GET['id']))
{
echo '<input type="text" id="npsw_code" value="' . $_GET['id'] . '" readonly>';
}
else
echo '<input type="text" id="npsw_code" value="" readonly>';
?>
Sorry I just can't deal with poorly formatted code, it makes reading it a chore. It just seems like so much wasted effort.
<select id="animal_list" name="animal_list">
<?php foreach($results as $res): ?>
<option value="<?php echo $res['id'];?>"><?php echo $res['name']; ?></option>
<?php endforeach; ?>
</select>
<br/><br/>
<?php
$readonly = '';
$npsw_code = '';
if(isset($_GET['id'])){
$readonly = ' readonly';
$npsw_code = $_GET['id'];
}
?>
<input type="text" id="npsw_code" value="<?php echo $npsw_code; ?>" <?php echo $readonly; ?>>
We'll also ignore this (missing ; ):
<?php echo $res['name'] ?>
Probably a syntax error, but see that's what happens when you cant read the code.
Javascript don't care how the HTML got in the page, only what the HTML looks like. Without knowing what it looks like, all we can do is guess. You can view source and see what it looks like.
Otherwise, put an alert in the on change handler and see what it says.
$("#animal_list").change(function(){
var animalValue = $(this).val();
alert(animalValue);
window.location.href="animal_list.php?id=" + animalValue;
});
Alert has the nice side effect of halting/pausing Javascript execution so it will interrupt the page redirect. This will tell you 2 things,
your event is being fired on change
the value is correct.
Never mind it was a typo. The column in my database was 'code' not 'id'. So it should have read . Sorry for wasting your time.
Im pretty stuck at this code, I really can't see why it should not work, i don't know if some javascript code im running beforehand is interfering?
Only showing relevant part of the code
The first section with javascript updates page when selecting another dropdown, and is placed before the code that im struggling with:
`
<script type="text/JavaScript">
function changeDropDown(){
var elLocation = document.getElementById('form_location_id');
var location = elLocation.options[elLocation.selectedIndex].value;
document.getElementById("form1").action = "choose.php?id=" + location;
document.getElementById("form1").submit();
}
</script>
<form id="form1" name="form1" method="post">
<select size="1" name="form_location_id" id="form_location_id" onchange='changeDropDown(this);'>
<?php
if ($chosen_id == "1") { ?>
<option value = "1" selected><?php echo "dropdown text" ?></option>
<? } else { ?>
<option value = "1"><?php echo "dropdown text" ?></option>
<?php } ?>
</select>
</form>
<form method="post" action="update.php">
<select size="1" id="choice" name="value">
<?php
while($row = mysqli_fetch_array($query)) {
$id = $row['id'];
$number = $row['number'];
>?
<option value = "<?php echo ($id) ?>"><?php echo "ID=" . ($id) . " - #" . ($number) . ""?></option>
<?php
}
mysqli_close($db_conn);
?>
</select>
<input name="submit" type="submit" value="Submit">
</form>
update.php:
<?php
if (isset($_POST['submit'])) {
$chosen_id = $_POST['id'];
}
?>
`
I've only posted the code handling the select option and the post part...
Why is the $chosen_id variable always 0 ?
The while loop works, and fill's the variable, as this is tested with echo command inside the option line
Any help is much appreciated...
$_POST['id'] and <select size="1" id="choice" name="value">
Use $_POST['value']
You are trying to print the wrong key
if you trying to get the value of form_location_id
$chosen_id = $_POST['form_location_id'];
And if you trying to get the value of choice
$chosen_id = $_POST['value'];
This is why when you post a form to php it use html name attribute as key to assign the value to $_POST Array
I'd change Update.php to
<?php
if (isset($_POST['value'])) {
$chosen_id = $_POST['value'];
}
?>
You need to use the form_location_id to get the required value. You are using the wrong key to access the data. You need to use the name of the input. In this case, the input is the select and the name of that is form_location_id. So, you need to do this.
$value = $_POST['form_location_id'];
Try it out and do let me know if it worked out for you.
Thanks for everyone posting idea's - i've actually got it working, the code was actually working, only error was a misplaced tag, which was placed inside a tag, when placed outside this tag it works ;)
Let's say I have a form like this in my CodeIgniter project.
<?php echo form_open(); ?>
<select>
<?php foreach($status_list as $status): ?>
<option value="<?php echo $status->id; ?>"><?php echo $status->name; ?></option>
<?php endforeach; ?>
</select>
<!-- Show this only if status type is, let's say "E" -->
<input type="text" name="E_happened">
<!-- Show this only if status type is, let's say "S" -->
<input type="text" name="S_happened">
<?php echo form_close(); ?>
What I want to do is if an user select one status, according to the it's type, show a text field to get an input.
I've made a way to get a type of the status like this: http://localhost/myapp/index.php/status/type/{status_id} where users can pass status ID and it will "echo" the type of the status.
I want to receive it back to the HTML page via a JavaScript method and show those text input fields. How do I do that?
Thank you. :)
As you have jQuery tag, so i suggest you this:
$('select').change(function(){
var inp = this.value.trim();
$(this).parent().find('input[type="text"][name^="'+inp+'"]').show().siblings(':text').hide();
});
I have posted the sample flow as per you want to do. hope this will helpful for you.
PHP:
<?php echo form_open(); ?>
<select>
<?php foreach($status_list as $status): ?>
<option value="<?php echo $status->id; ?>"><?php echo $status->name; ?></option>
<?php endforeach; ?>
</select>
<!-- Show this only if status type is, let's say "E" -->
<input type="text" id="E_happened" name="E_happened">
<!-- Show this only if status type is, let's say "S" -->
<input type="text" id="S_happened" name="S_happened">
<?php echo form_close(); ?>
JAVASCRIPT :
$('select').change(function(){
var statusId = $(this).val();
var statusType = $.get("http://localhost/myapp/index.php/status/type/"+statusId);
if(statusType == 'E')
{
$('#E_happened').value("what do you want here");
}
if(statusType == 'S')
{
$('#S_happened').value("what do you want here");
}
});
I have a while in PHP that is building a table. Inside my while, I have a dropdown menu that I want to execute code on change.... The form submit on change doesn'T work...
This is my code:
<?
while ($data2 = mysql_fetch_array( $data))
{ ?>
<form name="FormSize" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<td>
<select name="size[]" class="form-field3" OnChange="document.FormSize.submit();" >
<? foreach ($sizearray as $value) { ?>
<option value="$value" <? if($data2['size'] == $value) { echo "selected";} ?> ><? echo $value; ?></option>
<? } ?>
</select>
<input type="hidden" name="product_id[]" value="<? echo $data2['product_id']; ?>">
</td>
</form>
<? } ?>
and on top of my page, I have this to execute the code..
<?
//submit size form
if (isset($_POST['size']))
{
foreach($_POST['product_id'] as $key => $id)
{
$product_id = $id;
$newsize = $_POST['size'][$key];
$sql3 = mysql_query("update cart SET size = '".$newsize."' where product_id = '".$product_id."' ");
}
?>
any idea why it's not executing ?
You have multiple forms with the same name="FormSize". So document.FormSize will be an array-like object, and you need to access the appropriate one. You can do this by using this.form to refer to the <form> that contains the <select>.
You also need to fix the element nesting -- the <form> has to be inside the <td>, not the other way around.
<?
while ($data2 = mysql_fetch_array( $data))
{ ?>
<td>
<form name="FormSize" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<select name="size[]" class="form-field3" OnChange="this.form.submit();" >
<? foreach ($sizearray as $value) { ?>
<option value="$value" <? if($data2['size'] == $value) { echo "selected";} ?> ><? echo $value; ?></option>
<? } ?>
</select>
<input type="hidden" name="product_id[]" value="<? echo $data2['product_id']; ?>">
</form>
/td>
<? } ?>
Could be because the html is not valid, you cannot put your form tag as a direct child of a tr.
Apart from that, naming all your forms the same will make it pretty hard to submit a specific one by its name.
As you are using arrays for your input names, I assume that you mean all of them to be in the same form, so you should just have your form wrap the table and take it out of the while loop.