IM trying to populate a select field with some data i receive from ajax but the other select the select_dropdow , dont populate and i dont know how to fix it, there someone who could help me with that?
I had some help to mkae the ajax work but now i dont have so im kinda lost i already try to make it with some code from js, but nothing happens in select_dropdow select and i want to populate that select with the data from the data from my sql, like in the image.
index.php
<select id="txt_maq" name="txt_maq">
<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>
<select id="select_dropdow" name="select_dropdow">
<option value="">Selecione</option>
</select>
<script>
let txt_maq =$("#txt_maq");
let select_dropdow =$("#select_dropdow");
console.log(txt_maq);
console.log(select_dropdow);
txt_maq.on("change", function() {
//faz a consulta no banco com ajax em um
$.ajax({
url: "test.php?maq="+txt_maq.val(),
context: document.body
}).done(function(response) {
console.log(response);
let resposta = JSON.parse(response);
resposta.forEach(function(valor, chave) {
option = new Option(chave, valor);
select_dropdow.options[select_dropdow.options.length] = option;
})
});
});
</script>
test.php
<?php
print_r($_GET);
include ("databaseconfig.php");
$maquina = $_GET["maq"];
$tpe_te = "";
if ($maquina == "E09"){
$type_te= "ET";
} else {
$type_te= "EP";
}
//$tpe_te = $_GET["maq"] === "E09" ? "ET" : "EP";
$consulta = "SELECT Cat_Material FROM cat_mat where TE = '" . $type_te . "' "; //código SQL
$pesquisa = mysqli_query($ligacao,$consulta);
$resultado = [];
while ($listar = mysqli_fetch_array($pesquisa)){
$resultado [$listar['Cat_Material']] = $listar['Cat_Material'];
}
echo json_encode($resultado);
?>
Here is the data when i select the first data in the first select
Related
i want to automatically select value of dropdown matching value of php variable
here is my
<select class="destinationId" id="destination" name="destinationId" onchange="getNationalityAndLiving(this.value,'','');">
<option value="" disabled selected>Select Traveling to</option>
<option data-prefix="azerbaijan" value="azerbaijan" >
Azerbaijan </option>
<option data-prefix="cambodia" value="cambodia" >
Cambodia </option>
<option data-prefix="egypt" value="egypt" >
Egypt </option>
<option data-prefix="india" value="india" >
India </option>
<option data-prefix="kenya" value="kenya" >
Kenya </option>
</select>
<select class="nationality" name="nationality" id="nationality">
<option value="" disabled selected>Select Citizen of</option>
</select>
this is my ajax code to retrive dynamic dropdown for select select option "nationality"
<script>
$(document).ready(function(){
$("#destination").change(function(){
var deptid = $(this).val();
var dbnm = "country";
var res = dbnm.concat(deptid);
$('.overlay').show();
$.ajax({
url: 'getcountry.php',
type: 'post',
data: {dest:res},
dataType: 'json',
success:function(response){
var len = response.length;
$("#nationality").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#nationality").append("<option data-nation='"+name+"' value='"+name+"'>"+name+"</option>");
}
$('.overlay').hide();
}
});
});
});
</script>
i have some dynamic php variable coming on this page from previous url.
for example
$nationality = "some value";
What i want is selected dropdown with value of $nationality in second dropdown,
if it was static i could have achieved this, but how to auto select in dynamic i am not able to get any workaround.
you can pass the php variable to js variable
var Nationality = "<?php echo $nationality; ?>";
then when append the option you can use
$("#nationality").append("<option data-nation='"+name+"' value='"+name+"' "+ (Nationality.trim() == name.trim()) ? 'selected' : '' +">"+name+"</option>");
I'm using ajax function to send select values to my php script, it is working fine but i have issue when there user add multiple data, i have option to add multiple add child in the form, user can add as many fields.
I need a each loop here. This is my code.
<select class="firstpiller" name="firstpiller">
<option value="0">0</option>
<option value="1">1</option>
</select>
<select class="thirdpiller" name="thirdpiller">
<option value="2">2</option>
<option value="3">3</option>
</select>
if (document.querySelector('[name=firstpiller]') != null){
var firstpiller = document.querySelector('[name=firstpiller]').value;
} else {
var firstpiller = null;
}
if (document.querySelector('[name=thirdpiller]') != null){
var thirdpiller = document.querySelector('[name=thirdpiller]').value;
} else {
var thirdpiller = null;
}
var stepVar = firstpiller + "--" + thirdpiller;
Can anyone help how should i write each loop here?
Thanks in advance.
add a common class to the select say you are given a class .myselect, now you can do something like below
var stepvar = '';
$('.myselect').each(function(value){
stepvar += '--' + value.val();
});
alert(stepvar);
This is my main page where I select a option field.
opt1.php:
<html>
<div>
<select id="mn" onchange = "show(this.id)" >
<option value="3">hello</option>
<option value="4">hiii</option>
<option value="5">byee</option>
</select>
</div>
<?php include 'OPT2.php'?>
</html>
This is my javascript where I get the value from above select and pass to opt2.php
function show(s1){
var s1 = document.getElementById(s1);
var ch = s1.value;
$.post('OPT2.php', {variable: ch});
}
This is my opt2.php page to display the sub select.
<?php
$con = #$_POST['ch'];
echo "SELECT MODEL:<select id=sb name=sb >";
echo "<option name=$con>$con</option>";
echo "</select>";
?>
Actually this is not generating the intended result.
Is there any logical or processing mistake?
you need to make ajax call to opt2.php to get that data
so your opt1.php should look like
<html>
<div>
<select id="s1" onchange = "show(this.id)" >
<option value="3">hello</option>
<option value="4">hiii</option>
<option value="5">byee</option>
</select>
<select id="s2">
<option>--</option>
</select>
</div>
<?php include 'OPT2.php'?>
</html>
and your javascript
<script type="text/javascript">
$("#s1").change(function(){
$('#s2').find('option').remove().end(); //clear the city ddl
var block_no = $(this).find("option:selected").text();
var s1 = document.getElementById(s1);
var ch = s1.value;
//do the ajax call
$.ajax({
url:'OPT2.php',
type:'GET',
data:{variable:s1},
dataType:'json',
cache:false,
success:function(data)
{
//data=JSON.parse(data); //no need if dataType is set to json
var ddl = document.getElementById('s2');
for(var c=0;c<data.length;c++)
{
var option = document.createElement('option');
option.value = data[c];
option.text = data[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert("Pls Reload the page");
}
});
});
I have an ajax dynamic dropdown form that onchange changes a second dropdown based on the firsts selection. However, if someone were to reset the form, all elements get cleared except for the dynamic one.
I made a reset button function that does: $('#myForm')[0].reset();
However it doesn't reset the dynamic dropdown.
Then I added $('#state').prop('selectedIndex',0); which only then selects the initial subitem.
Essentially I want it to go back to the default <option value="">State/Province</option> state that was there prior to becoming dynamic and I cannot figure out how to exactly to do this.
I am very very new and used previous questions and google to even get me this far.
Thanks
Update:
This is what I need reset:
<select name="state" class="dropdown" id="state">
<option value="">State/Province</option>
<!-- this is populated by ajax -->
</select>
This form changes the above:
<select name="country" class="dropdown" id="country" onchange="getStates();">
<option value="">Select Country</option>
<?php
$con = mysql_connect($db_host, $db_user, $db_pass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('earth');
$query = "select id,country from regions order by country";
$result = mysql_query($query);
while ( $row = mysql_fetch_object( $result ) )
{
?>
<option value=<?php echo $row->id; ?>><?php echo $row->country;?> </option>
<?php }
mysql_free_result($result);
?>
</select>
Additional code:
function getStates()
{
$('#state').html('');
var e = document.getElementById("country");
var countryID = e.options[e.selectedIndex].value;
$.ajax({
type: "POST",
url: "getStates.php",
data: {countryID:countryID},
dataType:'json',
//success: function(result){
success: function(data){
var toAppend = '';
$.each(data,function(i,o){
toAppend += '<option value=' +o.id + '>' + o.name + '</option>';
});
$('#state').append(toAppend);
},
});
}
function reset_select_box(selector, default_value)
{
if(typeof default_value !== 'string') default_value = "";
var select_box = $(document).find(selector),
children = select_box.children();
console.log(children);
for(var i in children){
if(children[i].value === ""){
select_box.prop('selectedIndex', i);
}
}
};
function resetForm()
{
// since the form is dynamic, reset form does not reset the states
$('#frmSigGen')[0].reset();
}
This seems to do the trick:
function resetForm()
{
$('#frmSigGen')[0].reset();
$('#state').empty();
$('#state').append('<option value="">State/Province</option');
}
Maybe try looping through the select elements children looking for the default value?
var reset_select_box = function(selector, default_value){
if(typeof default_value !== 'string') default_value = "";
var
select_box = $(document).find(selector),
children = select_box.children();
console.log(children);
for(var i in children){
if(children[i].value === ""){
select_box.prop('selectedIndex', i);
}
}
};
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<select id="test">
<option value="">Default</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5</option>
</select>
<button type="button" onclick="reset_select_box('#test');">Reset</button>
</body>
</html>
You could mark the newests options adding a particular data tag, i.e. data-toreset. Then, when you need to reset, remove only options with that tag.
The newest options:
<option data-toreset="1"></option>
The JQuery script could be like:
$('*[data-toreset="1"]').remove();
And then you could select the first element of your combo.
So the code below works for this particular example, and I would like to make it work in scenario where the amount of forms select + input type is dynamic determined by user on previous page. So now we have in php array of $champion[] = ("Aatrox", "somethingelse", "somethingelse2"); so now we loop the amount of select and input fields. Every champion has different spells so now when you choose Q for first champion AAtrox in input you will see "Spell1" below in somethingelse input user might want to choose E and he will see the name of the spell for that champion in the input form
<?php
$champion = "Aatrox"
?>
<select id="spell" name="spell" onchange="val()">
<option value="Passive">Passive</option>
<option value="Q" selected>Q</option>
<option value="W">W</option>
<option value="E">E</option>
<option value="R">R</option>
</select>
<input type="text" id="spellname" disabled>
<script>
var champions = {
"Aatrox":["Passive", "spell1", "spell2", "spell3", "spell4"],
"Ahri":["Passive", "spell1", "spell2", "spell3", "spell4"]
};
function change(x){
if(x==="Passive"){x=0;}
if(x==="Q"){x=1;}
if(x==="W"){x=2;}
if(x==="E"){x=3;}
if(x==="R"){x=4;}
return x;
}
function val(d) {
if(typeof d === "undefined"){
d = document.getElementById("spell").value;}
var spellname = document.getElementById("spellname");
spellname.value=champions["<?php echo $champion; ?>"][change(d)];
}
val("Q");
</script>
I can't really figure out dynamic how to check dynamic array from PHP in this javascript script
Not sure if I fully understand what you're trying to accomplish here, but here's a go at it.
<?php
$champions = array("Aatrox","Ahri");
foreach($champions as $champion){
?>
<select id="spell-<?php echo $champion ?>"
name="spell" onchange="val('<?php echo $champion ?>')">
<option value="Passive">Passive</option>
<option value="Q" selected>Q</option>
<option value="W">W</option>
<option value="E">E</option>
<option value="R">R</option>
</select>
<input type="text" id="spellname-<?php echo $champion ?>" disabled>
<?php } //end foreach ?>
<script>
var champions = {
"Aatrox":["Passive", "spell1", "spell2", "spell3", "spell4"],
"Ahri":["Passive", "spell1", "spell2", "spell3", "spell4"]
};
function change(x){
if(x==="Passive"){x=0;}
if(x==="Q"){x=1;}
if(x==="W"){x=2;}
if(x==="E"){x=3;}
if(x==="R"){x=4;}
return x;
}
function val(championName) {
d = document.getElementById("spell-" + championName).value;
var spellname = document.getElementById("spellname-" + championName);
spellname.value=champions[championName][change(d)];
}
<?php foreach($champions as $champion) {
echo "val(" . $champion . ");";
} ?>
</script>
Keep in mind it is generally bad practice to mix server side code with client side code. Although, at this point it would require a restructure of how you're handling everything (using AJAX to load JSON for example). I highly encourage you to research the topic.