简体   繁体   中英

form with js, html, not hidden fields at first

I have a problem with a field, code HTML

<span id="sudaner">
  <input type="radio" name="traveledis" checked value="0" >No
  <input type="radio" name="traveledis" value="1" />Yes
</span>

<div id="sudandetails">`

and this is the js code

$("#sudaner input[type='radio']").click(function(){
    if($(this).attr("value")=="1"){
        $("#sudandetails").css("display","block");
        $("#countries").prop('required',true);
        $("#bcfrom").prop('required',true);
        $("#bcto").prop('required',true);
        $("#country_reason").prop('required',true);
    }
    else {
        $("#countries").prop('required',false);
        $("#countries").val("");
        $("#bcfrom").prop('required',false);
        $("#bcfrom").val("");
        $("#bcto").prop('required',false);
        $("#bcto").val("");
        $("#country_reason").prop('required',false);
        $("#country_reason").val("");
        $("#sudandetails").css("display","none");
    }
});

I have 'checked' active in 'NO' but when I go to the form, I see the 'No' in default but the fields aren't hidden at first. I need to move the selection by 'Yes' and again 'No' and the fields are hidden or click 2 times in 'No' and the fields are hidden. so I don't understand why the field aren't hidden at first.

Thanks for your help

You need to hide this div initially. add this line in you script

$("#sudandetails").hide();

You bind an event on click and when page load click event not trigger.

I made a fiddle for you and combined the ready function with the click function in an own handler. You can't only check the value on click because there is no click if the document gets loaded, so nothing happens.

https://jsfiddle.net/ww582Lj9/

function myHandler(e) {
    if($(this).attr("value")=="1"){
          $("#sudandetails").css("display","block");
          $("#countries").prop('required',true);
          $("#bcfrom").prop('required',true);
          $("#bcto").prop('required',true);
          $("#country_reason").prop('required',true);
      }
      else {
          $("#countries").prop('required',false);
          $("#countries").val("");
          $("#bcfrom").prop('required',false);
          $("#bcfrom").val("");
          $("#bcto").prop('required',false);
          $("#bcto").val("");
          $("#country_reason").prop('required',false);
          $("#country_reason").val("");
          $("#sudandetails").css("display","none");
      }
}

$(document).ready(myHandler);
$("#sudaner input[type='radio']").on("click", myHandler);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM