tags:

views:

32

answers:

1

i'm trying to get jquery to add the value of a select box to both a hidden input field and a div to show in public view.

here's my code

<script type='text/javascript'>
$("#departments_submit").click(function(){

 added_departments = new Array();
 var depo = $("#depo_list").val();
 alert(jQuery.inArray(depo, added_departments))
     if(jQuery.inArray(depo, added_departments) != -1)
     {
      return false;
     }
     else
     {
      added_departments.push(depo);

     }
     $("#depo_added_list").append("<li>" + depo + "</li>");
     var current_value = $("#departments").val();
  if(current_value)
  {
   $("#departments").val(current_value + "," + depo);
  }
  else
  {
   $("#departments").val(depo);
  }
     return false;
    alert(added_departments)
});

</script>

problem i'm having, is when the user submits the select form, if the item has already been added it will still add it to the field and the div when its not supposed to.

any ideas?

+1  A: 

Try:

<script type='text/javascript'>
added_departments = new Array();

$("#departments_submit").click(function() {
        var depo = $("#depo_list").val();
        alert(jQuery.inArray(depo, added_departments))

        if (!jQuery.inArray(depo, added_departments)) {
               added_departments.push(depo);
               $("#depo_added_list").append("<li>" + depo + "</li>");
               var current_value = $("#departments").val();

               if (current_value) $("#departments").val(current_value + "," + depo);
               else $("#departments").val(depo);

               alert(added_departments)
        }
});
</script>

If that doesn't work then please post the HTML code and I'll have another look.

Sbm007
this isn't exactly what i was after as doing it this way reloads the page for some reason (the page is loaded in ajax first so reloading is not an option) however i noticed that you moved the added_departments outside of the function, and that made my version of the script work so thanks for taking the time out it really did help!
Neil Hickman
No problem, glad it worked. You were basically re-initializing the added_departments every time someone clicked submit, defying the point of having it in the first place :)
Sbm007
glad it worked out*
Sbm007