I am working on a dropdown list of countries and I have two questions about the code below:
-
How do I pass the value of the getSelectedValue() function into a hidden html field, so that I can post it to PHP’s $_POST array?
-
When I create two or more instances of the dropdown list (shipping and billing addresses) the value of one changes both values, when I echo out <span id=“country”>. What do I need to do to separate them, so that each getSelectedValue() is separate? I know I can only have one id=country per page, so how do I have multiple values that remain separate?
$(".dropdown dd ul a").click(function() {
var dl = $(this).closest("dl");
var dropID = dl.attr("id");
var text = $(this).html();
var source = dl.prev();
$("#" + dropID + " dt a").html(text);
$("#" + dropID + " dd ul").hide();
$("#country").html(getSelectedValue(dropID));
});
function getSelectedValue(dropID) {
return $("#" + dropID).find("dt a span.value").html();
}
Here’s the full script example I am using:
$(document).ready(function() {
createDropDown();
$(".dropdown dt a").click(function(event) {
event.preventDefault();
var dropID = $(this).closest("dl").attr("id");
$("#" + dropID).find("ul").toggle();
});
$(document).bind('click', function(e) {
var $clicked = $(e.target);
if (! $clicked.parents().hasClass("dropdown"))
$(".dropdown dd ul").hide();
});
$(".dropdown dd ul a").click(function() {
var dl = $(this).closest("dl");
var dropID = dl.attr("id");
var text = $(this).html();
var source = dl.prev();
$("#" + dropID + " dt a").html(text);
$("#" + dropID + " dd ul").hide();
$("#country").html(getSelectedValue(dropID));
});
function getSelectedValue(dropID) {
return $("#" + dropID).find("dt a span.value").html();
}
});
function createDropDown() {
var selects = $("select.dropdown_value");
var idCounter = 1;
selects.each(function() {
var dropID = "dropdown_" + idCounter;
var source = $(this);
var selected = source.find("option[selected]");
var options = $("option", source);
source.after('<dl id="' + dropID + '" class="dropdown"></dl>');
$("#" + dropID).append('<dt><a href="#">' + selected.text() + '<span class="value">' + selected.val() + '</span></a></dt>');
$("#" + dropID).append('<dd><ul></ul></dd>');
options.each(function() {
$("#" + dropID + " dd ul").append('<li><a href="#">' + $(this).text() + '<span class="value">' + $(this).val() + '</span></a></li>');
});
idCounter++;
});
}