我有一个选择元素,我需要检索所选选项的值,然后将数组的索引设置为该值。我需要在页面加载时以及每当选择更新时发生这种情况。
它看起来像:
{{ Form::select('marketplace_id', $donation_options, '', array('data-smart-select', 'required', 'id' => 'marketplace_id')) }}
<span id="market_hint" class="help-block">{{ $marketplaces[0]['example'] }}</span>
选择的 ID 是marketplace_id
数组是 $marketplaces,它是一个多维数组,第二个值始终是 ['example'],但第一个值是 select 的值,它始终是数字,例如 0,1,2,3等
通过当前的javascript可以检索select的值:
$( "#marketplace_id" ).val();
但我不知道如何继续更新 market_hint span 标记内的数组。有没有简单的 jQuery 方法?
最佳答案
如果你想在 php 渲染页面时将整个数组放入 javascript 中
?>
<script>
$(function(){
var myData = <?php echo json_encode( $marketplaces ); ?>
$("#marketplace_id").change(function(){
var value = $(this).val();
$("#market_hint").html(myData[value]["example"]);
});
//do a call here to do an initial setting of the span
$("#marketplace_id").change();
});
</script>
否则,您将必须对脚本执行 ajax 请求来为您提供数据
$(function(){
$("#marketplace_id").change(function(){
var value = $(this).val();
$.get("someScript.php?theIndex="+value)
.done(function(response){
$("#market_hint").innerHTML = response;
});
});
});
someScript.php
<?php
$index = isset($_GET["theIndex"]) ? intval($_GET["theIndex"]) : 0;
//do some processing to get the needed data
//...
echo $data;
die;
当然要定制它以适应你的 Laravel 框架,只是使用普通的 php,因为我不太了解 Laravel
关于javascript - 通过 JS 获取 Select 选项值并设置数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24708688/