Dynamic PHP array with accordingly added onchange scripts - javascript

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.

Related

Populate a select with js in a foreache

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

Limiting the options in a combobox, based on the selected one

I made a similar question yesterday, but couldn't come up with a solution since then, so i went and refined my code a bit to a logic that seemed more plausible to work.
However, it didn't.
I want to have only a couple of options in a combobox available to the user, depending on what option was pre-selected. Here is the Combobox:
<SELECT class=caixas id=cbostatus style="WIDTH: 3cm;" tabIndex=25 name=cbostatus onchange= "StatusTest(); hideField();" >
<option selected></option>
<option value="Planned" id="optionPlanned" <?php if ($row['task_status']=='Planned') echo 'selected="selected"';?>>Planned</option>
<option value="Started" id="Started" <?php if ($row['task_status']=='Started') echo 'selected="selected"';?>>Started</option>
<option value="Available" id="Available" <?php if ($row['task_status']=='Available') echo 'selected="selected"';?>>Available</option>
<option value="Finished" id="Finished" <?php if ($row['task_status']=='Finished') echo 'selected="selected"';?>>Finished</option>
<option value="Impeded" id="Impeded" <?php if ($row['task_status']=='Impeded') echo 'selected="selected"';?>>Impeded</option>
</SELECT>
For example, when "Planned" is selected, the only other available option should be "Started". So i went and made a Javascript, for a Onchange Event, like so:
function hideField(){
var e = document.getElementById("cbostatus");
var strUser = e.options[e.selectedIndex].value;
if( strUser == 'Planned' ) {
document.getElementById("Impeded").style.display = 'none';
document.getElementById("Available").style.display = 'none';
document.getElementById("Finished").style.display = 'none';
}
}
And for some reason, it is wrong. Any ideas?
(Also, i'd aprecciate if you didn't suggest using Jquery, as i have never used before and don't really have time to learn for this)
I suggest you start with an empty select, and add the options dynamically.
var e=document.getElementById("cbostatus");
var strUser = 'Planned'; // get this value from somewhere, maybe a hidden field
if( strUser == 'Planned' ) {
e.options[e.length]=new Option("Planned", "optionPlanned", true, true);
e.options[e.length]=new Option("Started", "Started");
} else if ..
Use this code.
Html
<select class=caixas id=cbostatus style="WIDTH: 3cm;" tabIndex=25 name=cbostatus>
<option selected></option>
</select>
jQuery
var insertoption = "";
first add options in ready function
$(document).ready(function()
{
insertoption += "<option value='Planned' id='Planned'>Planned</option>";
insertoption += "<option value='Started' id='Started'>Started</option>";
insertoption += "<option value='Available' id='Available'>Available</option>";
insertoption += "<option value='Finished' id='Finished'>Finished</option>";
insertoption += "<option value='Impeded' id='Impeded'>Impeded</option>";
$("#cbostatus").append(insertoption);
insertoption = "";
});
This is create your option
and now create onchange function
$("#cbostatus").on("change",function()
{
if($("#cbostatus").val() == "Planned")
{
$("#cbostatus").children().remove();
insertoption = "<option value='Started' id='Started'>Started</option>";
$("#cbostatus").append(insertoption);
}
});

This function how to use switch case

I am new in PHP and JS. This function use to get only one vales.
In my program dept1 values are 5 and 1st value select onchange in 1, 2nd select onchange in 2, 3rd value select onchange in 3. so any idea to give code for switch case.
<script>
function deptchange()
{
var x = document.getElementById("dept1").value;
document.getElementById("dept2").value = 2;
}
</script>
<input class="form-last-name form-control" id= 'dept1'
onchange="deptchange()" list="dept" value='<?php echo $dept; ?>' name="department"/>
<datalist id="dept">
<option>
<?php
include 'dblayer.php';
$query = mysqli_query($mysqli,"SELECT department FROM department");
while($row=mysqli_fetch_array($query))
{
echo "<option value='". $row['department']."'>".$row['department'] .'</option>';
}
?>
</option>
</datalist>
<input type="hidden" id='dept2' value=' 'class="form-first-name form-control" />
You can use array with push, So after finished your 5 selection all 5 values push to values array.
<script>
var values = [];
function deptchange()
{
values.push(document.getElementById("dept1").value);
}
</script>
To get the stored elements from array.
var firstElement = values[0];
datalist's option should have value attribute. and there is no need to put closing tag. it's different from select's option.
<datalist id="dept">
<?php
include 'dblayer.php';
$query = mysqli_query($mysqli,"SELECT department FROM department");
while($row=mysqli_fetch_array($query)) {
echo "<option value='". $row['department']."'>';
}
?>
</datalist>

Reset a dynamic dropdown back to initial state

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.

How can I pass select-option value of the html code into the php file by javascript?

My script code is for ajax function in database.
The code is same as below.
<script>
function showUser(str)
{
.....
}
var selectedLang2 = document.getElementById('lang2').value;
var selectedSubject1 = document.getElementById('subject1').value;
xmlhttp.open("GET","db_"+selectedLang2+".php?q="+str,true);
xmlhttp.send();
}
</script>
According to above script code, script code only calls the php file which is selected-option value. So my select-option code is same as below
<form>
<select name="lang2" id="lang2">
<option value="co">한국어</option>
<option value="en">English</option>
<option value="af">Afrikaans</option>
<option value="ar">Arabic</option>
.......
</select>
<select name="subject1" id="subject1">
<option value="a">Infection : bacteria and virus </option>
<option value="b">Infection : virus, fungus and etc</option>
<option value="c">Malignant neoplasm</option>
----
</select>
So I want to use php variables code(here is, $lang1, $subject1) as like below code.
<?php
$q = htmlspecialchars($_GET['q']);
$lang2 = $REQUEST_['lang2'];
$subject1 = $REQUEST_['subject1'];
$con = mysqli_connect('localhost','root','autoset','my_db');
if (!$con)
......
How have i to write script code.
/*Here is target point.
var selectedLang2 = document.getElementById('lang2').value;
var selectedSubject1 = document.getElementById('subject1').value;
xmlhttp.open("GET","db_"+selectedLang2+".php?q="+str,true);
xmlhttp.send(); */
Please, give me a piece of advice.
Thank you
You can't send any info by GET without specifying the url parameters. But you can add extra parameters to the request url to achieve this.
Change your JS:
var selectedLang2 = document.getElementById('lang2').value;
var selectedSubject1 = document.getElementById('subject1').value;
xmlhttp.open("GET","db_" + selectedLang2 + ".php?q=" + str + "&lang2=" + selectedLang2 + "&subject1=" + selectedSubject1,true);
xmlhttp.send();
Change your PHP:
$q = htmlspecialchars($_GET['q']);
$lang2 = htmlspecialchars($_GET['lang2']);
$subject1 = htmlspecialchars($_GET['subject1']);

Categories

Resources