简体   繁体   中英

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. 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

 <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. 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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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