我试图将文本框的值(id = msg)传递给js,但输出始终是foreach循环上的第一个文本框值。请帮我。一直在网上搜索2小时。这是代码。
JS:
function sub() {
var name = document.getElementById('msg').value;
alert(name);
}
HTML:
<?php
foreach($messages->result() as $msg):
foreach($agentname->result() as $agnt):
if($msg->message_status == 1):
$message_status = "<font class='icon-exclamation-sign'></font> <font class='purple'>New message!</font>";
else:
$message_status = "";
endif;
?>
<div class="accordion-wrapper" style="margin-top:0">
<a id="message" onclick="return sub();" rel="msg<?php echo $msg->message_id;?>" id = "button_id" style="background-color:#C2E4CD" href="javascript:void(0)" class="accordion-title blue"><span><?php echo $message_status; ?> <font class="icon-comment"></font> <font class="orange" >From:</font> <?php echo $agnt->agent_shortname;?> | <font class="icon-envelope-alt"></font> <font class="orange">Subject:</font> <?php echo $msg->message_title;?></span></a>
<div class="accordion-content">
<input type="text" id="msg" value="<?php echo $msg->message_id;?>" />
<p><?php echo $msg->message;?></p>
</div>
</div>
<?php endforeach; ?>
<?php endforeach; ?>
答案 0 :(得分:1)
您将外循环的值放在文本框中。
据我所知,你应该将内循环的值放在文本框中。
<input type="text" id="msg" value="<?php echo $msg->message_id;?>" />
您的意思是$agnt
而不是$msg
吗?
答案 1 :(得分:0)
我已将{strong> name
属性添加到您的input
,并点击一个按钮,它将逐个显示输入的值,所以现在您可以试试这个代码
<强> JS:强>
function check() {
var inputs = document.getElementsByName('messages[]');
alert(inputs.length);
for (var x = 0; x < inputs.length; x++) {
inp_val = inputs[x].value;
alert(inp_val);
}
}
HTML:
<?php
foreach($messages->result() as $msg):
foreach($agentname->result() as $agnt):
if($msg->message_status == 1):
$message_status = "<font class='icon-exclamation-sign'></font> <font class='purple'>New message!</font>";
else:
$message_status = "";
endif;
?>
<div class="accordion-wrapper" style="margin-top:0">
<a id="message" onclick="return sub();" rel="msg<?php echo $msg->message_id;?>" id = "button_id" style="background-color:#C2E4CD" href="javascript:void(0)" class="accordion-title blue"><span><?php echo $message_status; ?> <font class="icon-comment"></font> <font class="orange" >From:</font> <?php echo $agnt->agent_shortname;?> | <font class="icon-envelope-alt"></font> <font class="orange">Subject:</font> <?php echo $msg->message_title;?></span></a>
<div class="accordion-content">
<input type="text" id="msg" name="messages[]" value="<?php echo $msg->message_id;?>" />
<p><?php echo $msg->message;?></p>
</div>
</div>
<?php endforeach; ?>
<?php endforeach; ?>
<input type="button" value="check" onclick="check()">