2008年9月17日 星期三

jQuery Tips


  • select


  • //Empty options
    $("#select1").empty();

    //Get Text
    $("select[name='select1'] option[selected]").text(); //1.3 +
    $("select[@name='select1'] option[@selected]").text(); //1.2.6 -
    $("#select1 :selected").text();
    $("#select1").text(); //This will get all the options

    //Get Value
    $("select[name='select1'] option[selected]").val(); //1.3 +
    $("select[name='@select1'] option[@selected]").val(); //1.2.6-
    $("#select1").val();
    $("#select1 :selected").val();

    //Set Value -> By value (If value is 0)
    $("#select1").attr("value","0");

    //Set Value -> By index -> the second element
    $("#select1")[0].selectedIndex = 1;

    //Count the options of select
    alert($("select[name='select1'] option").length); //1.3 +
    alert($("select[@name='select1'] option").length); //1.2.6 -


  • radio button


  • //Get Value
    $("input[name='radio1'][checked]").val(); //1.3 +
    $("input[name='@radio1'][@checked]").val(); //1.2.6 -

    //Set Value -> By value (If value is radio_0)
    $.each($("input[name='radio1']"),function(){ //1.2.6 - => @name
    if($(this).val() == "radio_0"){
    $(this).get(0).checked = true;
    }
    });

    //Set Value -> By index -> the second element
    $("input[name='radio1']").get(1).checked = true; //1.2.6 - => @name


  • checkbox


  • //select All
    $(":checkbox[name='checkbox_1']").attr("checked","checked"); //1.2.6 - => @name

    $.each($("input[name='checkbox_1']"),function(){ //1.2.6 - => @name
    $(this).attr("checked",true);
    });

    //unselect All
    $(":checkbox[name='checkbox_1']").attr("checked",false); //1.2.6 - => @name

    $.each($("input[name='checkbox_1']"),function(){ //1.2.6 - => @name
    $(this).attr("checked",false);
    });

沒有留言: