Checkbox shows hidden field - not working onload

后端 未结 3 1196
星月不相逢
星月不相逢 2021-01-28 03:01

I am using this probably ugly javascript to show a text box (in a li tag plus its label) if a checkbox is checked.

   $(\"#li-2-21\").css(\"display\",\"none\");
         


        
相关标签:
3条回答
  • 2021-01-28 03:15

    Just call the function immediately upon defining it's function. Example:

       $("#Languages-spoken-and-understood-8").click(function(){
        if ($("#Languages-spoken-and-understood-8").is(":checked"))
        {
            $("#li-2-21").show("fast");
        }
        else
        {     
            $("#li-2-21").hide("fast");
        }
      }).click();
    
    0 讨论(0)
  • 2021-01-28 03:22

    Most concisely:

    $(document).ready(function() {
       $("#Languages-spoken-and-understood-8").change(function() {
          $("#li-2-21")[$(this).is(":checked") ? 'show' : 'hide']("fast")
      }).change();
    });
    

    EDIT : switched from click to change event

    0 讨论(0)
  • 2021-01-28 03:27

    Extract your click function into a separate function (not inline) and run it on the load of the page:

    function ToggleCheckbox() {
        if ($("#Languages-spoken-and-understood-8").is(":checked"))
        {
            $("#li-2-21").show("fast");
        }
        else
        {     
            $("#li-2-21").hide("fast");
        }
    }
    
    $(function() {
        $("#Languages-spoken-and-understood-8").click(ToggleCheckbox);
        ToggleCheckBox(); 
    });
    

    If you want to clean it up a bit I'd extract the checkbox and languages element into separate vars:

    var languages = $("#Languages-spoken-and-understood-8");
    var checkbox = $("#li-2-21");
    

    make sure you place them in the appropriate scope though. This will mean that jQuery doesn't need to keep requerying the DOM to find them.

    0 讨论(0)
提交回复
热议问题