I have a question.
I want to achieve something, however, I have never done this so unfortunately I do not know how to handle this.
In my screen I fill a dropdown box with names from a sql db.
Now I would like, as soon as a name is chosen from that dropdown that the other data be loaded such as, for example, min and max values.
I would like to use these values to, for example, be able to give limits to input fields.
So as soon as an entry field falls outside of the loaded values, the entry field then turns red.
However, I would like to use this without the submit button of the form being pressed.
Is this possible ? if so can someone help me with this?
The code i use to fill my selectbox is this.:
<td>
<div class="controls">
<select name="prod" id="employee" onclick="updateBottomValue(this.value);" onchange="mys1()" style="width: 245px;">
<option value="" disabled selected="selected[]" multiple="multiple">Selecteer Product</option>
<?php
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM specsv1 where RActive = 'y' order by RNaam";
$q = $pdo->prepare($sql);
$q->execute(array($Id,$RNaam));
Database::disconnect();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['Id'] . "'>" . $row['RNaam'] . "</option>";
}
?>
</select>
<?php if (!empty($ProductError)): ?>
<span class="help-inline"><?php echo $ProductError;?></span>
<?php endif; ?>
</div>
<span id="selectedValue"></span>
<input STYLE="width: 6em" name="rrss" type="text" id='rrss'>
</td>
The code i have to get the selected name is this.:
<script>
function updateBottomValue(selectedvalue) {
document.getElementById("selectedValue").innerHTML=selectedvalue;
document.getElementById('rrss').value = selectedvalue;
}
</script>
Yap it is possible.
And maybe this example ajax for what you want, feel free to modify to fit your requirements.
function viewMinMax(value){
if (value == 'a'){
tempurl = "https://api.myjson.com/bins/dv40y";
}else if (value == 'b'){
tempurl = "https://api.myjson.com/bins/egjmq";
}
$.ajax({
url: tempurl,
type: "get",
dataType: "JSON",
data: {}, //this is data you send to your server
success: function(res)
{
$('#info').show();
document.getElementById("info").innerHTML = 'Your min value: ' + res.min + ', Your max value: ' + res.max;
$('#min').val(res.min);
$('#max').val(res.max);
}
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post">
<select name="product_select" id="product_select" onchange="viewMinMax(this.value)">
<option value="">Select Product</option>
<option value="a">Product A</option>
<option value="b">Product B</option>
</select>
<p id="info" style="display:none;"></p>
<h3>Load the min & Max</h3>
<label for="min">Min</label>
<input type="text" name="min" id="min" value="">
<br>
<label for="max">Max</label>
<input type="text" name="max" id="max" value="">
</form>
ignore the tempurl it can be change with your action to select data based on value to your DB.
Is it possible? Absolutely. There are a few ways of going about it. One easy way is to use jQuery to fire off what's called an AJAX call as soon as the dropdown value changes. The AJAX call your PHP script and get back some HTML that it will place wherever you want it on the screen.
It's a big subject, so difficult to give you exact answers, but google jquery ajax dropdown onchange and you should be able to get enough information to get you going. One of them is the following (there are many):
jQuery Load form elements through ajax, from onchange event of drop down box
Related
<div class="form-group"><label for="unit_of">Unit of Measure</label>
<select class="form-control-sm selectpicker" multiple="multiple" id="unit_of" name="unit_of[]" data-selected-text-format="count">
<?php $sql = "select * from unit_of";
$res = mysqli_query($db_handle, $sql);
while ($list = mysqli_fetch_assoc($res)) {
$unit_of = $list['unit_of'];
?>
<option><?= $unit_of; ?></option>
<?php
}
?>
</select>
</div>
<input type="text" class="form-control-sm" id="rates" name="rates" >
<input type="text" class="form-control-sm" id="rates1" name="rates1" style="display:none">
<input type="text" class="form-control-sm" id="rates2" name="rates2" style="display:none">
In the dropdown
Per Minute
Per Page,
Per Hour,
Per Day,
Per Month,
Per Item,
Per Contract,
Others
I want onchange multiple select hide and show input types number e.g.(name="per_page") e.g.("Enter Rate Per Page") for three input type
Thanks in Advance
If I understand correctly, there are 2 questions here really:
How to restrict a multiple select to a max of 3 selections?
There are multiple ways to achieve this, but my recommendation would be to validate this right before the form is submitted. If you're using a form validation library, try adding the code in there. If not, then you can add a custom submit event handler that will validate the selections. Maybe something like:
$("form").on("submit", function(e) {
var selectionCount = $("#unit_of option:selected").length;
if (selectionCount > 3) {
e.preventDefault();
alert("You may only select up to 3 options.");
}
});
How to add a placeholder to the multiple select?
You can add a placeholder option just before the PHP code adds the other options, like so:
<select class="form-control-sm selectpicker" multiple="multiple" id="unit_of"
name="unit_of[]" data-selected-text-format="count">
<option value="">Enter Rate Per Page</option>
<?php $sql = "select * from unit_of";
$res = mysqli_query($db_handle, $sql);
while ($list = mysqli_fetch_assoc($res)) {
$unit_of = $list['unit_of'];
?>
<option><?= $unit_of; ?></option>
<?php
}
?>
</select>
Of course, with this approach, you'll need to add extra validation code to make sure that the placeholder option is not one of the selected options.
I am using PHP to dynamically populate a select box (a list of equipment). The value is set with the ID of the item selected so I can use it later in my programming.
What I need help with...
Based on the item selected I need to show/hide one of two form fields but I can't use the value as this is the id.
What I need to be able to do is read the text in the select box which will contain the item name with either (Service: Set by dates) or (Service: Set by hours) and show either the form field for the date or the form field for the hours?
Is this possible? I can find loads great resources based on the value but not on the text in the select.
I think something like this should work but not sure how to use the text in the select rather than the value.
$(function() {
$('#system').change(function(){
$('.system').hide();
$('#' + $(this).val()).show();
});
});
Any help would be greatly appreciated!!!!
Regards
Matt
(N.B this is what I'm working with at the mo based on the answers so far, thank you all so much for the help (and for your example Louys Patrice Bessette) - not quite there yet... I was getting an error and managed to track it back to the script not getting the result from the select box. See below now working code! Thanks all!!!
<div class="col">
<div class="form-group">
<label for="system_select">Equipment or System to be serviced</label>
<select class="form-control" name="system_select" id="system_select">
<option></option>
<?php
$systems = DB::getInstance()->get('ym_system', 'vessel_id', '=', $vid);
foreach ($systems->results() as $system) {
?><option data-type="<?php echo $system->service_type ?>" value="<?php echo $system->system_id ?>"><?php echo $system->system_name; ?></option> <?php
}
?>
</select>
</div>
</div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
$("#due_dates").hide(); // Hide both divs
$("#due_hours").hide(); // Hide both divs
$('#system_select').change(function(){
var dataType = $(this).find(':selected').attr('data-type') // should be "Set by dates" or "Set by hours"
if (dataType == 'Set by dates') {
$("#due_hours").hide();
$("#due_dates").show();
} else if (dataType == 'Set by hours') {
$("#due_dates").hide();
$("#due_hours").show();
}
});
});
</script>
<div class="row">
<div class="col-md-3" id="due_date">
<div class="form-group">
<label for="service_date">Next Service (Set by dates)</label>
<input type="date" class="form-control" name="service_date" id="service_date" value="<?php echo escape(Input::get('service_date')); ?>" autocomplete="off">
</div>
</div>
<div class="col-md-3" id="due_hour">
<div class="form-group">
<label for="service_hours">Next Service (Set by hours)</label>
<input type="number" class="form-control" name="service_hours" id="service_hours" value="<?php echo escape(Input::get('service_hours')); ?>" autocomplete="off">
</div>
</div>
</div>
I think that you PHP $system->service_type; is echoing either "Set by dates" or "Set by hours".
If you echo that in a data attribute like this:
<select class="form-control" name="system_select" id="system_select">
<option></option>
<?php
$systems = DB::getInstance()->get('ym_system', 'vessel_id', '=', $vid);
foreach ($systems->results() as $system) {
?><option data-type="<?php echo $system->service_type; ?>" value="<?php echo $system->system_id ?>"><?php echo $system->system_name . ' (Service: '. $system->service_type .')'; ?></option> <?php
}
?>
</select>
Then, in jQuery, you could use it like this to decide to show <div id="due_hours" class="col-md-3"> or <div id="due_hours" class="col-md-3">.
$(function() {
$('#system').change(function(){
$('.system').hide(); // I don't know what this is for...
$("div[id=^'due']").hide(); // Hide both divs
var dataType = $(this).data("type"); // should be "Set by dates" or "Set by hours"
var type = dataType.split(" by ")[1]; // should be "dates" ot "hours"
$("#due_"+type).show();
});
});
Now be carefull with the s on dates...
Try this out... Console.log the values to make sure you have the correct one to match the id to show.
;)
If $(".classname").text() is not working you could try to add that info that you need in a "data" attribute.
Something like this ->
<option data-service="service name" class="myClass">15</option>
Using data attributes can give you a lot of freedom on what you can add. You could add lots of information that a normal user cant read (without inspecting element).
Then you would simply do something like this ->
$(".myClass").on("click", function() {
var serviceData = $(this).attr("data-service");
})
You can then do if checks, compare and whatever you need.
EDIT: Or you can use your approach with on.change and get the selected data attr, it would probably be better
If you change your select into something like this:
<select class="form-control" name="system_select" id="system_select">
<option data-hide='#due_date' data-show='#due_hours'>Show Hours</option>
<option data-hide='#due_hours' data-show='#due_date' value="B">Show Dates</option>
</select>
And your jquery like this:
$('#system_select').change(function () {
$($(this).children("option:selected").attr("data-hide")).hide();
$($(this).children("option:selected").attr("data-show")).show();
});
It could work.
It appears that I am facing a common beginer's problem but I haven't managed to solved it on my code.
What I want to do:
I have created a database and I am currently working on a simple UI for updating it. So, I use
One drop-down menu populated by a mySQL table
Some forms with their values changed accordingly to the drop down selection.
Code(Simplified a little):
<html>
<body>
<form method="post">
<select class="dropdown" id="dropdown_id" onChange='fillFun(this.value)' >
<option disabled selected value style="display:none"> -- select an option -- </option>
<?php
//stuff pdo connection
$pdo = new PDO("mysql:host=$servername;dbname=myDatabase", $user, $password);
try
{
$result = $pdo->query("SELECT * FROM dbTable");
foreach($result as $row)
{
echo '<option value="'.$row.'"';
echo '>'. $row['last_name'].' '. $row['first_name'].'</option>'."\n";
}
}
catch(PDOException $e) { echo 'No Results'; }
?>
</select >
</form>
<form id="forms" action="results.php" method="post">
Last Name: <input type="text" id="last_name" /><br><br>
First Name: <input type="text" id="first_name" /><br><br>
<input type="submit" />
</form>
<script>
function fillFun(fill)
{
document.getElementById('last_name').value = fill[1];
document.getElementById('first_name').value = fill[2];
}
</script>
<body>
Problem:
this.value = "Array"
After researching a little I found a couple of question with a similar problem.(For instace this one)
The thing is that I can't(or don't know how,to be precise) apply the given solution print_r() or var_dump() since I am echo-ing an option value. Another way to solve a similar problem was the use of json_encode() but after the change of
onChange='fillFun(this.value)'
with
onChange='fillFun(json_encode(this.value))'
the problem wasn't solved. On the contrary, it seems that now the fill parameter was null.(Nothing happens on change).
What am I missing here?Thanks.
Instead of referring to this.value you can pass the event object to fillFunc function and obtain the value through event.target.value.
So fillFunc will be updated to:
fillFunc(event) {
document.getElementById('last_name').value = event.target.value[1];
document.getElementById('first_name').value = event.target.value[2];
}
And pass event to your onchange handler.,
<select onchange="filFunc(event)"></select>
i want a combobox which populates itself from a database column, when a user selects an option from the combobox it will populate textboxes, which are on the same page, with information related to the selection in the combobox.
Below is the code I used to populate a textbox when I selected the select nama from the dropdown combobox. but it doesnt work, the textbox still blank.
I have the drop down working and also it fills a JavaScript array using names but I just cannot work out how to use the array to show in the fields.
i understand it will have to use javascript and Onchange function, can anyone point me in the right direction?
cheers and thank in advance :)
<script src="js/jquery.js"></script>
<script type="text/javascript">
var selected = new Array();
<?php
$query1 = "SELECT * FROM inventori";
$result1 = mysql_query($query1) or die(mysql_error());
// build javascript array
while($row1=mysql_fetch_array($result1)){
echo 'selected['.$row1['selectnama'].'] = new Array();';
echo 'selected['.$row1['selectnama'].']["NAMA_BAHAN_BAKU"] = "'.$row1['NAMA_BAHAN_BAKU'].'";';
echo 'selected['.$row1['selectnama'].']["SATUAN"] = "'.$row1['SATUAN'].'";';
}
?>
function showname() {
var selectnama = document.formInventori.selectnama.value;
document.formInventori.SATUAN.value = selected[selectnama]["SATUAN"];
}
window.onload=function() {
showname();
}
</script>
<form role="form" action="" method="post" name="formInventori">
<div class="form-group">
<label for="NAMA_BAHAN_BAKU">Nama Bahan Baku</label>
<select class="form-control" name="selectnama" onchange="showname()">
<option value="">Pilih Nama Bahan Baku</option>
<?php
$query1 = "SELECT * FROM inventori";
$result1 = mysql_query($query1) or die(mysql_error());
// build javascript array
while($row1=mysql_fetch_array($result1)){
echo '<option value="'.$row1['ID_BAHAN_BAKU'].'">'.$row1['NAMA_BAHAN_BAKU'].'</option>'; }
?>
</select>
</div>
<div class="form-group">
<label for="SATUAN">Satuan Barang</label>
<input type="text" class="form-control" readonly="" id="SATUAN" name="SATUAN" value="">
</div>
</form>
I would use AJAX to do that, i would save the value selected from the combobox and then pass it to a php through ajax so the php executes a query where the selected value is the search "key", then print the result throught php
Here is my dilemma. A multi-select drop-down displays pre-selected options. When the user makes any changes, I'm running some code in the PHP action file (called through a submit button). I'm trying to accomplish this using a flag and updating the flag in the onchange event of "select option". The rest is working fine. I just wanted to execute the queries in action file only when the user changed selections in drop down rather than every time the form is submitted. However I'm unable to pass the flag successfully. I know I'm missing something basic and have spent two days looking at it. Any help is appreciated.
The relevant code is pasted below:
//Initialize flag
<?php
...
$multi_prog_change_flag = '0';
...
?>
//Hidden Form Element
<form action="update_u.php" method="post" id="cForm" name="cForm" onsubmit="return validateForm()" autocomplete="off">
...
<?php echo '<input type="hidden" id="email" value="'.$email.'"> ';?>
<?php echo '<input type="hidden" id="multiprogchangeflag" name="multiprogchangeflag" value="'.$multi_prog_change_flag.'"> ';?>
...
// Drop-down Element where update is triggered
<tr id="odd">
<td><select id="programName" name="programName[]" onchange="updateflag();>" multiple="multiple" size=10>
..
<option name="drop1" value ="<?php echo $data['Program_Id'] ?>" <?php if ($data[curr_prog] == '1') echo 'selected="selected"'; ?>> <?php echo $data['Program_Name'];?></option>
..
</select>
<input type="hidden" id="pNames" name="pNames" value="" />
</td>
</tr>
// Function to update flag
function updateflag() {
<document.getElementById("multiprogchangeflag").value = "1";
}
// update_u.php PHP Action File
$multi_prog_flag=mysql_real_escape_string($_POST['multiprogchangeflag']);
if ($multi_prog_flag == '1'){
$multi_prog_delete_query=mysql_query("UPDATE multi_prog_access SET is_act = '0', Updated_by = '$updatedby', update_timestamp = NOW() WHERE user_id = '$useid'");
$count = count($multi_prog_names);
for($i=0;$i<$count;$i++){
$multi_prog_ID=$multi_prog_names[$i];
$multi_prog_update_query=mysql_query("INSERT INTO multi_prog_access (user_id, Prog_id, created_by, is_act, Update_timestamp) VALUES ('$ids','$multi_prog_ID', '$updatedby', '1', NOW())");
}
}