2017-10-05 104 views
-1

我想使輸入類型文本字段可編輯點擊按鈕,但它不能正常工作。嘗試了所有可能的事情任何建議,請如何使內容可編輯按鈕

<html><body> 
    <script> 
    $(document).ready(function() 
    { 
    $('#btnEdit').click(function() 
    { 
     $("input[name='name']").removeAttr("readonly"); 
    }); 

    }); 

    </script> 
    <?php 
    require_once ('connectdb.php'); 

    $sql = "SELECT * FROM general_information"; 
    $result = $dbhandle->query($sql); 
    if ($result->num_rows > 0) { 
     // output data of each row 
     while($row = $result->fetch_assoc()) { 

    ?> 
    <form> 
    <input type = "text" name = "name" value = <?php echo $row["email"];?> readonly> 
    <button class="btn btn-primary" id="btnEdit" > edit </button> 
    <?php } } ?> 
    </form> 
    </body></html> 
+2

請定義「_not working properly_」。不要使用'name'作爲'name'的值,或者HTML元素的任何其他屬性或屬性。 – Teemu

+0

你有沒有包含jQuery? –

回答

0

有兩個問題我在代碼中看到,

  1. 按鈕時提交表單並重新加載頁面。使用preventDefault()覆蓋表單提交。使用prop代替removeAttr

    $(document).ready(function(){ 
    
        $('#btnEdit').click(function(e){ 
         e.preventDefault(); 
         $("input[name='name']").prop("readonly", false); 
        }); 
    }); 
    

從@cmorrissey評論UPDATE。

  • 在文本框中,引號中缺少value屬性

    <input type = "text" name = "name" value = "<?php echo $row["email"];?>" readonly> 
    
  • +1

    3.'value'不包含在'''' 中4.如果從數據庫中選擇多於1行,則有多個開放的'form'標籤,具有相同'id'的多個按鈕 – cmorrissey

    0

    你的按鈕因此發佈的形式重新加載頁面,以便更改按鈕,給它一個onclick事件功能等的onclick = 「editInputField()」:

    <a href="#" class="btn btn-primary" role="button" onclick="editInputField()">Edit</a> 
    

    給輸入和ID:

    <input type = "text" id = "name" name = "name" value = <?php echo $row["email"];?> readonly> 
    

    然後你的JavaScript功能,使輸入編輯:

    <script type="text/javascript"> 
    function editInputField(){ 
        document.getElementById("name").readOnly = false; 
    } 
    </script> 
    

    編輯

    我注意到您在使用,即使問題被標記與JavaScript的jQuery。 爲什麼你的代碼是不工作的原因有做:

    1:

    <a href="#" class="btn btn-primary" id="btnEdit" role="button">Edit</a> 
    

    2:您如何針對輸入字段,使用字段標識如前所述所以改爲按鈕像這樣:

    $("#fieldID").removeAttr("readonly"); 
    
    +0

    這不解釋所有_why_OP的代碼無效 –

    +0

    @HermanLauenstein我已經更新了我的答案。 – Laiman

    0

    您可以使用禁用readOnly的屬性。這裏有兩個例子。

    <input type="text" id="name" disabled="disabled" value="Example"/> 
    <input type="text" id="name2" readonly="readonly" value="Example2"/> 
    <button onclick="myFunction()">Click me</button> 
    
    function myFunction() { 
    
        document.getElementById("name").disabled = false; 
        document.getElementById("name2").readOnly = false; 
    
    } 
    
    相關問題