Как автоматически выбрать выпадающий - PullRequest
1 голос
/ 01 июля 2019

У меня есть HTML-таблица, внутри которой у меня есть несколько полей ввода, поэтому, когда я выбираю любой параметр из dropdown, я заполняю одну строку таблицы внутри этой строки itemname как поле ввода, равное autocomplete.

Итак, что я делаю, так это то, что у меня есть строка типа A BR SB EX~333, где 333 - код элемента, а other - имя, поэтому, когда я набираю 333, этот элемент заполняется.Затем, нажав клавишу ввода, я фокусируюсь и выполняю некоторые вычисления.

Что я пытаюсь сделать

  • Когда я набираю, например, 333 при автозаполненииполе и только один вариант есть, я хочу заполнить это в моем inputfield.Я не хочу, чтобы пользователь выбирал эту опцию вручную, просто введите, если она соответствует одному name, а затем, нажав Enter, заполните это поле ввода.

Мой код

var tableData = {
  "ALMOND CHBAR~2402": {
    "itemName": "ALMOND CHBAR",
    "itemCode": "2402",
    "costPrice": 20.0,
    "gstPercentage": 14.5,
    "mrp": 30.0
  },
  "A BR SB EX~333": {
    "itemName": "A BR SB EX",
    "itemCode": "333",
    "costPrice": 1.0,
    "gstPercentage": 0.0,
    "mrp": 1.0
  }
}


var autoCompleteData = Object.keys(tableData);

function rowappend(tbody) {

  const markup =
    `<tr>
									  <td>
									    <input type="text" class="form-control commanChange" id="itemNametd" name="itemNametd">
									  </td>
									  <td><input type="text" name="itemCodetd" id="itemCodetd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="mrptd" id="mrptd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="purRatetd" id="purRatetd" class="form-control commantd"></td>
									  <td>
									    <input type="tel" id="unitQtytd"class="form-control commanChange" name="unitQtytd">
									  </td>
						               			 
									  <td>
									    <input type="tel" id="discPercentagetd"class="form-control commanChange" name="discPercentagetd" >
									  </td>
									  <td><input type="text" name="discAmttd" id="discAmttd" class="form-control commantd" readonly="readonly"></td> 
									  <td><input type="text" name="gstPercentagetd" id="gstPercentagetd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="gstAmttd" id="gstAmttd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="totalAmttd" id="totalAmttd" class="form-control commantd" readonly="readonly"></td>
									  <td style="background-color: white;border: 1px white"><i class="fas fa-times fa-2x remove-btn"></i></td>
									  
									</tr>`

  $(tbody).append(markup);
  setTimeout(() => $("[name=itemNametd]", tbody).last().focus(), 100);

  $("[name=itemNametd]", tbody).last().autocomplete({
    source: autoCompleteData

  });




}
rowappend($('tbody', '#tableInvoice'))

