У меня есть 2 входа в форме. В 1-м входе я загружаю datalist
через JSON
. Список json имеет 2 атрибута machine
и lot
.Как выбрать описание datalist
Что я хочу, когда пользователь выбирает машину, второй вход должен быть заполнен автоматически лотом. Например, если я выберем 1
, второй ввод будет заполнен lot1
.
Другой подход - выбрать элемент data-description
. Но ни я не знаю, как ..
var dataList = document.getElementById('lots');
var jsonOptions = [{
"machine": 1,
"lot": "lot1"
}, {
"machine": 2,
"lot": "lot2"
}];
// Loop over the JSON array.
jsonOptions.forEach(function(item) {
var option = document.createElement('option');
option.value = item.machine;
option.text = item.lot;
option.setAttribute('data-description', item.lot);
dataList.appendChild(option);
});
$(function() {
$('#machine').on('change keyup', function() {
var i = this.value;
$('#lot').val(i);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-md-5">
<input type="text" id="machine" list="lots" class="form-control" name="machine" />
<datalist id="lots"></datalist>
</div>
</div>
<br/>
<div class="form-group">
<div class="col-md-5">
<input type="text" id="lot" class="form-control" name="lot" />
</div>
</div>
Реальный код я использую для загрузки JSON это:
var dataList = document.getElementById('lots');
var input = document.getElementById('machine');
var request = new XMLHttpRequest();
request.onreadystatechange = function(response) {
if (request.readyState === 4) {
if (request.status === 200) {
// Parse the JSON
var jsonOptions = JSON.parse(request.responseText);
// Loop over the JSON array.
jsonOptions.forEach(function(item) {
var option = document.createElement('option');
option.value =item.machine;
option.text = item.lot;
option.setAttribute('data-description', item.lot);
dataList.appendChild(option);
});
// Update the placeholder text.
input.placeholder = "machine";
} else {
// An error occured :(
input.placeholder = "error:(";
}
}
};
// Update the placeholder text.
input.placeholder = "Loading options...";
// Set up and make the request.
request.open('GET', 'lots.json', true);
request.send();
Я получаю 'неперехваченным ReferenceError: jsonOptions не defined'. Я добавил в вопрос, как именно я загружаю JSON – yaylitzis
@yaylitzis. Вы попробовали мой фрагмент? Он работает отлично! –
@yaylitzis Переместите весь мой код в функцию 'request.onreadystatechange'. Тогда он будет работать –