1

I found this neat code online that does exactly what I need. The problem I'm having is that the variable is not passing the entire value.

<script type='text/javascript'>
    $(window).load(function() {
        $("#add_id").click(function() {
            var value = $("#entered_id").val();
            $("#list_id").append("<option value =" + value + " selected>" + value + "</option>");
        });
    });    
</script>




<select id='entered_id'>
    <option value='This is a test message'>test</option>";
</select>


<button id="add_id">Add</button>


<h2>Entered IDs</h2>
<form name="test" method="POST" action="test2.php">
    <select id="list_id" name="list_id" multiple="multiple"> </select>
    <input type="submit" />
</form>

On test2.php the variable $list_id comes in as "This" instead of "This is a test".

Can anyone steer me in the right direction?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Ronaldo
  • 111
  • 7

1 Answers1

5

You should put the string values arround quotes ' :

$("#list_id").append("<option value =" + value + " selected>" + value + "</option>");

Should be :

$("#list_id").append("<option value ='" + value + "' selected>" + value + "</option>");
_____________________________________^_____________^

In other words, the generated option html looked like <option value=This is a test>, making is, a, and test invalid/unknown attributes.

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • 1
    In other words, the generated option html looked like ` – Marc B Feb 29 '16 at 16:48
  • Thanks @MarcB for your intervention, can i update my answer using your explanation? – Zakaria Acharki Feb 29 '16 at 16:49
  • 1
    of course... you got the right answer, this just expands on WHY it's the right anwer. – Marc B Feb 29 '16 at 16:50
  • If the value happens to include a double-quote, he'll have the same problem again. He should add some code to [replace `"` with `"` inside the string.](http://stackoverflow.com/questions/3752769/how-to-escape-double-quotes-in-title-attribute) – Blazemonger Feb 29 '16 at 17:03