im trying to get some data from a DropDown menu and i want to use that value when it change to make a Query in a secound DropDown but until now, i was unable to send the Value to my php with the javascript.
Im using this code:
<script type="text/javascript" language="javaScript">
function flow() {
var x = document.getElementById("txt_maq").value;
document.getElementById("demo").innerHTML = x;
var maq = document.getElementById('txt_maq').value;
var cat = document.getElementById('txt_catmaterial').value;
if (maq != "")
{
document.getElementById('txt_catmaterial').disabled=false;
}
if (cat == "")
{
document.getElementById('txt_material').disabled=true;
}
if (cat != "")
{
document.getElementById('txt_material').disabled=false;
}
}
</script>
<div class="col-2">
<div class="input-group">
<label class="label">Maq. Destino</label>
<div class="rs-select2 js-select-simple select--no-search">
<select id="txt_maq" name="txt_maq" onchange="flow()">
<option value="">Selecione</option>
<option value="E02">E02</option>
<option value="E03">E03</option>
<option value="E04">E04</option>
<option value="E05">E05</option>
<option value="E06">E06</option>
<option value="E07">E07</option>
<option value="E08">E08</option>
<option value="E04/E07">E04/E07</option>
<option value="E04/E08">E04/E08</option>
<option value="E03/E04">E03/E04</option>
<option value="E03/E07">E03/E07</option>
<option value="E04/E07/E08">E04/E07/E08</option>
<option value="E03/E07/E08">E03/E07/E08</option>
<option value="E07/E08">E07/E08</option>
<option value="E09">E09</option>
</select>
<div class="select-dropdown"></div>
</div>
</div>
</div>
</div>
<div class="row row-space">
<div class="col-2">
<div class="input-group">
<label class="label">Cat. Material</label>
<div class="rs-select2 js-select-simple select--no-search">
<select id="txt_catmaterial" disabled="true" name="txt_catmaterial" onchange="flow()">
<option value=""></option>
<?php
$maquina = $_POST['txt_maquina'];
$type_te = "";
if ($maquina == "E09"){
$type_te= "ET";
} else {
$type_te= "EP";
}
echo $type_te;
$selecione = "";
$consulta = "SELECT Cat_Material FROM cat_mat where TE = '".$type_te."' "; //código SQL
$resultado = mysqli_query($ligacao,$consulta);
while ($listar = mysqli_fetch_array($resultado)){
$catmat = $listar['Cat_Material'];
echo "<option value=".$catmat.">$catmat</option>";
}
?>
</select>
<div class="select-dropdown"></div>
</div>
</div>
</div>
</div>
All I try to do is make a If if the txt_maq is E09 so I can do the query in the txt_catmaterial but the value doesn't come from the javascript.
Use Ajax to send data from Javascript to PHP
function testEndpoint(){
$.ajax({
url: "https://path/to/your-php-script.php",
type: "POST",
crossDomain: true,
data: {"txt_maq": $("#txt_maq").val()},
dataType: "json",
error: function(xhr, status, error){
console.log("Error: " + error);
},
success: function(result, status, xhr){
console.log(result);
}
});
}
testEndpoint();
At your PHP script your-php-script.php
You can use txt_maq as a POST variable:
$useTxtMag = $_POST['txt_maq'];
The Ajax should be used after the jQuery is included or you can simply include the jQuery in your head element
I have a textbox and selected option list of 4 options like below...
<select id="select2" class="form-control">
<option value="pre">Pre</option>
<option value="rep" selected="selected">Rep</option>
<option value="new">New</option>
<option value="dec">Dec</option>
</select>
and a textbox where user input some keywords and based on keywords i want to change selected option in above option list
<td id="fpv_col1" contenteditable="">decorating and repair work</td>
main value for selction comes from php and ajax based on user input
so i just want to set selected value in above option list
below is my jquery code
$(document).on('keyup', '#fpv_col1', function(event) {
var desc_text = $(this).text();
$.ajax({
url: 'php/fpv_lbyl_prediction.php',
type: 'POST',
data:{
value1:desc_text,
},
dataType:'text',
success: function(data){
$("#error_msg").fadeIn();
$("#error_msg").html("<strong>Success!</strong> "+data);
//$('select#select2 option').removeAttr('selected');
//$('select#select2').find('option[value='+data+']').attr("selected",true);
$('select#select2 option').removeAttr('selected').filter('[value='+data+']').attr('selected', true);
}
});
event.preventDefault();
});
my jquery code works fine, it set selected option but not displaying selected option, it saw using inspect
$(document).ready(function() {
$('#otherCategory').keyup(function() {
if ($(this).val() == 0) {
$('#category').val(1);
} else if ($(this).val() > 0) {
$('#category').val(2);
} else {
$('#category').val(0);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="category" name="category">
<option value="0">Please select</option>
<option value="1">Clear</option>
<option value="2">UnClear</option>
</select>
<input type="text" id="otherCategory" name="otherCategory">
Here I want to display the images according to the numbers selected from the select box and my values in select box are 9,12,18 and here is my code
my view page looks like this...
<form action="<?php echo base_url();?>roxcontrol/numberdisplay" id="numberdisplay" method="post">
<div class="col-md-4 col-sm-4 none-xs text-center">
<div class="limiter hidden-xs">
<label>Show</label>
<select name="gallery" id="gallery">
<option selected="selected" value="9">9</option>
<option value="12">12</option>
<option value="24">24</option>
<option value="36">36</option>
</select>
per page
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
//alert();
$("#numberdisplay").change(function() {
var parent = $(this).val();
//alert(parent);
var url = '<?php echo base_url(); ?>roxcontrol/ajax_get_sub';
$.post(url, {
parent: parent
}, function(data)
{
$('#gallery').html(data);
});
});
});
</script>
My control page looks like this
public function ajax_get_sub()
{
$gal_id=$this->input->post('parent');
$data['galery']=$this->roxmodel->get_gallery_by_number($gal_id);
$this->load->view('ajax_get_sub',$data);
}
My model page looks like this.
public function get_gallery_by_number($gal_id)
{
$this->db->order_by("gallery.id","desc");
$query=$this->db->limit($gal_id)->get('gallery');
return $query->result();
}
Here I am not getting any images
In controller Just get Post value from ajax call and try this
public function ajax_get_sub()
{
$gal_id=$this->input->post('gal_id');
$this->db->order_by("id","desc");
$query=$this->db->limit($gal_id)->get('gallery');
$var="";
foreach($query->result() as $row)
{
$var .= "<img src=".$row->img_url."/> </br>"; //your table image url(path)
}
echo $var;
}
In view File
<div class="col-md-4 col-sm-4 none-xs text-center">
<div class="limiter hidden-xs">
<label>Show :</label>
<select name="gallery" id="gallery">
<option selected="selected" value="9">9</option>
<option value="12">12</option>
<option value="24">24</option>
<option value="36">36</option>
</select>
per page
</div>
<div id="img_display">
<script type="text/javascript">
$(document).ready(function() {
$("#gallery").change(function() {
var gal_id = $("#gallery").val();
alert(gal_id);
$.ajax({
type: "post",
url: base_url+'sample_controller/ajax_get_sub',
cache: false,
data: {gal_id:gal_id},
success: function(get_img){
try{
$("#img_display").append(get_img);
}catch(e) {
alert('Exception while request..'+JSON.stringify(e));
}
},
error: function(e){
alert('Error while request..'+JSON.stringify(e));
}
});
});
});
Dont forget to give value for gallery select option.
This is one of the way to append the element.
I Edited
I have a html
<select name="action-grid">
<option selected > Select</option>
<option value="1" >Edit</option>
</select>
<select name="action-grid">
<option selected > Select</option>
<option value="2" >Edit</option>
</select>
<?php $_product = $this->getProductBy($values);?>
<div><?php echo $_product->getName();?></div>
in code php. i have function getProductBy($value){....}. in view i have grid product, in column action i want when chose option edit value will set variable $value.
Html code, (Assuming Jquery included)
<script type="text/javascript">
function getNewFunction(val) {
$.ajax({
url: "./myPhp.php",
method: 'POST',
data: {
'value': val
},
success: function(res) {
console.log(res);
}
});
}
</script>
<select onchange="getNewFunction(this.value)" name="action-grid">
<option selected > Select</option>
<option value="1" >First</option>
</select>
myPhp.php
<?php
echo $_POST['value'];
?>
As per you mentioned in comments
Your script
<script type="text/javascript">
function getNewFunction(gridValue){
$.ajax({
type: 'POST',
url : 'some_file.php',
data: {value: gridValue},
success: function(response) {}
})
}
</script>
in some_file.php file
<?php
$value = $_POST['value'];
//your funtion here
function getProductEdit($value)
{
.....
}
?>
<select onchange="getNewFunction($('option:selected', this))" name="action-grid">
<option selected>Select</option>
<option value="2">Second</option>
</select>
<script type="text/javascript">
function getNewFunction(value) {
alert(value.text());
}
</script>
try this way
demo
I have 2 different SELECT OPTION in a form.
The first one is Source, the second one is Status. I would like to have different OPTIONS in my Status drop-down list depending on the OPTION selected in my Source drop-down.
Source:
<select id="source" name="source">
<option>MANUAL</option>
<option>ONLINE</option>
</select>
Status:
<select id="status" name="status">
</select>
Options:
- If Source is MANUAL, then Status is OPEN or DELIVERED
- If Source is ONLINE, then Status is OPEN or DELIVERED or SHIPPED
My non-working attempt:
<script>
$(document).ready(function () {
var option = document.getElementById("status").options;
if (document.getElementById('source').value == "MANUAL") {
$("#status").append('<option>OPEN</option>');
$("#status").append('<option>DELIVERED</option>');
}
if (document.getElementById('source').value == "ONLINE") {
$("#status").append('<option>OPEN</option>');
$("#status").append('<option>DELIVERED</option>');
$("#status").append('<option>SHIPPED</option>');
}
});
</script>
Try something like this... jsfiddle demo
HTML
<!-- Source: -->
<select id="source" name="source">
<option>MANUAL</option>
<option>ONLINE</option>
</select>
<!-- Status: -->
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
</select>
JS
$(document).on('ready', function () {
$("#source").on('change', function () {
var el = $(this);
if (el.val() === "ONLINE") {
$("#status").append("<option>SHIPPED</option>");
} else if (el.val() === "MANUAL") {
$("#status option:last-child").remove();
}
});
});
I am posting this answer because in this way you will never need any plugin like jQuery and any other, This has the solution by simple javascript.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
function dynamicdropdown(listindex)
{
switch (listindex)
{
case "manual" :
document.getElementById("status").options[0]=new Option("Select status","");
document.getElementById("status").options[1]=new Option("OPEN","open");
document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
break;
case "online" :
document.getElementById("status").options[0]=new Option("Select status","");
document.getElementById("status").options[1]=new Option("OPEN","open");
document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
document.getElementById("status").options[3]=new Option("SHIPPED","shipped");
break;
}
return true;
}
</script>
</head>
<title>Dynamic Drop Down List</title>
<body>
<div class="category_div" id="category_div">Source:
<select id="source" name="source" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="">Select source</option>
<option value="manual">MANUAL</option>
<option value="online">ONLINE</option>
</select>
</div>
<div class="sub_category_div" id="sub_category_div">Status:
<script type="text/javascript" language="JavaScript">
document.write('<select name="status" id="status"><option value="">Select status</option></select>')
</script>
<noscript>
<select id="status" name="status">
<option value="open">OPEN</option>
<option value="delivered">DELIVERED</option>
</select>
</noscript>
</div>
</body>
</html>
For more details, I mean to make dynamic and more dependency please take a look at my article create dynamic drop-down list
function dropdownlist(listindex)
{
document.getElementById("ddlCity").options.length = 0;
switch (listindex)
{
case "Karnataka":
document.getElementById("ddlCity").options[0] = new Option("--select--", "");
document.getElementById("ddlCity").options[1] = new Option("Dharawad", "Dharawad");
document.getElementById("ddlCity").options[2] = new Option("Haveri", "Haveri");
document.getElementById("ddlCity").options[3] = new Option("Belgum", "Belgum");
document.getElementById("ddlCity").options[4] = new Option("Bijapur", "Bijapur");
break;
case "Tamilnadu":
document.getElementById("ddlCity").options[0] = new Option("--select--", "");
document.getElementById("ddlCity").options[1] = new Option("dgdf", "dgdf");
document.getElementById("ddlCity").options[2] = new Option("gffd", "gffd");
break;
}
}
*
State:
--Select--
Karnataka
Tamilnadu
Andra pradesh
Telngana
<div>
<p>
<label id="lblCt">
<span class="red">*</span>
City:</label>
<select id="ddlCity">
<!-- <option>--Select--</option>
<option value="1">Dharawad</option>
<option value="2">Belgum</option>
<option value="3">Bagalkot</option>
<option value="4">Haveri</option>
<option>Hydrabadh</option>
<option>Vijat vada</option>-->
</select>
<label id="lblCity"></label>
</p>
</div>
In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:
<select id="continents">
<option value = 0>All</option>
<option value = 1>Asia</option>
<option value = 2>Europe</option>
<option value = 3>Africa</option>
</select>
<select id="selectcountries"></select>
Uses (in the jsFiddle)
MAIN.createRelatedSelector
( document.querySelector('#continents') // from select element
,document.querySelector('#selectcountries') // to select element
,{ // values object
Asia: ['China','Japan','North Korea',
'South Korea','India','Malaysia',
'Uzbekistan'],
Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
}
,function(a,b){return a>b ? 1 : a<b ? -1 : 0;} // sort method
);
[Edit 2021] or use data-attributes, something like:
document.addEventListener("change", checkSelect);
function checkSelect(evt) {
const origin = evt.target;
if (origin.dataset.dependentSelector) {
const selectedOptFrom = origin.querySelector("option:checked")
.dataset.dependentOpt || "n/a";
const addRemove = optData => (optData || "") === selectedOptFrom
? "add" : "remove";
document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
.forEach( opt =>
opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
}
}
[data-from-dependent] {
display: none;
}
[data-from-dependent].display {
display: initial;
}
<select id="source" name="source" data-dependent-selector="#status">
<option>MANUAL</option>
<option data-dependent-opt="ONLINE">ONLINE</option>
<option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
<option data-from-dependent="ONLINE">SHIPPED</option>
<option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
<option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
You're better off making two selects and showing one while hiding the other.
It's easier, and adding options to selects with your method will not work in IE8 (if you care).
I hope the following code will help or solve your problem or you think not that understandable visit http://phppot.com/jquery/jquery-dependent-dropdown-list-countries-and-states/.
HTML DYNAMIC DEPENDENT SELECT
<div class="frmDronpDown">
<div class="row">
<label>Country:</label><br/>
<select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Country</option>
<?php
foreach($results as $country) {
?>
<option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>State:</label><br/>
<select name="state" id="state-list" class="demoInputBox">
<option value="">Select State</option>
</select>
</div>
GETTING STATES VIA AJAX
<script> function getState(val) { $.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
$("#state-list").html(data);
}
});} </script>
READ STATE DATABASE USING PHP
<?php require_once("dbcontroller.php"); $db_handle = new DBController();if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results = $db_handle->runQuery($query); ?> <option value="">Select State</option><?php foreach($results as $state) { ?> <option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option><?php } } ?>
for this, I have noticed that it far better to show and hide the tags instead of adding and removing them for the DOM. It performs better that way.
The answer should be updated to replace the defunct functions .change & .ready
$(document).on('ready',function() {
$("#source").on('change', function(){
var el = $(this);
if (el.val() === "ONLINE") {
$("#status").append("<option>SHIPPED</option>");
} else if (el.val() === "MANUAL") {
$("#status option:last-child").remove();
}
});
});