选择元素$(this).find()不起作用

时间:2018-11-28 09:09:46

标签: javascript jquery select jquery-select2

我正在尝试从2018-11-28 08:52:48.881 UTC [fsblkstorage] newBlockfileMgr -> INFO 004 Getting block information from block storage 2018-11-28 08:52:48.920 UTC [orderer/commmon/multichannel] checkResourcesOrPanic -> CRIT 005 [channel byfn-sys-channel] config requires unsupported channel capabilities: Channel capability V1_3 is required but not supported: Channel capability V1_3 is required but not supported panic: [channel byfn-sys-channel] config requires unsupported channel capabilities: Channel capability V1_3 is required but not supported: Channel capability V1_3 is required but not supported 元素中获取选定的选项值。

select

尝试访问<form method="post" action="training/save" enctype="multipart/form-data" id="trainingForm"> <select name="trainees[]" id="trainees" class="form-control" required multiple="multiple"> <option value="1">1</option> </select> <button type="submit">Submit</button> </form> 值时得到undefined

select

我可以通过其他方式(通过ID)获取值:

$('#trainingForm').submit( function (){
  console.log($(this).find('select[name="trainees"]').val());
});

注意:正在使用$('#trainees').val();

但是我想以以前的方式获取值。

2 个答案:

答案 0 :(得分:2)

[]也是元素 name 属性的一部分。您必须将其包括在选择器中:

$(document).ready(function() {
    $('#trainees').select2();
});

$('#trainingForm').submit( function (){
  console.log($(this).find('select[name="trainees[]"]').val());
  return false;
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<form method="post" action="training/save" enctype="multipart/form-data" id="trainingForm">
    <select name="trainees[]" id="trainees" class="form-control" required multiple="multiple">
        <option value="1">1</option> 
        <option value="2">2</option>
    </select>
<button type="submit">Submit</button>
</form>

答案 1 :(得分:1)

只需更改您的

$('#trainingForm').submit( function ()
{
  console.log($(this).find('select[name="trainees"]').val());
});

$('#trainingForm').submit( function ()
{
  console.log($(this).find('select[name="trainees[]"]').val());
});

您需要提供与html中相同的名称。