function getValues(row) {

  const search = ($('[name=itemNametd]', row).val()).toString()
  const value = tableData[search];
  CostPrice = value.costPrice;

  if (value) {
    $(row).find("[name=itemCodetd]").val(value.itemCode);
    $(row).find("[name=mrptd]").val(value.mrp);
    $(row).find("[name=purRatetd]").val(CostPrice);

    $(row).find("[name=gstPercentagetd]").val(value.gstPercentage);
  }

}
document.addEventListener("keydown", function(e) {
  const row = e.target.parentElement.parentElement
  if (event.target.matches('[name=itemNametd]')) {

    var keycode = e.keyCode || event.e;
    if (keycode == '13') {

      getValues(e.target.parentElement.parentElement)
      $("[name=purRatetd]").focus();

    }
  }

});
$(document).on('focusout', (e) => {

  const row = e.target.parentElement.parentElement
  if (e.target.matches("[name=itemNametd]")) {


    getValues(e.target.parentElement.parentElement)
    $("[name=purRatetd]").focus();

  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

<div class="row tableInvoice" id="commonDvScroll">
  <table class="table table-bordered" id="tableInvoice">
    <thead>
      <tr>
        <th id="itemNameth" class="commanth">Item Name</th>
        <th id="itemCodeth" class="commanth">Item Code</th>
        <th id="unitQtyth" class="commanth">Unit Qty</th>
        <th id="purRateth" class="commanth">Pur.Rate</th>
        <th id="discPercentageth" class="commanth">Disc%</th>
        <th id="discAmtth" class="commanth">Disc Amt</th>
        <th id="gstPercentageth" class="commanth">Gst%</th>
        <th id="gstAmtth" class="commanth">Gst Amt</th>
        <th id="totalAmtth" class="commanth">Total Amount</th>
      </tr>
    </thead>
    <tbody>

    </tbody>

  </table>

</div>

please check out this image for better understanding

Когда я печатаю, и в качестве опции остается только один элемент, я хочу, чтобы это пришловнутри поля ввода, чтобы пользователь не выбирал его вручную.

Если есть какой-либо другой способ сделать это автозаполнение, я открыт, чтобы использовать это, я просто хочу, чтобы во время ввода я получилполе ввода заполнено, поскольку я не хочу выбирать его вручную.

Ответы [ 2 ]

1 голос
/ 01 июля 2019

Здесь вы должны использовать response обратный вызов для этого

var tableData = {
  "ALMOND CHBAR~2402": {
    "itemName": "ALMOND CHBAR",
    "itemCode": "2402",
    "costPrice": 20.0,
    "gstPercentage": 14.5,
    "mrp": 30.0
  },
  "A BR SB EX~333": {
    "itemName": "A BR SB EX",
    "itemCode": "333",
    "costPrice": 1.0,
    "gstPercentage": 0.0,
    "mrp": 1.0
  }
}


var autoCompleteData = Object.keys(tableData);

function rowappend(tbody) {

  const markup =
    `<tr>
									  <td>
									    <input type="text" class="form-control commanChange" id="itemNametd" name="itemNametd">
									  </td>
									  <td><input type="text" name="itemCodetd" id="itemCodetd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="mrptd" id="mrptd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="purRatetd" id="purRatetd" class="form-control commantd"></td>
									  <td>
									    <input type="tel" id="unitQtytd"class="form-control commanChange" name="unitQtytd">
									  </td>
						               			 
									  <td>
									    <input type="tel" id="discPercentagetd"class="form-control commanChange" name="discPercentagetd" >
									  </td>
									  <td><input type="text" name="discAmttd" id="discAmttd" class="form-control commantd" readonly="readonly"></td> 
									  <td><input type="text" name="gstPercentagetd" id="gstPercentagetd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="gstAmttd" id="gstAmttd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="totalAmttd" id="totalAmttd" class="form-control commantd" readonly="readonly"></td>
									  <td style="background-color: white;border: 1px white"><i class="fas fa-times fa-2x remove-btn"></i></td>
									  
									</tr>`

  $(tbody).append(markup);
  setTimeout(() => $("[name=itemNametd]", tbody).last().focus(), 100);

  $("[name=itemNametd]", tbody).last().autocomplete({
    source: autoCompleteData,
    response: (e, ui)=>{
      if(ui.content.length === 1){
        $(e.target).val(ui.content[0].label);
        $(e.target).autocomplete( "close" );
      }
    }
  });




}
rowappend($('tbody', '#tableInvoice'))

function getValues(row) {

  const search = ($('[name=itemNametd]', row).val()).toString()
  const value = tableData[search];
  CostPrice = value.costPrice;

  if (value) {
    $(row).find("[name=itemCodetd]").val(value.itemCode);
    $(row).find("[name=mrptd]").val(value.mrp);
    $(row).find("[name=purRatetd]").val(CostPrice);

    $(row).find("[name=gstPercentagetd]").val(value.gstPercentage);
  }

}
document.addEventListener("keydown", function(e) {
  const row = e.target.parentElement.parentElement
  if (event.target.matches('[name=itemNametd]')) {

    var keycode = e.keyCode || event.e;
    if (keycode == '13') {

      getValues(e.target.parentElement.parentElement)
      $("[name=purRatetd]").focus();

    }
  }

});
$(document).on('focusout', (e) => {

  const row = e.target.parentElement.parentElement
  if (e.target.matches("[name=itemNametd]")) {


    getValues(e.target.parentElement.parentElement)
    $("[name=purRatetd]").focus();

  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

<div class="row tableInvoice" id="commonDvScroll">
  <table class="table table-bordered" id="tableInvoice">
    <thead>
      <tr>
        <th id="itemNameth" class="commanth">Item Name</th>
        <th id="itemCodeth" class="commanth">Item Code</th>
        <th id="unitQtyth" class="commanth">Unit Qty</th>
        <th id="purRateth" class="commanth">Pur.Rate</th>
        <th id="discPercentageth" class="commanth">Disc%</th>
        <th id="discAmtth" class="commanth">Disc Amt</th>
        <th id="gstPercentageth" class="commanth">Gst%</th>
        <th id="gstAmtth" class="commanth">Gst Amt</th>
        <th id="totalAmtth" class="commanth">Total Amount</th>
      </tr>
    </thead>
    <tbody>

    </tbody>

  </table>

</div>
0 голосов
/ 01 июля 2019

Я нашел что-то в j query плагине автозаполнения, т.е.

autoSelectFirst: true,
 autoFocus: true

это делает то, что я пытаюсь достичь

var tableData = {
  "ALMOND CHBAR~2402": {
    "itemName": "ALMOND CHBAR",
    "itemCode": "2402",
    "costPrice": 20.0,
    "gstPercentage": 14.5,
    "mrp": 30.0
  },
  "A BR SB EX~333": {
    "itemName": "A BR SB EX",
    "itemCode": "333",
    "costPrice": 1.0,
    "gstPercentage": 0.0,
    "mrp": 1.0
  }
}


var autoCompleteData = Object.keys(tableData);

function rowappend(tbody) {

  const markup =
    `<tr>
									  <td>
									    <input type="text" class="form-control commanChange" id="itemNametd" name="itemNametd">
									  </td>
									  <td><input type="text" name="itemCodetd" id="itemCodetd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="mrptd" id="mrptd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="purRatetd" id="purRatetd" class="form-control commantd"></td>
									  <td>
									    <input type="tel" id="unitQtytd"class="form-control commanChange" name="unitQtytd">
									  </td>
						               			 
									  <td>
									    <input type="tel" id="discPercentagetd"class="form-control commanChange" name="discPercentagetd" >
									  </td>
									  <td><input type="text" name="discAmttd" id="discAmttd" class="form-control commantd" readonly="readonly"></td> 
									  <td><input type="text" name="gstPercentagetd" id="gstPercentagetd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="gstAmttd" id="gstAmttd" class="form-control commantd" readonly="readonly"></td>
									  <td><input type="text" name="totalAmttd" id="totalAmttd" class="form-control commantd" readonly="readonly"></td>
									  <td style="background-color: white;border: 1px white"><i class="fas fa-times fa-2x remove-btn"></i></td>
									  
									</tr>`

  $(tbody).append(markup);
  setTimeout(() => $("[name=itemNametd]", tbody).last().focus(), 100);

  $("[name=itemNametd]", tbody).last().autocomplete({
    source: autoCompleteData,
    autoSelectFirst: true,
    autoFocus: true

  });




}
rowappend($('tbody', '#tableInvoice'))

function getValues(row) {

  const search = ($('[name=itemNametd]', row).val()).toString()
  const value = tableData[search];
  CostPrice = value.costPrice;

  if (value) {
    $(row).find("[name=itemCodetd]").val(value.itemCode);
    $(row).find("[name=mrptd]").val(value.mrp);
    $(row).find("[name=purRatetd]").val(CostPrice);

    $(row).find("[name=gstPercentagetd]").val(value.gstPercentage);
  }

}
document.addEventListener("keydown", function(e) {
  const row = e.target.parentElement.parentElement
  if (event.target.matches('[name=itemNametd]')) {

    var keycode = e.keyCode || event.e;
    if (keycode == '13') {

      getValues(e.target.parentElement.parentElement)
      $("[name=purRatetd]").focus();

    }
  }

});
$(document).on('focusout', (e) => {

  const row = e.target.parentElement.parentElement
  if (e.target.matches("[name=itemNametd]")) {


    getValues(e.target.parentElement.parentElement)
    $("[name=purRatetd]").focus();

  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

<div class="row tableInvoice" id="commonDvScroll">
  <table class="table table-bordered" id="tableInvoice">
    <thead>
      <tr>
        <th id="itemNameth" class="commanth">Item Name</th>
        <th id="itemCodeth" class="commanth">Item Code</th>
        <th id="unitQtyth" class="commanth">Unit Qty</th>
        <th id="purRateth" class="commanth">Pur.Rate</th>
        <th id="discPercentageth" class="commanth">Disc%</th>
        <th id="discAmtth" class="commanth">Disc Amt</th>
        <th id="gstPercentageth" class="commanth">Gst%</th>
        <th id="gstAmtth" class="commanth">Gst Amt</th>
        <th id="totalAmtth" class="commanth">Total Amount</th>
      </tr>
    </thead>
    <tbody>

    </tbody>

  </table>

</div>

я отправляю этот ответ, но я готов использовать и другие подходы

...