html selection enable disable attribute - javascript

I have three selection boxes in one of my web page. I set the two of it to be dependent on the value of the first one like when the value of select a is 1 then the other two will be enabled and I did but the problem lies after I press the submit because after that I cannot clicked the other two even if the value of the first s still selected to 1. Here is my select boxes:
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>">
<label>Department</label>
<select class="field" id="cmbdept" name="dept" onchange="handleSelect()">
<option value=""></option>
<?php
try{
$query1 = $con->prepare("SELECT * FROM departments");
$query1->execute();
} catch(PDOException $e){
echo $e->getMessage();
exit();
}
while($r = $query1->fetch()) {
extract($r);
echo <<<EOL
<option value='$Deptname'>$Deptname</option>
EOL;
}
?>
</select>
<script type="text/javascript">
document.getElementById('cmbdept').value = "<?php echo $_GET['dept'];?>";
</script>
<label><strong>Section</strong></label>
<select id="cmbsection" name="section" disabled="disabled">
<option value=""></option>
<?php
try {
$query2 = $con->prepare("SELECT * FROM section");
$query2->execute();
} catch(PDOException $e) {
echo $e->getMessage();
exit();
}
while($s = $query2->fetch()) {
extract($s);
echo "<option value='$sectionName'>$sectionName</option>";
}
?>
</select>
<script type="text/javascript">
document.getElementById('cmbsection').value = "<?php echo $_GET['section'];?>";
</script>
<label><strong>Line</strong> </label>
<select id="cmbline" name="line" disabled="disabled">
<option value=""></option>
<?php
try{
$query3 = $con->prepare("SELECT * FROM line");
$query3->execute();
} catch(PDOException $e){
echo $e->getMessage();
exit();
}
while($t = $query3->fetch()) {
extract($t);
echo "<option value='$lineName'>$lineName</option>";
}
?>
</select>
<script type="text/javascript">
document.getElementById('cmbline').value = "<?php echo $_GET['line'];?>";
</script>
<label for="from">From</label>
<input type="text" id="from" name="from">
<script type="text/javascript">
document.getElementById('from').value = "<?php echo $_GET['from'];?>";
</script>
<label for="to">To</label>
<input type="text" id="to" name="to">
<script type="text/javascript">
document.getElementById('to').value = "<?php echo $_GET['to'];?>";
</script>
<br/>
<input type="submit" name="submit" value="Submit">
</form>
and here is the javascript that i use:
function handleSelect() {
var item1 = document.getElementById("cmbdept");
var item2 = document.getElementById("cmbsection");
if(item1.value == 'SEWING') {
document.getElementById('cmbsection').disabled = false;
document.getElementById('cmbline').disabled = false;
} else {
document.getElementById('cmbsection').disabled = true;
document.getElementById('cmbline').disabled = true;
}
}

