Advertisement
iarmin

jquery + html select

Nov 10th, 2011
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // jquery + <SELECT> methods
  2.  
  3. // Add options to the end of a select
  4. $("#myselect").append("<option value='1'>Apples</option>");
  5. $("#myselect").append("<option value='2'>After Apples</option>");
  6.  
  7. // Add options to the start of a select
  8. $("#myselect").prepend("<option value='0'>Before Apples</option>");
  9.  
  10. // Replace all the options with new options
  11. $("#myselect").html("<option value='1'>Some oranges</option><option value='2'>More Oranges</option><option value='3'>Even more oranges</option>");
  12.  
  13. // Replace items at a certain index
  14. $("#myselect option:eq(1)").replaceWith("<option value='2'>Some apples</option>");
  15. $("#myselect option:eq(2)").replaceWith("<option value='3'>Some bananas</option>");
  16.  
  17. // Set the element at index 2 to be selected
  18. $("#myselect option:eq(2)").attr("selected", "selected");
  19.  
  20. // Set the selected element by text
  21. $("#myselect").val("Some oranges").attr("selected", "selected");
  22.  
  23. // Set the selected element by value
  24. $("#myselect").val("2");
  25.  
  26. // Remove an item at a particular index
  27. $("#myselect option:eq(0)").remove();
  28.  
  29. // Remove first item
  30. $("#myselect option:first").remove();
  31.  
  32. // Remove last item
  33. $("#myselect option:last").remove();
  34.  
  35. // Get the text of the selected item
  36. alert($("#myselect option:selected").text());
  37.  
  38. // Get the value of the selected item
  39. alert($("#myselect option:selected").val());
  40.  
  41. // Get the index of the selected item
  42. alert($("#myselect option").index($("#myselect option:selected")));
  43.  
  44. // Alternative way to get the selected item
  45. alert($("#myselect option:selected").prevAll().size());
  46.  
  47. // Insert an item in after a particular position
  48. $("#myselect option:eq(0)").after("<option value='4'>Some pears</option>");
  49.  
  50. // Insert an item in before a particular position
  51. $("#myselect option:eq(3)").before("<option value='5'>Some apricots</option>");
  52.  
  53. // Getting values when item is selected
  54. $("#myselect").change(function() {
  55. alert($(this).val());
  56. alert($(this).children("option:selected").text());
  57. });
  58.  
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement