我手风琴里面有一个表格。当单击每个手风琴中的按钮时,它会检索同一手风琴的title
和query
内容。
https://jsfiddle.net/rkdrfj4y/3/这表明我正在尝试做什么。
问题是第一支手风琴总是返回未定义的form
input
值。所有其他后续手风琴都会返回预期值。我不明白这是怎么发生的,因为每个手风琴使用相同的js代码。
HTML
<form>
<div class="form-group">
<label for="exampleTextarea">Global Templates</label>
<div class="panel-group" id="accordion-global">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="title-anchor" data-toggle="collapse"
data-parent="#accordion-global" href="#collapse-global-0">
title</a>
</h4>
</div>
<div id="collapse-global-0" class="panel-collapse collapse">
<div class="panel-body">
<form class="query-form">
<div class="form-group">
<label for="template-title">Template Title</label>
<input type="text" class="form-control template-title" name="template-title" value="title">
</div>
<div class="form-group">
<label for="template-query">Template Query</label>
<textarea class="form-control template-query" name="template-query" onkeyup="textAreaAdjust(this)">query</textarea>
</div>
</form>
<input class="query-id" type="hidden" value="_id">
<button class="btn btn-info apply-template-btn">Save
</button>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="title-anchor" data-toggle="collapse"
data-parent="#accordion-global" href="#collapse-global-1">
title</a>
</h4>
</div>
<div id="collapse-global-1" class="panel-collapse collapse">
<div class="panel-body">
<form class="query-form">
<div class="form-group">
<label for="template-title">Template Title</label>
<input type="text" class="form-control template-title" name="template-title" value="title">
</div>
<div class="form-group">
<label for="template-query">Template Query</label>
<textarea class="form-control template-query" name="template-query" onkeyup="textAreaAdjust(this)">query</textarea>
</div>
</form>
<input class="query-id" type="hidden" value="_id">
<button class="btn btn-info apply-template-btn">Save
</button>
</div>
</div>
</div>
</div>
</div>
</form>
JS
$('.apply-template-btn').click(function (e) {
e.preventDefault();
let id = $(this).siblings('.query-id').val();
let title = $(this).siblings('.query-form').find('.template-title').val();
let query = $(this).siblings('.query-form').find('.template-query').val();
console.log([id,title,query])
alert(title) //undefined for first accordion but works for all other subsequent accordions
$.post('/api/database/query_template/update', {id,title,query}, function (data) {
console.log(data)
})
});
答案 0 :(得分:2)
更改以下现有行:
let title = $(this).siblings('.query-form').find('.template-title').val();
let query = $(this).siblings('.query-form').find('.template-query').val();
到
let title = $(this).parent().find(".template-title").val();
let query = $(this).parent().find(".template-query").val();