See if this is what you are trying to do. The key here is to limit repetitions in your script. If you are doing things over and over again, like the same database call sequence, that is a signal you should be creating a function (or class) to go in place of it:
/functions/form.php
<?php
// Since you are doing the same query sequence over and over,
// just do it once and make it reusable
function fetch_query($con,$sql,$keyname = false)
{
try{
$query = $con->prepare($sql);
$query->execute();
} catch(PDOException $e){
// Let's not announce issues to users. You reveal the error
// only if the user is logged in as an administrator otherwise
// You should be able to just return an empty array so the
// web app keeps on going (unless you really want to exit, you can)
//echo $e->getMessage();
return array();
}
while($r = $query->fetch()) {
$result[] = (isset($r[$keyname]))? $r[$keyname] : $r;
}
return (!empty($result))? $result : array();
}
// Create a get_departments function
function get_departments($con)
{
return fetch_query($con,"SELECT * FROM `departments`","Deptname");
}
// Create a get_section function
function get_section($con)
{
return fetch_query($con,"SELECT * FROM `section`","sectionName");
}
// Create a get_line function
function get_line($con)
{
return fetch_query($con,"SELECT * FROM `line`","lineName");
}
// Create a sanitizer function that checks for set array keys
function to_page($array = false,$key = false)
{
if(!is_array($array))
return false;
return (isset($array[$key]))? htmlspecialchars($array[$key],ENT_QUOTES) : "";
}
/form.php (or whatever the name of this page is)
<?php
// include the php functions above
include_once("functions/form.php");
?>
<!-- INCLUDE JQUERY LIBRARIES IF NOT ALREADY SET -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>">
<label>Department</label>
<select class="field" id="cmbdept" name="dept">
<option value="">Select</option>
<?php foreach(get_departments($con) as $Deptname) {
?> <option value="<?php echo $Deptname; ?>"><?php echo $Deptname; ?></option>
<?php }
?>
</select>
<label><strong>Section</strong></label>
<select id="cmbsection" name="section" disabled="disabled">
<option value="">Select</option>
<?php foreach(get_section($con) as $sectionName) {
?> <option value="<?php echo $sectionName; ?>"><?php echo $sectionName; ?></option>
<?php }
?>
</select>
<label><strong>Line</strong> </label>
<select id="cmbline" name="line" disabled="disabled">
<option value="">Select</option>
<?php foreach(get_line($con) as $lineName) {
?> <option value="<?php echo $lineName; ?>"><?php echo $lineName; ?></option>
<?php }
?>
</select>
<label for="from">From</label>
<input type="text" id="from" name="from" value="<?php echo to_page($_GET,"from");?>" />
<label for="to">To</label>
<input type="text" id="to" name="to" value="<?php echo to_page($_GET,"to");?>" />
<br/>
<input type="submit" name="submit" value="Submit">
</form>
<script type="text/javascript">
$(document).ready(function() {
<?php
// Fetch the values of the get
$set['line'] = to_page($_GET,"line");
$set['cmbdept'] = to_page($_GET,"dept");
$set['section'] = to_page($_GET,"section");
// Remove empty
$set = array_filter($set);
// If there are any left, loop through them
if(!empty($set)) {
foreach($set as $idName => $value) {
?>$('#<?php echo $idName; ?>').val('<?php echo $value; ?>');
<?php }
}
?>
// Run on load
handleSelect();
// Run on change
$("#cmbdept").change(function() {
handleSelect();
});
});
function handleSelect()
{
var item2 = $("#cmbsection");
var item1 = $("#cmbdept");
if(item1.val() == 'SEWING') {
item2.prop("disabled",false);
$("#cmbline").prop("disabled",false);
} else {
item2.prop("disabled",true);
$("#cmbline").prop("disabled",true);
}
}
</script>

Related

AJAX form with e.preventDefault(); redirects to the PHP file

