简体   繁体   English

将段落属性更改为输入标签

[英]Change paragraph attribute to input tag

I tried following code in which I am trying to change paragraph tag to input fields through jquery on button click. 我尝试了下面的代码,其中我试图在按钮单击时通过jquery将段落标签更改为输入字段。 I want my values to retain in the textbox when I click the button. 当我单击按钮时,我希望我的值保留在文本框中。 Unfortunately, it isn't working! 不幸的是,它不起作用! Here I have tried it with just name field. 在这里,我仅使用名称字段进行了尝试。 Any suggestions please. 有任何建议请。

code

<div id="menu2" class="tab-pane fade">
            <h3>Address Book</h3>
            <p>Default delivery address</p>
            <?php
            $em=$_SESSION['login_email'];
            $query = mysqli_query($con,"SELECT * FROM customers where email='$em'" );
            while($row=mysqli_fetch_assoc($query)){
            ?>
            <h5>Name:</h5><p  class="name" id="name"><?= $row['name'] ?></p>
            <h5>Email:</h5><p class="mail"><?= $row['email'] ?></p>
            <h5>Telephone:</h5><p class="tele"><?= $row['phone'] ?></p>
            <h5>Address:</h5><p class="addres"><?= $row['address'] ?></p>
             <h5>City:</h5><p class="city"><?= $row['city'] ?></p>

            <?php
            }
            ?>
            <input type="button" id="update" value="Update Address" >
        </div>

Jquery jQuery的

 <script src="js/jquery-1.6.2.js"></script>
    <script>
        $(document).ready(function() {
            $('#update').click(function()

            var input = $("<input>", { val: $(this).text(),type: "text" });
            $('#name').replaceWith(input);
            input.select();
        });
        });


    </script>

Your code works, bar two errors. 您的代码有效,排除了两个错误。 Firstly, you're missing a { after the click handler function definition. 首先,在click处理程序函数定义之后,您缺少了{ Secondly, this within the #update click handler refers to the button element, yet you're trying to read the val() of the #name input, so you need to change the selector. 其次,在#update点击处理程序中, this引用了button元素,但是您试图读取#name输入的val() ,因此需要更改选择器。 With that in mind, try this: 考虑到这一点,请尝试以下操作:

$('#update').click(function() {
    var $name = $('#name');
    var $input = $("<input>", { 
        val: $name.text(),
        type: "text"
    });
    $name.replaceWith($input);
    $input.select();
});

Working example 工作实例

I would also be wary of having duplicated id attributes in your page as you are defining the elements in a loop. 当您在循环中定义元素时,我也会警惕在页面中有重复的id属性。 Should there be multiple rows returned from your query, then you will have multiple elements with the same id in the document which will lead to possible errors as the HTML will be invalid. 如果您的查询返回了多行,那么文档中将有多个具有相同id元素,这将导致可能的错误,因为HTML无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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