aHunter
aHunter

Reputation: 3530

How to have a select box in form populate a input box below using php

I have a requirement for adding values selected in a select box to a input box with the same form and am not sure how to best go about this. The select box contains user email addresses and the input box needs to contain multiple email addresses. The idea is that when you select a email address from the select box it is then added to the input either automatically, or by clicking the add button which reload the page in PHP adding to a variable that is the value of the input box. I have tried to do this by having a form within a form but that does not work is there a better way of doing this?

Many thanks.

Upvotes: 0

Views: 571

Answers (2)

DanRedux
DanRedux

Reputation: 9359

Well, in the select's onchange event, set the inputs value to all of the selected options concatenated together.

Here's some psuedo-code:

on select changed {
  str= ''
  for every element
    if checked
      str = str + value + ','
  set input's value to the variable str

Again in jQuery:

$('select').onchange(function(){
  str='';
  $('option:selected').each(function(){
    str+=this.value+','; });
  $('input:text').value(str); });

Edit: Here's what you wanted, without multi-select.

$('select').onchange(function(){
  $('option:selected').each(function(){
    $('input:text').val($('input:text').val()+$(this).val()+',');})
  .removeAttr('selected'); });

Upvotes: 1

Kaushtuv
Kaushtuv

Reputation: 489

You can try this:

Write this code in the top of the page before DOCTYPE.

    <?php
if(isset($_POST['add']))
{
    $previous_email = $_POST['txt_email'];
    $emails = $_POST['select_email'].",".$previous_email;
}
else
{
    $emails = '';   
}
?>

The javascript: you can put it in the head section of your html document

<script>
function add_email()
{
    document.getElementById('txt_email').value = document.getElementById('select_email').value +','+ document.getElementById('txt_email').value;    
}
</script>

And finally the html:

    <body>

    <form method="post" action="" name="myform">
    <select name="select_email" id="select_email" onchange="add_email();">
    <option value="[email protected]">[email protected]</option>
    <option value="[email protected]">[email protected]</option>
    <option value="[email protected]">[email protected]</option>
    </select>

    <textarea name="txt_email" id="txt_email"><?=$emails;?></textarea>
    <input type="submit" value="add" name="add"/>
    </form>

</body>

Hope it helps

Upvotes: 0

Related Questions