我想在一个文本区域中插入另一个表单域的值。有多个字段,每个字段以不同的形式放置,具有不同的提交按钮。只要单击该按钮,就应将该表单中的值插入文本区域。
字段是在数组中生成的。我为每个字段分配了相同的id
名称。这是为了使每个字段的值都属于该textarea。我的问题是,当我点击它的按钮时,只有第一个字段将其值插入textarea。其他字段不起作用。我怎么能解决这个问题?
以下是代码:
<script type="text/javascript">
window.onload = function() {
btn1 = document.getElementById("btnInsertText1");
myText1 = document.getElementById("myTextArea1");
text1 = document.getElementById("textToInsert1");
btn1.onclick = function(){
insertAtCursor(myText1, text1.value);
}
}
function insertAtCursor(myField, myValue) {
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
}
else {
myField.value += myValue;
}
}
</script>
<textarea id="myTextArea1" name="update" cols="85" rows="22">
Testing. Values from another field will be inserted here.
</textarea>
<?php
$ref = "
SELECT *
FROM reftext1_objective
WHERE projectid='$id'";
$refresult = mysql_query($ref);
while($row = mysql_fetch_array($refresult))
{?>
<form>
<input id="textToInsert1" type="text" value="<?php echo $row[$text];?>" readonly="true">
<input type="button" id="btnInsertText1" value="<<" />
</form><br><?php
}
答案 0 :(得分:1)
正如我在该问题的评论中所述,问题是由于PHP代码中循环中的重复元素ID。要解决此问题,请尝试以下方法:
<script type="text/javascript">
$(function() {
var textarea = document.getElementById("myTextArea1");
$(".button").click(function() {
var $parentForm = $(this).closest("form");
var text = $(".insert-text", $parentForm).val();
insertAtCursor(textarea, text);
});
});
function insertAtCursor(myField, myValue) {
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
}
else {
myField.value += myValue;
}
}
</script>
<textarea id="myTextArea1" name="update" cols="85" rows="22">
Testing. Values from another field will be inserted here.
</textarea>
<?php
$ref = "SELECT * FROM reftext1_objective WHERE projectid = '$id'";
$refresult = mysql_query($ref);
while ($row = mysql_fetch_array($refresult))
{ ?>
<form>
<input class="insert-text" type="text" value="<?php echo $row[$text];?>" readonly="true">
<input type="button" class="button" value="<<" />
</form><br>
<?php }
?>