Option Menu with 2 Values - javascript

I have the following option menu in a form that will insert the fields into a table:
<option value="">select staff</option>
<?php
do {
?>
<option value="<?php echo $row_Staff['Staff_Name']."||".$row_Staff['Email']?>">
<?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>
I have 2 fields from source table in value of option from technique explained in How to post two values in an option field?: Staff_Name and Email.
I am trying to insert both fields from the form into a table using:
<input type="hidden" name="Staff_Name" class="form-control" id="Staff_Name" value=<?php
$staff =$_POST['Staff_Data'];
$staff_name = explode("||", $staff);
echo $staff_Name[0];
?> />
and
<input type="hidden" name="Email" class="form-control" id="Email" value=<?php
$staff =$_POST['Staff_Data'];
$email = explode("||", $staff);
echo $email[1];
?> />
Unfortunately, I can see the 2 fields separated by "||" in the table if I insert the option menu value but cannot seem to insert Staff_Name or Email into individual fields. On insert both fields are blank. Any help would be appreciated.

Instead of combine staffname and staffemail in the dropdown value. Please staffname in dropdown value and staffemail in the property of dropdown and onchange of the dropdown set those values in the hidden inputs so you will easily get those values on the form submission.
Please go through below code and let me know if you have any query.
//Dropdown
<select id="ddStaff">
<option value="">select staff</option>
<?php
do { ?>
<option value="<?php echo $row_Staff['Staff_Name']; ?>" staff-email = "<?php echo $row_Staff['Email'];?>">
<?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>
//Input hidden fields to store staff name and staff email
<input type="hidden" id="txtStaffName" name="txtStaffName">
<input type="hidden" id="txtStaffEmail" name="txtStaffEmail">
//Jquery code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#ddStaff").on('change',function(){
var staffName = $(this).val();
var staffEmail = $('option:selected', this).attr('staff-email');
$("#txtStaffName").val(staffName);
$("#txtStaffEmail").val(staffEmail);
});
});
</script>
Please check it on https://jsfiddle.net/z4a0fywp/
For testing purpose I have not made the inputs hidden in the fiddle.

Related

how to retain drop down values as the value selected after submit

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>

Use value from a form in a redirect button outside the form

Fetch selected value from dropdown which is in one form and onClick of the button outside the form send the value to php page
<div class="drpvendorname">
<font style="color: white;">
<label>Distribution Point:</label>
</font>
</div>
<select class="form-control" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option onClick="distribution('.$result['pointshortname'].')" value="' .$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
</form><!--form1 ends here-->
<form action="../customer/form.php"><!--form2 starts here-->
<button class="btn pos7" name="abc" method="GET" style="margin-left:5%;">New Customer</button>
</form><!--form2 ends here-->
<div class="dailybreakupbtn">
<input class="btn" type="submit" id="dailybreakupbutn" name="dailybreakup" value="Enter Daily Breakup" onClick="distribution(<?=$pointname?>)"/>
</div>
<?php
if(isset($pointname)){
?>
<script type="text/javascript">
function distribution(pointname){
var pointname;
window.location.href="dailybreakup.php?query=" +pointname;
}
</script>
<?php
}
?>
I have tried this sending selected dropdown box value to next page using function name distribution
I ended sending undefined to the next page.
can any one help me sending the selected value to the next page with out putting the button in the <form>
May this will be help you :)
Html code:
<form action= "" method= "post">
<select class="form-control drpvendor" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option value="'.$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
</form>
JQuery Code:
$(doucment).on('change','.drpvendor',function(){
var data=$(this).attr('selected','selected');
$.ajax({
url: "dailybreakup.php",
data:'query='+ data,
type: "POST",
success: function(data) {
window.location.href='customer/form.php';
}
});
});
Use code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> // please link the path or use cdn
<script type="text/javascript">
function call_me(){
var pointname=document.getElementById("drpvendor").value;
alert(pointname); // comment it after testing
window.location.href="dailybreakup.php?query=" +pointname;
}
</script>
<form>
<select class="form-control" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option value="' .$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
<input type="button" onclick="call_me()"/>
</form><!--form1 ends here-->
Note : 1) Code is not tested
2) use your select id instead of your_select_id
3) check variable