When I click the button to submit the form it sends me to the PHP file (Php/modify-recipes.php). I'm using AJAX with e.preventDefault();, but it doesn't seem to work. I have a similar form on my other page and it works fine. This one is a little bit different, the form is generated from another PHP file (it takes values from the database).
// AJAX (in HTML head tag)
<script>
$(function () {
$("#search-form").on('click', 'p.product', function(e){
var product = $(this).attr('id');
e.preventDefault();
$.ajax({
type: "post",
url: 'Php/display-modify-recipes.php',
data: { "id": product },
success: function(response) {
$(".modify-recipes").html(response);
$(".search-results").html("");
}
});
}
)});
$(function () {
$('#add_recipes_form').on('click', '#add', function (e) {
e.preventDefault();
let sendForm = true;
$('.required').each(function(){
if ($(this).val() == ''){
$(this).addClass('error', 4000);
$('#placeholder-text').html("Fill in the form");
$('#placeholder-text').addClass('error');
$('#add').addClass('error', 4000);
sendForm = false;
} else {
$(this).removeClass('error');
$('#placeholder-text').removeClass('error');
$('#add').removeClass('error');
}
})
$('.required2').each(function(){
if ($(this).val() == ''){
$('#placeholder-text').html("Fill in the form");
$('#placeholder-text').addClass('error');
$('#add').addClass('error');
$('#file_style').addClass('error');
sendForm = false;
} else {
$('#file_style').removeClass('error');
$('#placeholder-text').removeClass('error');
$('#add').removeClass('error');
}
})
if (sendForm) {
$.ajax({
type: "post",
url: 'Php/modify-recipes.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function () {
},
error: function () {
}
});
}
});
});
</script>
// HTML
<form method="POST" enctype='multipart/form-data' id="search-form" class="aaa">
<input type="text" name="search-bar" class="search-bar" placeholder="Search">
<div class="search-results"></div>
</form>
<div class="modify-recipes"></div>
// Php/display-modify-recipes.php
<?php
function display_mod_form(){
$con = mysqli_connect("localhost", "root", "", "cookbook");
$product = $_POST["id"];
$sql = "SELECT * FROM product WHERE id = '$product'";
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($res)) {
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
$type = $row['type'];
$difficulty = $row['difficulty'];
$image = $row['image'];
?>
<form method="POST" action="Php/modify-recipes.php" enctype="multipart/form-data" id="add_recipes_form" class="add-form">
<input type="text" name="id" id="<?php echo $id ?>" value="<?php echo $id ?>" style="display:none;">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="required" maxlength="28" value='<?php echo $name ?>'>
<label for="description">Desc.</label>
<input type="text" name="description" id="description" class="required" maxlength="128" value='<?php echo $description ?>'>
<label for="type">Type</label>
<select name="type" class="required">
<option value="dishes" <?php if($type == 'dishes') {echo "selected=selected"; } ?>>
Dishes
</option>
<option value="desserts" <?php if($type == 'desserts') {echo "selected=selected"; } ?>>
Desserts
</option>
<option value="snacks" <?php if($type == 'snacks') {echo "selected=selected"; } ?>>
Snacks
</option>
<option value="other" <?php if($type == 'other') {echo "selected=selected"; } ?>>
Other
</option>
</select>
<label for="difficulty">Difficulty</label>
<select name="difficulty" class="required">
<option value="easy" <?php if($difficulty == 'easy') {echo "selected=selected"; } ?>>
Ease
</option>
<option value="moderate" <?php if($difficulty == 'moderate') {echo "selected=selected"; } ?>>
Moderate
</option>
<option value="hard" <?php if($difficulty == 'hard') {echo "selected=selected"; } ?>>
Hard
</option>
</select>
<label for="image">Image (jpg, png)</label>
<label for="upload_image" id="file_style">Choose image</label>
<input type="file" style="display:none;" id="upload_image" name="image" accept="image/*" onchange="loadFile(event)" class="required2">
<div class="send-btn">
<p id="placeholder-text"></p>
<input type="submit" name="add" id="add" value="Send">
<div class="send-block"></div>
</div>
</form>
<?php
}
mysqli_close($con);
}
display_mod_form();
?>
// Php/modify-recipes.php
<?php
$con = mysqli_connect("localhost", "root", "", "cookbook");
$id = $_POST["id"];
$name = $_POST["name"];
$description = $_POST["description"];
$type = $_POST["type"];
$difficulty = $_POST["difficulty"];
if ($_FILES['image']['name'] == ""){
$sql_var = "SELECT image FROM product where id = '$id'";
$var = mysqli_query($con,$sql_var);
while($row = mysqli_fetch_assoc($var)) {
$image = $row['image'];
}
} else {
$image = $_FILES['image']['name'];
}
$sql = "
UPDATE product SET
name = '$name',
description = '$description',
type = '$type',
difficulty = '$difficulty',
image = '$image',
last_mod_date = '$mod_date'
WHERE id = '$id';
";
$target = "../Uploads/".basename($image);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
}
$var = mysqli_multi_query($con,$sql); <!-- There are more queries -->
mysqli_close($con);
?>
(Sorry for any mistakes, it's a shortened version)
There is a third ajax function and PHP file, but it's not important (simple search bar). I tried other things like action="", no action at all, etc., but it didn't work.
How to fix this?
Edit: There is only one form (when you click on p.product it displays the form according to the data in the database). The problem occurs ONLY when I'm submitting the "add_recipes_form", there is no problem with the search box. Please don't mark this question as a duplicate of a 10 year old post that is irrelevant to my problem.

Can't get value of select list with Javascript when it is created using PHP array from database

If I generate a select list using PHP from the results of a database query, for some reason I can't then use Javascript to get the value of the currently selected item. I tested this code with a static list and it works no problem. Here is my code:
<?php
require_once("config.php");
$sql="SELECT * FROM animals ORDER BY name ASC";
try
{
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_UNIQUE); //each column is addressed by the primary key
}
catch (Exception $ex)
{
echo $ex->getMessage();
}
?>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function(){
$("#animal_list").change(function(){
var animalValue = $(this).val();
window.location.href="animal_list.php?id=" + animalValue;
});
});
</script>
</head>
<body>
<select id="animal_list" name="animal_list">
<?php
foreach($results as $res)
{
?>
<?php echo '<option value="'. $res['id'] . '">' ?>
<?php echo $res['name'] ?>
</option>
<?php
}
?>
</select>
<br/><br/>
<?php
if(isset($_GET['id']))
{
echo '<input type="text" id="npsw_code" value="' . $_GET['id'] . '" readonly>';
}
else
echo '<input type="text" id="npsw_code" value="" readonly>';
?>
</body>
</html>
Testing with a static list works. Here is the example:
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function(){
$("#fruits").change(function(){
var fruitValue = $(this).val();
window.location.href="fruits.php?id=" + fruitValue;
});
});
</script>
</head>
<body>
Fruits
<select id="fruits" name="fruits">
<option value="0">Apple</option>
<option value="1">Pear</option>
<option value="2">Watermelon</option>
<option value="3">Orange</option>
</select>
<br/><br/>
<?php
if(isset($_GET['id']))
{
echo 'My Fruit <input type="text" id="myfruit" value="' . $_GET['id'] . '" readonly>';
}
else
echo 'My Fruit <input type="text" id="myfruit" value="" readonly>';
?>
</body>
</html>
remove onchange="listChange()" because is not defined and we dont need it.
and use $(this).find('option:selected').val(); for get value of option selected.
$("#animal_list").change(function(){
var animalValue = $(this).find('option:selected').val();
window.location.href="animal_list.php?id=" + animalValue;
});
First off I would clean this mess up.
<select id="animal_list" name="animal_list">
<?php
foreach($results as $res)
{
?>
<?php echo '<option value="'. $res['id'] . '">' ?>
<?php echo $res['name'] ?> <!-- missing ; -->
</option>
<?php
}
?>
</select>
<br/><br/>
<?php
if(isset($_GET['id']))
{
echo '<input type="text" id="npsw_code" value="' . $_GET['id'] . '" readonly>';
}
else
echo '<input type="text" id="npsw_code" value="" readonly>';
?>
Sorry I just can't deal with poorly formatted code, it makes reading it a chore. It just seems like so much wasted effort.
<select id="animal_list" name="animal_list">
<?php foreach($results as $res): ?>
<option value="<?php echo $res['id'];?>"><?php echo $res['name']; ?></option>
<?php endforeach; ?>
</select>
<br/><br/>
<?php
$readonly = '';
$npsw_code = '';
if(isset($_GET['id'])){
$readonly = ' readonly';
$npsw_code = $_GET['id'];
}
?>
<input type="text" id="npsw_code" value="<?php echo $npsw_code; ?>" <?php echo $readonly; ?>>
We'll also ignore this (missing ; ):
<?php echo $res['name'] ?>
Probably a syntax error, but see that's what happens when you cant read the code.
Javascript don't care how the HTML got in the page, only what the HTML looks like. Without knowing what it looks like, all we can do is guess. You can view source and see what it looks like.
Otherwise, put an alert in the on change handler and see what it says.
$("#animal_list").change(function(){
var animalValue = $(this).val();
alert(animalValue);
window.location.href="animal_list.php?id=" + animalValue;
});
Alert has the nice side effect of halting/pausing Javascript execution so it will interrupt the page redirect. This will tell you 2 things,
your event is being fired on change
the value is correct.
Never mind it was a typo. The column in my database was 'code' not 'id'. So it should have read . Sorry for wasting your time.

