[英]Fetch input value after Dropdown menu item selected
我有一張關於產品的表。 它具有id,productdmc,productcode列。 在此選擇菜單中,顯示productdmc 。 選擇一項后,將其標簽更改為相關行。 那就是我所需要的。 但我不知道解決方案。
產品代碼 。
<select class="form-control" name="productdmc" id="productdmc">
<option disabled selected>DMC</option>
@foreach ($product as $products)
<option value="{{ $products->productdmc }}">{{ $products->productdmc }}</option>
@endforeach
</select>
相關輸入
<input type="text" name="productcode" id="productcode">
這是js代碼。 我不知道這是工作。 這是我的實際問題。
<script type="text/javascript">
$(document).ready(function() {
$('select[name="productdmc"]').on('change', function() {
var tmp = $(this).val();
if(tmp) {
$.ajax({
url: '/products/create/'+tmp,
type: "GET",
dataType: "json",
success:function(data) {
$('productcode').empty();
$.each(data, function(key, value) {
$('productcode').innerHTML('<input value="'+ key +'">');
});
}
});
}else{
$('productcode').empty();
}
});
});
</script>
在我的控制器中:
$val = DB::table("products")->pluck("productdmc","productcode");
return json_encode($val);
我知道,我搞砸了。 但是代碼比這復雜得多。 我在這里(較短的版本)編寫此代碼。 不能復制粘貼。 我在這里停留了一段時間。 我找不到真正的解決方案是什么。 我願意接受所有解決方案。
對不起,我的英語不好。
innerHTML
是HTML元素的屬性,而不是jQuery表示的功能。
使用html(content)
代替,我認為它應該工作:
$('#productcode').html('<input value="'+ key +'">');
您的選擇器錯誤,您忘記了“#”。
var $productCode = $('#productcode');
同樣,當事件“更改”被觸發時,您需要獲取選定的選項。
var selectedValue = $element.find('option:selected').val();
的HTML
<select class="form-control" name="productdmc" id="productdmc">
<option disabled selected>DMC</option>
@foreach ($product as $products)
<option value="{{ $products->productdmc }}">{{ $products->productdmc }}</option>
@endforeach
</select>
<input type="text" name="productcode" id="productcode">
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$('body').on('change', 'select[name="productdmc"]', function(e) {
var $element = $(e.currentTarget); // $(this) is also fine.
// Get selected value
var selectedValue = $element.find('option:selected').val();
var $productCode = $('#productcode');
// No value selected
if (!selectedValue) {
$productCode.val('');
return;
}
$.ajax({
url: '/products/create/' + selectedValue,
type: 'GET',
dataType: 'json',
error: function() {
$productCode.val('');
},
success: function(res) {
$productCode.val('');
if (res.length < 1) return;
$productCode.val(res[0] || '');
// This will populate more than 1 field. So,
// I'm not sure about what you expect on the backend.
// If you want to populate more than 1,
// you should change the selector/field (do not use id in this case)
// $.each(res, function(key, value) {
// $productCode.val(key);
// });
}
})
});
});
</script>
的PHP
<?php
$products = DB::table('products')->get();
return response(
$products->pluck('productdmc', 'productcode')->toArray()
);
您可以在此處閱讀有關jQuery選擇器的更多信息: https : //api.jquery.com/category/selectors/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.