Checkbox shows hidden field - not working onload

大城市里の小女人 提交于 2019-12-02 22:14:53

问题


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");
   $("#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");
    }
  });

That works fine but it doesn't work if a page is loaded and the checkbox is already checked because the #li-2-21 gets automatically hidden.

Do I need to create a function that reads the state of the checkbox? Or is there a simpler way?

Oh and also feel free to shorten that ugly code, I guess there's a shorter way to achieve my goal? Thanks so much for your help!


回答1:


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




回答2:


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.




回答3:


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();


来源:https://stackoverflow.com/questions/3580276/checkbox-shows-hidden-field-not-working-onload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!