This question already has answers here:
How to set HTML5 required attribute in Javascript?
                                
                                    (6个答案)
                                
                        
                2年前关闭。
            
        

脚本中的必需项不起作用

$("#s_postby").attr('required', false); // put the id of the input field that you whant required
$("#s_postby").attr('required', true); // put the id of the input field that you whant required


我在帖子的osclass主题中添加了一些无线电字段!

    <div id="postby" class="property-ads-100">
      <label>
        <span class="required_fields">*</span>
        <?php _e('Posted By', 'ctg_housing'); ?>
      </label>
      <div class="item-post-postby-checkbox columns-0">
        <input  type="radio" name="s_postby" value="owner" id="s_postby0" <?php if(isset($housing['s_postby']) && $housing['s_postby'] =='owner') { echo 'checked="checked"'; }; ?>>
        <label for="s_postby0">
          <?php _e('Owner', 'ctg_housing'); ?>
        </label>
      </div>
      <div class="item-post-postby-checkbox columns-0">
        <input type="radio" name="s_postby" value="agent" id="s_postby1" <?php if(isset($housing['s_postby']) && $housing['s_postby'] =='agent') { echo 'checked="checked"'; }; ?>>
        <label for="s_postby1">
          <?php _e('Agent', 'ctg_housing'); ?>
        </label>
      </div>
      <div class="item-post-postby-checkbox columns-0">
        <input type="radio" name="s_postby" value="broker" id="s_postby2" <?php if(isset($housing['s_postby']) && $housing['s_postby'] =='broker') { echo 'checked="checked"'; }; ?>>
        <label for="s_postby2">
          <?php _e('Broker', 'ctg_housing'); ?>
        </label>
      </div>
      <div class="item-post-postby-checkbox columns-0">
        <input type="radio" name="s_postby" value="agency" id="s_postby3" <?php if(isset($housing['s_postby']) && $housing['s_postby'] =='agency') { echo 'checked="checked"'; }; ?>>
        <label for="s_postby3">
          <?php _e('Agency', 'ctg_housing'); ?>
        </label>
      </div>
    </div>


我将其隐藏在某些类别中(脚本中的必需项不起作用!)为什么?

<script type="text/javascript">
$('#catId').change(function(){
    if( $('#catId').val() == "28" || $('#catId').val() == "29" ||
$('#catId').val() == "30" || $('#catId').val() == "31")
    {
        $("#postby").hide();  // change Posted By with ID you give to the div
    $("#s_postby").attr('required', false); // put the id of the input field that you whant required
    }else
    {
         $("#postby").show(); // change Posted By with ID you give to the div
    $("#s_postby").attr('required', true); // put the id of the input field that you whant required
    }
});
</script>


我现在需要什么来使此无线电字段在显示时是必需的,而在不需要时是隐藏的!当显示并需要时,我需要一条错误消息发布者:此字段为必填项!

希望可以有人帮帮我!

最佳答案

element.required = true;


How to set HTML5 required attribute in Javascript?

10-07 21:47