选择下拉列表时如何在其他文本字段中设置值?

时间:2018-03-19 03:49:26

标签: javascript php html ajax codeigniter

我遇到了一些问题,当选择下拉列表时,我想在另一个字段中设置值。

我试过这个html:

<select id="nik" name="nik" class="select-select2" style="width: 100%;" onchange="setData('<?php echo $data['nama_jabatan']; ?>','<?php echo $data['nilai_tunjangan_p']; ?>','<?php echo $data['nilai_tunjangan_j']; ?>')">

和这个js:

 function setData(nama_jabatan,nilai_tunjangan_p,nilai_tunjangan_j)
 {
    $('#nama_jabatan').val(nama_jabatan);
    $('#nilai_tunjangan_p').val(nilai_tunjangan_p);
    $('#nilai_tunjangan_j').val(nilai_tunjangan_j);
}

但是文本框val没有更新。

1 个答案:

答案 0 :(得分:0)

实现此目的的一种方法是在<option>上添加信息,而不是<select>标记。您可以使用jQuery data-

像:

<option value="volvo" data-nama_jabatan="nama_jabatan 1" data-nilai_tunjangan_p="nilai_tunjangan_p 1" data-nilai_tunjangan_j="nilai_tunjangan_j 1">Volvo</option>

这是一个片段&#34;

&#13;
&#13;
$(function(){

    //Add event listener to element with id nik
    $("#nik").change(function(){

         //Get the selected option
         var opt = $(this).find("option:selected")

         //Get the data information from the selected option
         var nama_jabatan = $(opt).data("nama_jabatan");
         var nilai_tunjangan_p = $(opt).data("nilai_tunjangan_p");
         var nilai_tunjangan_j = $(opt).data("nilai_tunjangan_j");
		
         //Update the textboxes
         $('#nama_jabatan').val( nama_jabatan );
         $('#nilai_tunjangan_p').val( nilai_tunjangan_p );
         $('#nilai_tunjangan_j').val( nilai_tunjangan_j );
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="nik" name="nik" class="select-select2" style="width: 100%;">
    <option value="volvo" data-nama_jabatan="" data-nilai_tunjangan_p="" data-nilai_tunjangan_j=""></option>
    <option value="volvo" data-nama_jabatan="nama_jabatan 1" data-nilai_tunjangan_p="nilai_tunjangan_p 1" data-nilai_tunjangan_j="nilai_tunjangan_j 1">Volvo</option>
    <option value="saab" data-nama_jabatan="nama_jabatan 2" data-nilai_tunjangan_p="nilai_tunjangan_p 2" data-nilai_tunjangan_j="nilai_tunjangan_j 2">Saab</option>
    <option value="mercedes" data-nama_jabatan="nama_jabatan 3" data-nilai_tunjangan_p="nilai_tunjangan_p 3" data-nilai_tunjangan_j="nilai_tunjangan_j 3">Mercedes</option>
    <option value="audi" data-nama_jabatan="nama_jabatan 4" data-nilai_tunjangan_p="nilai_tunjangan_p 4" data-nilai_tunjangan_j="nilai_tunjangan_j 4">Audi</option>
</select>

<br />
<br /><input type="text" id="nama_jabatan">
<br /><input type="text" id="nilai_tunjangan_p">
<br /><input type="text" id="nilai_tunjangan_j">
&#13;
&#13;
&#13;