提问者:小点点

在选项值[closed]中插入数组的第一个元素


我是一个初学者,我有一个脚本:

var Name = [
['ABCD1234', '555123456'],
['EFGH5678', '111234111'],
['GHIJ9101', '222345222']
];

$(Name).ready( function() {
$(Name).each( function(index, item) {
    var option = ('<option value="'+item+'"></option>');
    $('#GZB').append(option);
}); 

我想在Datalist ID中的选项值中添加数组的第一个元素,还想根据数组的第二个元素更改第二个输入框值的值。

表示如果选择“EFGH5678”,则第二个输入框值应为111234111。

应答编辑:-

 const options = [
    ['DL01GB2355', '555123456'],
    ['HR38K1350', '111234111'],
    ['HR38M4985', '222345222']
    ];
// Its is showing both the Option but selecting only one may be because it's an input ID not a Select ID
jQuery( function($){
  const HTMLOptions = options.reduce((html, item) => (html += `<option value="${item[0]}">${item[1]}</option>`, html), "");

$('#KASHIPUR')
.append(HTMLOptions)
//not working
.on('change', function() {
  $("label:contains('Driver Mobile No')").parent().next().find('input').val(this.value);
});

});


共1个答案

匿名用户

null

const options = [
  ["ABCD1234", "555123456"],
  ["EFGH5678", "111234111"],
  ["GHIJ9101", "222345222"]
];

jQuery( function($) { // DOM ready and $ alias in scope

  // Create a HTMLString using Array.prototype.reduce()
  const HTMLOptions = options.reduce((html, item) => {
     html += `<option value="${item[1]}">${item[0]}</option>`;
     return html;
  }, "");
  
  // Append the generated Options and assign a change listener
  $("#GZB")
    .append(HTMLOptions)
    .on("change", function() {
      $("#GZB_selected").val(this.value);
    })
    .trigger("change"); // Initialize!

});
<select id="GZB" name="GZB"></select>
<input id="GZB_selected" name="GZB_selected" type="text">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>