codeigniter 3rd combo box does not display data

This is my Model
function getMatkul($dosen) {
$data = array();
$query = $this->db->get_where('input_jadwal', array('dosen' => $dosen));
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
function getKelas($matkul) {
$data = array();
$query = $this->db->get_where('input_jadwal', array('kode_matkul'=>$matkul));
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
This is my View
<select name="dosen" id="dosen" class="form-control" required="">
<option disabled="" selected="">Dosen</option>
<?php foreach($dosen as $d){ ?>
<option value="<?php echo $d['dosen']; ?>"><?php echo $d['dosen']; ?></option>
<?php } ?>
</select>
</div>
<div class="col-md-12 form-group">
<select name="matkul" id="matkul" class="form-control" required="">
<option disabled="" selected="">Mata Kuliah</option>
<?php foreach($matkul as $m) {?>
<option value="<?php echo $m['kode_matkul']; ?>"><?php echo $m['matkul']; ?></option>
<?php } ?>
</select>
</div>
<div class="col-md-12 form-group">
<select name="kelas" id="kelas" class="form-control" required="">
<option disabled="" selected="">Kelas</option>
<?php foreach($kelas as $k) {?>
<option value="<?php echo $k['kelas']; ?>"><?php echo $k['kelas']; ?></option>
<?php } ?>
</select>
</div>
<div class="col-md-12 form-group">
<button name="mysubmit" class="btn btn-primary pull-left btn-flat" type="submit">Show Record</button>
</div>
</div>
</div>
</form>
</div>
</section>
<script type="text/javascript">
<?php
$this->load->model('combobox_model');
foreach($dosen as $dm) { ?>
var <?php echo str_replace(' ','',$dm['dosen'].$dm['dosen']); ?> = [
<?php $resultM = $this->combobox_model->getMatkul($dm['dosen']); ?>
<?php foreach ($resultM as $rm) { ?>
{display: "<?php echo $rm['matkul']; ?>", value: "<?php echo $rm['kode_matkul']; ?>" },
<?php } ?>];
<?php } ?>
$("#dosen").change(function() {
var parent = $(this).val();
switch(parent){
<?php foreach($dosen as $dd){ ?>
case '<?php echo $dd['dosen']; ?>':
lista(<?php echo str_replace(' ','',$dd['dosen'].$dd['dosen']); ?>);
break;
<?php } ?>
default: //default child option is blank
$("#matkul").html('');
break;
}
});
function lista(array_list)
{
$("#matkul").html(""); //reset child options
$(array_list).each(function (i) { //populate child options
$("#matkul").append("<option value=\""+array_list[i].value+"\">"+array_list[i].display+"</option>");
});
}
</script>
<script type="text/javascript">
<?php
$this->load->model('combobox_model');
foreach($matkul as $mk) { ?>
var <?php echo str_replace(' ','',$mk['matkul'].$mk['kode_matkul']); ?> = [
<?php $resultK = $this->combobox_model->getKelas($mk['kode_matkul']); ?>
<?php foreach ($resultK as $rk) { ?>
{display: "<?php echo $rk['kelas']; ?>", value: "<?php echo $rk['kelas']; ?>" },
<?php } ?>];
<?php } ?>
$("#matkul").change(function() {
var parent = $(this).val();
switch(parent){
<?php foreach($matkul as $tt){ ?>
case '<?php echo $tt['kode_matkul']; ?>':
listb(<?php echo str_replace(' ','',$tt['matkul'].$tt['kode_matkul']); ?>);
break;
<?php } ?>
default: //default child option is blank
$("#kelas").html('');
break;
}
});
function listb(array_list)
{
$("#kelas").html(""); //reset child options
$(array_list).each(function (i) { //populate child options
$("#kelas").append("<option value=\""+array_list[i].value+"\">"+array_list[i].display+"</option>");
});
}
</script>
Combobox 1 linked to combobox 2, combobox 2 linked to combobox 3. when When I run it, only combo box 1 and 2 which have the data. I think the problem is on javascript. Need help, thank you. This is the pic of my combobox

JQuery or Javascript filter select options

I'm developing an app that have a form that contains two selects populated dynamically with arrays.
The second select is disabled if there isn't a choice in the first of them and i need to filter the options of the second select respect the choice of the first.
Whereas I must to pass these values to another PHP page I mustn't do the filter using the value attribute.
I've tried to use a custom attribute but without results.
This is my code,
<tr>
<td style="color: white;">Seleziona data: </td>
<td>
<select class="form-control" name="data" id="select1">
<option value="prova" disabled selected> Scegli</option>
<?php for ($y=0; $y<count($giorni); $y++){ $giorno=$ giorni[$y];?>
<option value="<?php echo $giorno; ?>" id="<?php echo $y; ?>">
<?php echo $giorno; ?> </option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td style="color: white;">Seleziona ora: </td>
<td>
<select class="form-control" name="ora" id="select2" disabled>
<?php $count=1 ; while ($count <=3 ){ if ($count==1 ){ for ($g=0; $g<count($ora1); $g++){ ?>
<option id="<?php echo $count-1; ?>" value="<?php echo $ora1[$g]; ?>">
<?php echo $ora1[$g]; ?>
</option>
<?php } $count ++; } ?>
<?php if ($count==2 ){ for ($g=0; $g<count($ora2); $g++){ ?>
<option id="<?php echo $count-1; ?>" value="<?php echo $ora2[$g]; ?>">
<?php echo $ora2[$g]; ?>
</option>
<?php } $count ++; } ?>
<?php if ($count==3 ){ for ($g=0; $g<count($ora2); $g++){ ?>
<option id="<?php echo $count-1; ?>" value="<?php echo $ora3[$g]; ?>">
<?php echo $ora3[$g]; ?>
</option>
<?php } $count ++; } } ?>
</select>
</td>
</tr>
JAVASCRIPT:
<script>
document.getElementById('select1').onchange = function() {
document.getElementById('select2').disabled = false;
};
</script>
<script>
$("#select1").change(function() {
if ($(this).data('options') == undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).id();
var options = $(this).data('options').filter('[id=' + id + ']');
$('#select2').html(options);
});
</script>
How can I solve it?
Thanks
There is an issue with your html. There is more than one option with an identical id. On a html document, ids must be unique.
For the same reason, you cannot filter your options on the id value.
What you should do is to use a data- attribute instead the id attribute. This will allow you to filter on it.
You could use the json_encode function to generate JSON objects in your PHP code and create the select2 options dynamically on the client side.
<tr>
<td style="color: white;">Seleziona data: </td>
<td>
<select class="form-control" name="data" id="select1">
<option value="prova" disabled selected> Scegli</option>
<?php
foreach ($giorni as $key => $value) {
?>
<option value="<?php echo $value; ?>" id="<?php echo $key; ?>" ><?php echo $value; ?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td style="color: white;">Seleziona ora: </td>
<td>
<select class="form-control" name="ora" id="select2" disabled></select>
</td>
</tr>
<script>
// the options object contains the possible option values for select2
// it can be accessed as an associative array using the selected value from select1
var options = {
"0" : <php echo json_encode($ora1, JSON_FORCE_OBJECT) ?>,
"1" : <php echo json_encode($ora2, JSON_FORCE_OBJECT) ?>,
"2" : <php echo json_encode($ora3, JSON_FORCE_OBJECT) ?>
};
// a helper variable to prevent unnecessary work
var prevSelectedValue = null;
// onChange handler for select1
document.getElementById('select1').onchange = function () {
var selectedValue = document.getElementById('select1').value;
if (selectedValue && (prevSelectedValue != selectedValue)) {
// select1 has changed so there is work to do
// 1 - get a handle on select2 to make code more legible
var select2 = document.getElementById('select2');
// 2 - remove all existing options
select2.options.length = 0;
// 3 - add new options
var obj = options[selectedValue];
// iterate through the object to get the keys and values
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var newOption = document.createElement('option');
newOption.text = obj[key];
newOption.value = key;
select2.options.add(newOption);
}
}
// 4 - enable select2
select2.disabled = false;
// 5 - record select1 change in prevSelectedValue
prevSelectedValue = selectedValue;
}
};
</script>

How to be a div id is undefined in javaScript?

I want to get the product id called "product_id" through a alert in javaScript. But it gives "undefined" as the alert. I am getting data from a database.
Here is my PHP code.
$jsql_ae7 = mysql_query("select request_list.product_id from request_list where request_list.product_id='{$jrowa2['id']}' and request_list.email='$visit_email'") or die(mysql_error());
$jfeta7 = mysql_fetch_assoc($jsql_ae7);
Here is my HTML code.
<div class="col-sm-2">
<select id="<?php echo $jfeta7['product_id']; ?>" name="aformats" onchange="showFormat(this);">
<option value="<?php echo $jrowa2['formats']; ?>"><?php echo $jrowa2['formats']; ?></option>
<?php foreach($formats3 as $v3){ ?>
<?php if($v3 !== $jrowa2['formats']) { ?>
<option value="<?php echo $v3; ?>"><?php echo $v3; ?></option>
<?php } ?>
<?php } ?>
</select>
</div>
Here is my javaScript code.
var showFormat = function(dd) {
var format_select_id = $(this);
var product_id = format_select_id.attr("id");
alert(product_id);
};
Here is a screenshot of my page.
change with this
var showFormat = function(dd) {
var product_id = dd.id;
alert(product_id);
};
Why not just pass the product id directly?
<select id="<?php echo $jfeta7['product_id']; ?>" name="aformats" onchange="showFormat(<?php echo $jfeta7['product_id']; ?>);">
and your showFormat()
function showFormat(dd) {
alert(dd);
};

Categories