How to get all the selected options in a drop down list with JavaScript?

I have a drop down list, and user can select multi options.
So this is part of my code in firtfile.inc
<div class="col-md-8">
<!-- Change report heading so we can grab it on the report page -->
<select name="SearchIn[]" multiple="multiple" onchange="javascript:this.form.Heading.value=this.options[this.selectedIndex].text;" required="required" title="Section">
<option value="" disabled selected>Select</option>
<?php
//Loop over the options
for($i=0;$i<sizeof($SearchCriteria);$i++){
?>
<option value="<?php echo $SearchCriteria[$i]['value'];?>"<?php if($SearchCriteria[$i]['value']=='FacultyName'){echo ' selected="selected"';}?>>
<?php echo $SearchCriteria[$i]['display'];?>
</option>
<?php
}//!End of looping over search criteria
?>
</select>
<!-- Hidden heading field for search report -->
<input type="hidden" name="Heading" valtue="" />
</div>
in another php file, I have included firstfile.inc, and i want to get the list of options that user has selected from drop down list.
so I have the folloing in the php file to get the selected options.
$Heading = $dat->if_default('Heading', '');
but it only gives me the first option that the user has selected, but I need all of them. How can I get them?
First of all, I highly recommend that you use jQuery, it will make any DOM manipulation a lot easier.
It's not clear what output you expect, but supposing you're expecting a comma separated string like:
Criteria1, Criteria2, Criteria3
You could:
1) Just use PHP to give you that, with something like:
$SearchIn = $_POST["SearchIn"];
$selectedArr = array();
foreach($SearchCriteria as $item) {
if (in_array($item["value"], $SearchIn)) {
$selectedArr[] = $item["display"];
}
}
$criteria = implode(", ", $selectedArr); // will contain: Criteria1, Criteria2, Criteria3
2) If you want to do it on the client and store the values in <input id="heading"/>, you can use jQuery and do this (your HTML would change a little, to include the IDs):
<form action="index.php" method="POST">
<div class="col-md-8">
<!-- Change report heading so we can grab it on the report page -->
<select id="section" name="SearchIn[]" multiple="multiple" required="required" title="Section">
<option value="" disabled selected>Select</option>
<?php for($i = 0; $i < sizeof($SearchCriteria); $i++) { ?>
<option value="<?php echo $SearchCriteria[$i]['value'];?>"<?php if($SearchCriteria[$i]['value']=='FacultyName'){echo ' selected="selected"';}?>>
<?php echo $SearchCriteria[$i]['display'];?>
</option>
<?php } ?>
</select>
<!-- Hidden heading field for search report -->
<input id="heading" type="hidden" name="Heading" value="" />
</div>
<input type="submit">
</form>
<script>
$('#section').on("change", function() {
selectedArray = new Array();
$(this).find("option:selected:not([disabled])").each(function() {
selectedArray.push(this.text);
});
$("#heading").val(selectedArray.join(", "));
});
</script>
3) For a pure JavaScript solution (use the same HTML as above):
<script>
document.getElementById("section").onchange=function(){
selectedArray = new Array();
for (x = 0; x < this.length; x++) {
if (this[x].selected && !this[x].disabled) {
selectedArray.push(this[x].text);
}
}
document.getElementById("heading").value = selectedArray.join(", ");
};
</script>

Based on a forms input value, how 2 generate selections 4 a drop down menu w row/record data from a database that will prefill a form when selected?

