charlie_cat charlie_cat - 5 months ago 9
HTML Question

difficulty with form action and unique ids

I have this code in a foreach that lists uniquecode links:

<a id="<?php echo $id_to ?>" href="<?php echo ADDRESS; ?>messageSent.php?id=<?php echo $id_to ?>" class="charcoal_link" style="line-height: 20px;" onclick="showMessageArea(this); return false;" >
<?php echo $uniqueCode1?><span class="pink_text"><?php echo $uniqueCode2?></span><?php echo $uniqueCode3?>
</a>
<form id="message_area" style="display:none" method="post" action="<?php echo ADDRESS; ?>messageSent.php?id=<?php echo $id_to ?>">
<textarea name="message" rows="10" cols="20"></textarea>
<input name="Submit" type="submit" value="Send"></input>
</form>


this is what I get when I view the page source:

<a href="http://www-rainbowcode-mobi/messageSent.php?id=36" class="charcoal_link" style="line-height: 20px;" onclick="showMessageArea(this); return false;" >
KUZELJA<span class="pink_text">000</span>RC
</a>
<form id="message_area" style="display:none" method="post" action="http://www-rainbowcode-mobi/messageSent.php?id=36">
<textarea name="message" rows="10" cols="20"></textarea>
<input name="Submit" type="submit" value="Send"></input>
</form>
<a href="http://www-rainbowcode-mobi/messageSent.php?id=38" class="charcoal_link" style="line-height: 20px;" onclick="showMessageArea(this); return false;" >
ALANZIM<span class="pink_text">000</span>RC
</a>
<form id="message_area" style="display:none" method="post" action="http://www-rainbowcode-mobi/messageSent.php?id=38">
<textarea name="message" rows="10" cols="20"></textarea>
<input name="Submit" type="submit" value="Send"></input>
</form>


the problem is when the action fires and page goes to messageSent and I view page source again
$id_to
is NOT the id of the link I clicked on. It takes the first link's id regardless of which link I click on?

here the messageSent page source (I clicked on link with id 38 NOT 36):
where I have a
print_r($_REQUEST)
and it gives:

Array
(
[id] => 36
[message] => bj,nbgj,
[Submit] => Send
)


.

function showMessageArea(link)
{
var message_area = document.getElementById('message_area');
message_area.parentNode.removeChild(message_area);
link.parentNode.insertBefore(message_area, link.nextSibling);
message_area.style.display="block";
}

Answer

The problem is indeed the non-unique ids.

Try appending $to_id to the form ids, so that they are unique (e.g. <form id="message_area_<?php echo $to_id; ?>" ...).

And then update showMessageArea function to do this:

var message_area = document.getElementById('message_area_'+this.id);

This way you will be operating on the desired form element.

As a refactoring suggestion, I would suggest using a single form instead and make id parameter to be <input type='hidden' name='id' id='message_id' value=''> and set it's value from the showMessageArea(...) like this:

document.getElementById('message_id').value = this.id;