我坚持下面的代码,它基本上从表单列表中获取数据并将帖子保存到我的数据库中。它仅适用于第一种形式,这是因为我设置了
var text = $("#msg1").val();
var resultid = $("#resultid1").val();
据我所知,仅阅读一个id字段。我的问题是如何修改此代码以正确读取所有三种形式,而不仅仅是第一种形式?
$(document).ready(function() {
$("[id^=submit]").click(function() {
var text = $("#msg1").val();
var resultid = $("#resultid1").val();
if (text == '') {
alert("The message field is empty");
} else
alert('posted: ' + text);
});
});
Form 1
<form id='replyform1'>
<textarea id='msg1'></textarea>
<input type='hidden' name='resultid1' id='resultid1' value='1234' />
<input type="button" id="submit1" value="Post" class='MenuButton' />
</form>
Form 2
<form id='replyform2'>
<textarea id='msg2'></textarea>
<input type='hidden' name='resultid2' id='resultid2' value='12345' />
<input type="button" id="submit2" value="Post" class='MenuButton' />
</form>
Form 3
<form id='replyform3'>
<textarea id='msg3'></textarea>
<input type='hidden' name='resultid3' id='resultid3' value='123456' />
<input type="button" id="submit3" value="Post" class='MenuButton' />
</form>
答案 0 :(得分:0)
您可以使用$(this)引用被单击的按钮元素,然后使用同级元素来查找所需的相对于该按钮的元素。
$("[id^=submit]").click(function() {
var text = $(this).siblings('textarea').first().val();
var resultid = $(this).siblings('.result').first().val();
if (text == '') {
alert("The message field is empty");
} else {
alert('posted: ' + text + ", resid: " + resultid);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Form 1
<form id='replyform1'>
<textarea id='msg1'></textarea>
<input type='hidden' name='resultid1' id='resultid1' value='1234' class="result" />
<input type="button" id="submit1" value="Post" class='MenuButton' />
</form>
Form 2
<form id='replyform2'>
<textarea id='msg2'></textarea>
<input type='hidden' name='resultid2' id='resultid2' value='12345' class="result"/>
<input type="button" id="submit2" value="Post" class='MenuButton' />
</form>
Form 3
<form id='replyform3'>
<textarea id='msg3'></textarea>
<input type='hidden' name='resultid3' id='resultid3' value='123456' class="result"/>
<input type="button" id="submit3" value="Post" class='MenuButton' />
</form>