2015-11-26 37 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","");