I'm trying to figure out a way to pre fill a form with data with past form information submitted in the past.
I have a form and a database. In my form I have a input named email that holds the pre-loaded default value of logged in member's email address that is read-only.
PIC
http://oi57.tinypic.com/2iubb4j.jpg
How can I generate a selection under a drop down menu that when selected will pre-fill the form with row/record data from my database?
and how can I generate only the records that match the forms input value 'email' to the records with the same value under the 'email' column in the database?
I've been at it for weeks now and can not seem to find any sense of direction on how to achieve this. Can't really find any tutorials site, video, sample code or anything close on how to make this possible. Any help would be great...thanks for your help in advance.
FORM
</header>
<body>
<form action="/demoform/contact_form.php" class="well" id="contactForm" method="post" name="sendMsg" novalidate="">
<big>LOAD PAST ORDERS:</big>
<select id="extrafield1" name="extrafield1">
<option value="">Please select...</option>
<option value="xxx">SAMPLE SELECTION</option>
</select>
</br>
<input type="text" required id="mile" name="mile" placeholder="Miles"/>
</br>
<input id="email" name="email" placeholder="Email" required="" type="text" value="demo#gmail.com" readonly="readonly"/>
</br>
<input id="name" name="itemname" placeholder="ITEM NAME 1" required="" type="text" />
</br>
<input type="reset" value="Reset" />
<button type="submit" value="Submit">Submit</button>
</form>
</body>
</html>
PHP FILE
<?php
define('DB_NAME', 'xxx');
define('DB_USER', 'xxx');
define('DB_PASSWORD', 'xxx');
define('DB_HOST', 'xxx');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$connection){
die('Database connection failed: ' . mysqli_connect_error());
}
$db_selected = mysqli_select_db($connection, DB_NAME);
if(!$db_selected){
die('Can\'t use ' .DB_NAME . ' : ' . mysqli_connect_error());
}
echo 'Connected successfully';
if (isset($_POST['itemname'])){
$itm = $_POST['itemname'];
}
else {
$itm = '';
}
if($_POST['mile']){
$mi = $_POST['mile'];
}else{
echo "Miles not received";
exit;
}
if($_POST['email']){
$email = $_POST['email'];
}else{
echo "email not received";
exit;
}
$sql = "INSERT INTO seguin_orders (itemname, mile, email)
VALUES ('$itm', '$mi', '$email')";
if (!mysqli_query($connection, $sql)){
die('Error: ' . mysqli_connect_error($connection));
}
UPDATE: closest thing below so far...but wont work...not sure it covers the matching the email values portion...thanks anyways 'edcoder'
<select id="extrafield1" name="extrafield1">
<option value="">Please select...</option>
<?php
$query='select * from tablename';
$res=mysql_query($query);
while($row=mysql_fetch_array($res))
{
?>
<option value="<?php echo $row['feildname']; ?>"><?php echo $row['feildname']; ?></option>
<?php
}
?>
</select>
It seems that you're almost there.
Try this.
<select id="extrafield1" name="extrafield1">
<option value="">Please select...</option>
<?php
$email = $_POST['email'];
$query="select * from tablename WHERE email={$_POST['email']}";
$res=mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($res))
{
?>
<option value="<?php echo $row['fieldname']; ?>"><?php echo $row['fieldname']; ?></option>
<?php
}
?>
</select>

clicking on the select option how to show hidden field using javascript?

I am working on php how to show hidden field?
I have bp_scholarship_enq table in my database and this database i have occupation field i want to add new occupation in my database how i do it?
<script>
function showss(ids)
{
var idss=ids;
if(idss=="other")
document.getElementById(idss).style.display='block';
}
</script>
<?php
echo "<select name='occupation' id='link_block' value='Source' style='width:196%'>
<option>select occupation </otpion>";
$sql = "SELECT * FROM bp_scholarship_enq";
$info = mysql_query($sql);
while ($row = mysql_fetch_array($info))
echo "<option > '" . #$row["occupation"] . "'</option>";
echo '<option onClick="showss('.input_field.')">other</option>';
echo "</select>";
echo '<input type="hidden" name="other" id="input_field" />';
?>
Hidden fields are not meant to be visible. You could use a textbox and set its visiblity to false in css and make visible it on changing the select option.
<input type="text" name="other" id="input_field" style="display:none"/>
<select name='occupation' id='link_block' value='Source' style='width:196%' onChange="showText(this.selectedIndex);">
...............
...............
<option value="other">other</option>
</select>
<script>
function showtext(ind){
var selectBox = document.getElementById('link_block');
if(selectBox.options[ind].value=="other"){
document.getElementById('input_field').style.display = "block";
}else{
document.getElementById('input_field').style.display = "none";
}
}
</script>
Instead of
<input type="hidden" name="other" id="input_field" />
Make it:
<input id="otherOccupation" class="hide" name="other" id="input_field" />
With hide being a class that sets visibility:hidden;
Then have some jquery to remove that class when the user selects "other"
$("#otherOccupation").removeClass("hide")

Categories