2015-11-26 36 views
1

我有一个脚本,显示一些并隐藏一些html,但我不知道如何添加所需的标记,当它显示,我已经尝试添加属性的部分,我想要它,但它需要它即使不显示...有人可以帮助我。提前致谢!所有的如何添加必填属性?

<div class="start"><select name="start" class="form-control"> 
      <option value="0" class="select">Select City</option> 
       <?php foreach($rows as $row): ?> 
        <option <? echo 'value="'.$row['id'].'"'; 
         echo ($row['id'] == $job['start'])?' selected>':'>'; 
         echo $row['name']; ?></option> 
       <?php endforeach; ?> 
      </select></div><br /> 
      <br /> 
      <script> 
      $('select[name=start]').change(function() { 
       if ($(this).val() == '89') { 
        $('#otherStart').show(); 
       } else { 
        $('#otherStart').hide(); 
       } 
      }); 
      </script> 
      <br /> 
      <div id="otherStart"> 
       <input type="text" name="otherStart" placeholder="Other City" <? echo ($job['otherStart'])?' value="'.$job['otherStart'].'"':''; 
      ?> class="form-control" > 
      </div> 
+0

的'required'属性?将它添加到什么元素和什么时候? '$('#otherStart')。show()。attr(“required”,“required”);'。你应该用'jquery'来标记你的问题,因为你正在使用它。 – Arg0n

回答

0

首先,你需要分配一个id -attribute你正在修改的投入,使我们可以改变使用jQuery的属性。您已经使用<div id="otherStart">来显示/隐藏整个div,因此请选择其他名称,例如id="inputOtherStart"(ID应始终唯一)。

然后,我们使用jQuery分别在显示和隐藏div时添加和删除属性。

<script> 
$(function() { 
    // Function to show/hide the extra subject-field, and making it required or not 
    var Start = '#Start'; 
    var otherStart = '#otherStart'; 
    var otherStartInput = '#otherStartInput'; 

    $(otherStart).hide(); 
    $(Start).change(function(){ 
     if($(Start).val() == 89) { 
      $(otherStart).show(); 
      $(otherStartInput).prop('required',true); 
     } else { 
      $(otherStart).hide(); 
      $(otherStartInput).prop('required',false); 
     } 
    }); 
}); 
</script> 
<br /> 
<div id="otherStart"> 
    <input type="text" id="otherStartInput" name="otherStart" placeholder="Other City" <? echo ($job['otherStart'])?' value="'.$job['otherStart'].'"':''; ?> class="form-control" /> 
</div> 
+0

我试过这样做,它是有道理的,但由于某种原因,它不会添加属性 –

+0

您是否已将'id'属性添加到'input'?你是如何检查它没有添加属性的(检查代码不起作用)。 – Qirel

+0

@MrJohnDowe现在就试试吧,我已经更新了jQuery脚本。测试它,这个应该可以工作,只要'input'有适当的'id'。 – Qirel

0

添加和删除属性“需要”的时候DIV显示和隐藏,你可以修改你的JavaScript原样

  <script> 
      $('select[name=start]').change(function() { 
       if ($(this).val() == '89') { 
        $('#otherStart').show(); 
        $('#otherStart : input').attr('required'); 
       } else { 
        $('#otherStart').hide(); 
        $('#otherStart : input').removeAttr('required'); 
       } 
      }); 
      </script> 
1

为了让在jQuery的你应该使用.prop需要某一个元素:

$(selector).prop("required", true); 

您还可以使用属性required做到这一点在JavaScript:

element.required = true; 

再或者,

element.setAttribute("required","");