0

我正在尝试将文本框的值(id = msg)传递给 js,但输出始终是 foreach 循环上的第一个文本框值。请帮我。这是代码。

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>&nbsp;<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; ?>&nbsp;<font class="icon-comment"></font>&nbsp;<font class="orange" >From:</font> <?php echo $agnt->agent_shortname;?> | <font class="icon-envelope-alt"></font>&nbsp;<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; ?>
4

2 回答 2

1

您将外部循环的值放入文本框中。

据我所知,您应该将内部循环的值放在文本框中。

<input type="text" id="msg" value="<?php echo $msg->message_id;?>" />

你的意思是$agnt代替$msg吗?

于 2013-10-01T06:45:16.747 回答
0

我已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>&nbsp;<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; ?>&nbsp;<font class="icon-comment"></font>&nbsp;<font class="orange" >From:</font> <?php echo $agnt->agent_shortname;?> | <font class="icon-envelope-alt"></font>&nbsp;<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()">
于 2013-10-01T11:02:54.607 回答