How to enable a field if a determined option is chosen? - php

I have a form in which when the user chooses certain option in a select drop-down, a new field should shows up for entering another piece of information.
Basically, it's the common "Where did you hear about us?" and when the user selects other, a new empty field is shown so that he can type the source if it wasn't in the list.
But I really have no clue about how to do it. I've been using PHP and HTML to do the form and validating it.
To add some code, this is where I create the select
<label for="where_heard">Where heard:</label>
<select name="where_heard"> <?php echo $sources; ?>
</select>
And this is where I get the source list from:
$query = "SELECT source FROM where_heard";
$stmt = $db->prepare($query);
$stmt->execute();
$sources = "";
while ($row = $stmt->fetch()) {
$sources .= '<option value= "'.$row['source'].'">'.$row['source'].'</option>';
}

You can do this with jquery like:
$( document ).ready(function() {
$('select').on("change",function(){
if($(this).val() == "other")
$(".other").html("Other: <input type='text' name='other'/>");
else
$(".other").html("");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="where_heard">Where heard:</label>
<select name="where_heard"><option></option><option value="other">Other</option>
</select>
<div class="other"></div>

Related

jquery get data attributes of select2 inside while loop php

I have been reviewing similar questions related to select2 data attributes, but couldn't find what I'm looking for. I have been taking time on this.
Basically I have a select2 dropdown inside a while loop which fetch values from sql database. I need to add an additional data attribute and when an option is selected, I need to display the selected data attributed in the input field. My code goes as below
<select class="select2-dropdown form-control" tabindex="-1" id="user" name="user">
<option value="">Select User</option>
<?php
$fetchuser = mysqli_query($link,"SELECT * FROM user ORDER BY name ASC") or die(mysql_error());
while($row=mysqli_fetch_assoc($fetchuser))
{
$id = $row["id"];
$name = $row["name"];
$status = $row["status"];
?>
<option value="<?php echo $id; ?>" data-status="<?php echo $status; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<input id="status" />
My JS:
<script type=text/javascript>
$('#user').on('select2:selecting', function() {
var status=$(this).find(":selected").data("status");
$('#status').val(status);
});
</script>
I'm only getting random status (not corresponding to the selected), and some options status is not displayed when selection is changed.
Could anyone suggest where i have made the mistake.
Thank you in advance.
Your code is so weird for me.
Try this:
$('select').on('change', function() {
var status=$(this).find(":selected").data("status");
$('#status').val(status);
});
I think it will change function that you need to use
$('#user').on('change', function() {
var status= $(this).find(":selected").data("status");
$('#status').val(status);
});

How to have an HTML input field appear when the value 'other' is selected with PHP

What I am trying to figure out is how to have an html input field appear when the value of other is selected from a dropdown menu. Right now the values for the dropdown list are coming from the results of a MySQL DB query, which works, but I can not seem to figure out how to get an input to appear when I select the other option.
$query = mysql_query("SELECT type FROM Dropdown_Service_Type"); // Run your query
echo '<select name="service_type">'; // Open your drop down box
echo '<option value="NULL"></option>';
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
echo '<option value="Other">Other</option>';
echo '</select>';// Close your drop down box
Use javascript, like in the example below. We can add an input field and have it hidden by default, using the style attribute:
<input name='otherInput' id='otherInput' type="text" style="display: none" />
var otherInput;
function checkOptions(select) {
otherInput = document.getElementById('otherInput');
if (select.options[select.selectedIndex].value == "Other") {
otherInput.style.display = 'block';
}
else {
otherInput.style.display = 'none';
}
}
<select onchange="checkOptions(this)" name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<!-- other options from your database query results displayed here -->
<option value="Other">Other</option>
</select>
<!-- the style attribute here has display none initially, so it will be hidden by default -->
<input name='otherInput' id='otherInput' type="text" style="display: none" />
There are 3rd party libraries like jQuery, AngularJS, PrototypeJS, etc., which can be used to make the code simpler by adding shortcut methods for DOM manipulation (though you should read this post). For example, with jQuery, using .on() (for the event handler binding), .show() and .hide() for the input display toggling, etc:
var otherInput;
var serviceTypeInput = $('#service_type');
serviceTypeInput.on('change', function() {
otherInput = $('#otherInput');
if (serviceTypeInput.val() == "Other") {
otherInput.show();
} else {
otherInput.hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<option value="Other">Other</option>
</select>
<input name='otherInput' id='otherInput' type="text" style="display: none" />
$(function() {
$('#sample').change(function() {
var val = this.value; // get the value of the select.
if (val == 'other') { // if the value is equal to "other" then append input below the select
$('html').append('<input type="text" id="inputOther"/>');
} else { // else then remove the input
$('#inputOther').remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sample">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="other">other</option>
</select>

Dynamic dependent select boxes (PHP+JQuery+AJAX)

I have been working on a dependent select boxes form using PHP as the server-side language and JQuery with Ajax. I am having an issue with getting the response text, as it is not displaying as options in the second select box.
P.S. I am new to Ajax and there is no video that can help me with my problem.
HTML&PHP:
<center><form method="post" action="php/functions.php" id="catForm">
<select name="catSelect" class="catSelect" name="category">
<option value='null' default>اختر الفئة:</option>
<?php
$selectCategories = mysqli_query($connectionDB, "SELECT * FROM categories");
while($categoriesDisplay = mysqli_fetch_array($selectCategories)){
echo '<option value="'.$categoriesDisplay['id'].'">'.$categoriesDisplay['category'].'</option>';
}
?>
</select><br/><br/>
<select name="subCatSelect" class="subCatSelect">
<option value="null" default>اختر النوع:</option>
<?php
$catSelectVal = $_POST['catSelect'];
$selectSubCat = mysqli_query($connectionDB, "SELECT * FROM sub_categories WHERE id LIKE '$catSelectVal'");
while($subCatDisplay = mysqli_fetch_array($selectSubCat)){
echo '<option value="'.$subCatDisplay['id'].'">'.$subCatDisplay['subCategory'].'</option>';
}
?>
</select><br/>
<h1></h1>
<input type="submit" value="اختر" class="submitForm" /><br/>
</form></center>
Jquery code:
$(document).ready(function(){
$('.catSelect').change(function(){
var changeURL = $('#catForm').attr("action");
var data = $('.catSelect').val();
$.post(changeURL, {category : data}, function(subCategory){
$('.subCatSelect').append(subCategory);
});
});
});
The code that should work on getting the options for the second select box:
$catSelectVal = $_POST['catSelect'];
$selectSubCat = mysqli_query($connectionDB, "SELECT * FROM sub_categories WHERE id LIKE '$catSelectVal'");
while($subCatDisplay = mysqli_fetch_array($selectSubCat)){
echo '<option value="'.$subCatDisplay['id'].'">'.$subCatDisplay['subCategory'].'</option>';
}
I could be wrong, but I don't think you've sent 'catSelect' in the ajax request.. rather you've sent category with data being the value from 'catSelect'
So when you look for $catSelectVal = $_POST['catSelect']; there won't be anything to find.
Try instead: $catSelectVal = $_POST['category'];
As #RiggsFolly mentioned, if you print_r($_POST); you'll instantly see if this is the case or not.

Select from drop-down menu and reload page

I've got a table that populates data from a MYSQL database and populates a drop-down menu from the same database. I have the drop down menu and table just fine, I would like to be able to choose which data I show in the table however.
<select name = 'peer-id' method='post' style = 'position: relative'>
<?php
while ($content = mysql_fetch_array($peer)) {
echo "<option value='" . $content['Peer'] . "'>" . $content['Peer'] . "</option>";
}
$results = mysql_query("SELECT Destination FROM rate ");
?>
</select>
That's what I have for the select box. How can I get the choice from that and save that as a variable and refresh the table data?
I need to clarify that this will change that current data
#Data#Data#Data
#Data#Data#Data
#Data#Data#Data
Then choose drop down choice and I want it to show new data
#Data2#Data2#Data2
#Data2#Data2#Data2
#Data2#Data2#Data2
So it's going to need to load a new page or refresh some how because it's changing via PHP and not javascript.
I think form may be better, for example
<form id="myform" method="post">
<select name = 'peer-id' style = 'position: relative' onchange="change()">
<option value="1">12</option>
<option value="2">15</option>
<option value="3">16</option>
<option value="4">18</option>
</select>
</form>
<script>
function change(){
document.getElementById("myform").submit();
}
</script>
In the above code, whenever you change the value of select, it will post to the backend, then according to the posted value, you can do want you want, to get the peer-id in php, you can use the following code
$peer-id = $_POST['peer-id'];
Hope helps!
apply this code in select tag hope this works
<select onchange="location = this.options[this.selectedIndex].value;" style="text-decoration:none;">
<option value="customers.php"></font></option>
</select>
insted of the static options, you can do it like this :) here you get all the options from the database. Just replace it with the static options
$peer = mysql_query("SELECT Peer FROM rate Group By Peer Where peer = 'variable'");
$result_peer = mysql_query($peer);
if($result_peer){
while($row_peer = mysql_fetch_array($result_peer)){
echo'<option value='.$row_peer['Peer'].'>'.$row_peer['Peer'].'</option>';
}
I agree in using form, and with this you can echo back onto the page with a submit button (code tested):
<form id="myForm" method="POST">
<select name="select" onchange="<?php echo $_SERVER['PHP_SELF'];?>">
<option value="N">No</option>
<option value="Y">Yes</option>
</select>
<input type="submit" name="formSubmit" value="Submit" >
</form>
<?php
if(isset($_POST['formSubmit']) ){
$var = $_POST['select'];
$query = "SELECT * FROM table_name WHERE DesiredField='$var'";
$result = mysql_query($query)
or die(mysql_error());
while($row = mysql_fetch_array($result)){
$var2 = $row['FieldName'];
echo "First field: " . $var2 . "<br>";
// and so on for what you want to echo out
}
}
?>

Dynamic drop down list to fill in a text box

I have searched high and low for a resolution to this bus have not been able to work it out. I managed to get this to work when I wanted a dynamic drop down to adjust the values in a second drop down and fill in a text value in a text box.
Now I want to cut out the second step: ie. I actually want to get rid of the second drop down and simply enter a value in the text box. I have tried everything to remove the second step but as soon as I do everything stops working.
At the moment the function looks at the second drop down and sets the options for it and I added the line
document.getElementById('fld_ClientID').value =""
to get it to enter the data in the text box. How do I get rid of the reference to the tblPromotions completely and make it get the data for the text box only.
<script language="javascript">
function setOptions(chosen) {
var selbox = document.myform.selectpromotion;
selbox.options.length = 0;
if (chosen == "0") {
selbox.options[selbox.options.length] = new Option('First select a client','0');
}
<?php
$client_result = mysql_query("SELECT * FROM tblClients ORDER BY ClientName") or die(mysql_error());
while(#($c=mysql_fetch_array($client_result)))
{
?>
if (chosen == "<?=$c['ClientID'];?>") {
<?php
$c_id = $c['ClientID'];
$promo_result = mysql_query("SELECT * FROM tblPromotions WHERE ClientID='$c_id'") or die(mysql_error());
while(#($m=mysql_fetch_array($promo_result)))
{
?>
selbox.options[selbox.options.length] = new
Option('<?=$m['PromotionName'];?>','<?=$m['ClientID'];?>');
document.getElementById('fld_ClientID').value ="<?=$m['ClientID'];?>";
<?php
}
?>
}
<?php
}
?>
}
</script>
</head>
<body>
<form name="myform" method="POST" action="processaddpromotionNEW.php"> ><div align="center">
<p>
<select name="selectclient" size="1"
onchange="setOptions(document.myform.selectclient.options
[document.myform.selectclient.selectedIndex].value);">
<option value="0" selected>Select a client</option>
<?php
$result = mysql_query("SELECT * FROM tblClients ORDER BY ClientName") or die(mysql_error());
while(#($r=mysql_fetch_array($result)))
{
?>
<option value="<?=$r['ClientID'];?>">
<?=$r['ClientName'];?>
</option>
<?php
}
?>
</select>
<br><br>
<select name="selectpromotion" size="1">
<option value=" " selected>First select a client</option>
</select>
</p>
<p>
<input name="fld_ClientID" type="text" class="Arial" id="fld_ClientID" tabindex="11" size="10" />
<br>
maybe, you shouldn't do a mysql query inside a javascript function. you should either:
use ajax to get the possible options
or
query all the possible options once then save it on a global variable
something like:
<script>
var secondOptions = {};
<?php
$promo_result = mysql_query("SELECT * FROM tblPromotions") or die(mysql_error());
while(#($m=mysql_fetch_array($promo_result))){
?>
if(secondOptions['<?=$m['ClientID'];?>'] == undefined)
secondOptions['<?=$m['ClientID'];?>'] = {};
secondOptions['<?=$m['ClientID'];?>']['<?=$m['PromotionId'];?>'] = '<?=$m['PromotionName'];?>';
<?php
}
?>
setOptions(clientId){
jQuery("select[name=selectpromotion]").empty();
options = "";
jQuery.each(secondOptions[clientID],function(a,b){
options += "<option value='"+a+"'>"+b+"</options>";
});
jQuery("select[name=selectpromotion]").append(options);
}
<select name="selectclient" size="1" onchange="setOptions(jQuery(this).val());">
...

Categories