I have a table “tb_seri” in MySQL, with columns “id_seri”, “nm_seri” and “value_seri”
So, I want to select “nm_seri” in the select option, and then “value_seri” will appear in the textbox afterwards based on “nm_seri” selected
Here is the code to select “nm_seri” from the database
JavaScript
x
13
13
1
<select name="nm_seri" id="nm_seri" onchange="myfunction()" required>
2
<option disabled selected>-Pilih Seri-</option>
3
<?php
4
$qu="Select DISTINCT nm_seri from tb_seri";
5
$res=$koneksi->query($qu);
6
7
while($r=mysqli_fetch_row($res))
8
{
9
echo "<option data-value='$r[1]' value='$r[0]'> $r[0] </option>";
10
}
11
?>
12
</select>
13
And I’ve tried various codes from here, but I’m still confused.
And this textbox code to display “value_seri”
JavaScript
1
9
1
<input type="text" name="value_seri" id="value_seri" value="" disabled><br></td>
2
<script>
3
function myFunction()
4
{
5
var value_seri = $('#value').find(':selected').data('nm_seri');
6
$('#value').val(value_seri);
7
}
8
</script>
9
Advertisement
Answer
In your current js code there is no value
it should be nm_seri
.Then , you are getting data attribute using data('nm_seri')
it should be data('value')
and show this value inside input box using $('#value_seri').val(value_seri);
.Also ,your function name should match with onchange="myfunction()"
so change that as well.
Demo Code :
JavaScript
1
4
1
function myfunction() {
2
var value_seri = $('#nm_seri').find(':selected').data('value');
3
$('#value_seri').val(value_seri);
4
}
JavaScript
1
9
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<select name="nm_seri" id="nm_seri" onchange="myfunction()" required>
3
<option disabled selected>-Pilih Seri-</option>
4
<option data-value='1' value='soemthing'> soemthing</option>
5
<option data-value='2' value='soemthing2'> soemthing2</option>
6
<option data-value='3' value='soemthin3g'> soemthing3</option>
7
</select>
8
9
<input type="text" name="value_seri" id="value_seri" value="" disabled><br>