Skip to content


jQuery กับ Select Box

jQuery เองมี function ต่าง ๆ รวมถึง Selector มากมายที่ทำให้เราสามารถจัดการกับ select box (หรือ combo box) ได้ง่ายขึ้น เราจะลองมาดูตัวอย่างการนำไปใช้ที่พบได้่บ่อยของ jQuery กับ select box กัน

function get_selected(path)
{
    return $(path + " option:selected");
}

function remove_selected(path)
{
    $(path + " option:selected").remove();
}

function append_item(path, value, text)
{
    $(path).append("<option value='" + value + "'>" + text + "</option>");
}

function select_first(path)
{
    $(path + " option:first-child").attr("selected","selected");
}

function select_last(path)
{
    $(path + " option:last-child").attr("selected","selected");
}

function remove_all(path)
{
    $(path).empty();
}

function select_by_value(path, value)
{
    $(path + " option[value=" + value + "]").attr("selected","selected");
}

function remove_by_value(path, value)
{
    $(path + " option[value=" + value + "]").remove();
}

Code ของตัวอย่างด้านบน จะใช้สำหรับการทำงานที่พบได้บ่อย ไม่ว่าจะเป็นการเพิ่ม element OPTION ลงใน select หรือการกำหนดค่า select box ให้เลือกไปที่ option ใด ๆ

ตัวอย่างการนำไปใช้ดูได้ที่ LIVE DEMO ได้เลยครับ

Share

Posted in HTML, JavaScript, jQuery.

Tagged with , , , .


One Response

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. pretty boy says

    เพิ่มเติมที่ http://www.texotela.co.uk/code/jquery/select/ ครับ

    jquery.selectboxes.js กับ parsesamples.js มีประโยชน์มาก



Some HTML is OK

or, reply to this post via trackback.

*