Need to update various form fields at once with jquery?

There is a form with fields for firstname, lastname, email, country, along with edit icon and submit/cancel buttons.

When the user clicks on the edit icon in the top right corner, all values will be displayed in textboxes and the country will be shown in a select dropdown.

I have attempted some code but I am encountering issues where all values are being displayed in a single field and appearing multiple times. Can anyone assist me with this?

$('#edit').click(function() {
 var text = $('.text-info').text();
 var input = $('<input id="attribute" type="text" value="' + text + '" />')
 $('.text-info').text('').append(input);
 input.select();
 $('.btn').show();
 $('#edit').hide();
});
.width-400{width: 400px;margin: 0 auto;padding: 20px;}
.border{border:1px solid #000;}
input{margin-bottom: 10px; width: 100%;}
.btn{display:flex;margin-top: 10px;display: none;}
.font-icon{text-align: right;}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="border width-400">
<div class="font-icon"><a class="edit" href="#" id="edit"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a></div>
<form method="post" action="update.php">
<div class="form-group">
    <label for="fname" class="control-label">Firstname:</label><spa class="text-info">Narendra</span>
</div>

<div class="form-group">
    <label for="lname" class="control-label">Lastname:</label><span class="text-info">verma</span>
</div>

<div class="form-group">
    <label for="email" class="control-label">Email:</label><span class="text-info"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b7a79785b7c767a727735787476">[email protected]</a></span>
</div>
    <select>
<option value="">Choose country</option>
<option>India</option>
<option>USA</option>
<option>UK</option>
</select>
<div class="btn">
<input type="submit" name="submit" value="save">
<input type="submit" name="submit" value="cancel">
</div>
    </form>
</div>

Answer №1

    $('#edit').click(function() {
     var text = $('.text-info').each(function (index,oneSpan){
                var input = $('<input type="text" value="' + $(oneSpan).text() + '" />')
     $(oneSpan).text('').append(input);
});
 

var country = $('.select-info').text();
  $('.select-info').hide();
  $('#select-elm').val(country).show();
 $('.btn').show();
 $('#edit').hide();
    });
.width-400{width: 400px;margin: 0 auto;padding: 20px;}
.border{border:1px solid #000;}
input{margin-bottom: 10px; width: 100%;}
  .btn{display:flex;margin-top: 10px;display: none;}
  .font-icon{text-align: right;}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="border width-400">
<div class="font-icon"><a class="edit" href="#" id="edit"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a></div>
<form method="post" action="update.php">
<div class="form-group">
    <label for="fname" class="control-label">Firstname:</label><span class="text-info">Narendra</span>
</div>

<div class="form-group">
    <label for="lname" class="control-label">Lastname:</label><span class="text-info">verma</span>
</div>

<div class="form-group">
    <label for="email" class="control-label">Email:</label><span class="text-info"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c1d1e1f3c1b111d1510521f1311">[email protected]</a></span>
</div>
<div class="form-group">
    <label for="country" class="control-label">Country:</label><span class="select-info">USA</span>
</div>
    <select id="select-elm" >
<option value="">Choose country</option>
<option>India</option>
<option>USA</option>
<option>UK</option>
</select>
<div class="btn">
<input type="submit" name="submit" value="save">
<input type="submit" name="submit" value="cancel">
</div>
    </form>
</div>

Points to Note: In the code, when using $('.text-info'), all nodes with this class are being selected. The text() method on it just concatenates them, resulting in a single string of values. After creating the input and appending it using

$('.text-info').text('').append(input);
, another array is returned by the text method, causing the append operation to be executed on all elements. This leads to a long string contained within an input that is appended multiple times to your spans.

Corrected Approach:

By utilizing each(function(){}) after fetching an array from $('.text-info'), we can iterate through each span individually. Simply create an input, retrieve the value from our individual span, empty it, and then populate it with our desired array one at a time.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for utilizing the onload attribute alongside the ng-controller directive to run a function that has been established within the controller

When trying to call the submit() function as soon as the page loads, I keep encountering a submit() method not found error. The positioning of ng-controller and onload is confusing to me. If there is an alternate method in Angular to achieve this, please ...

extract the text content from an object

I am trying to add an object to the shopping cart. The item contains a key/value pair as shown in the following image: https://i.stack.imgur.com/5inwR.png Instead of adding the title with its innerText using p and style, I would like to find another ...

Learn how to make a mesh in Three Js React refract its environment while keeping the background hidden from the camera

I've been grappling with this challenge for quite some time now, so any assistance would be highly valued! My aim is to create the illusion of an image being confined within a mesh structure. My initial idea was to utilize a mesh with defined thickne ...

Is there a way to retrieve the text content of the element that has been clicked?

code: <script> $(document).ready(function(){ $(".special").click(function(){ courses = this.id; location.href = "courses-college.php?courses="+courses; }); }); </script> <ul> <li class= ...

Navigating through Next.js for slug URLs such as site.com/username

Can someone help me figure out how to create a profile page for each username, like site.com/jack or site.com/jill? I'll be pulling the username info from an API that also contains the user ID and email. I'm new to Next.js and would really appre ...

Comment sections that refresh automatically after being posted

I am determined to provide a clear explanation. Despite having some code, I am uncertain about how to make it clone comments and add new ones with user inputted text. Below is the snippet of code I am struggling with: <!DOCTYPE html> <!-- this i ...

Please refrain from clearing the text field as it will delete the input value

I feel like I must be overlooking something really minor because I just can't seem to find it! I've been attempting to sanitize the text input by setting the state to ('') and while it clears the variable, the HTML input keeps displayi ...

"Successfully implementing AJAX POST functionality, but encountering issues where callbacks are not triggering

I have gone through numerous posts addressing this issue and attempted various solutions, however, none seem to work for me. My AJAX POST function correctly adds the email to my mailing list, but the success and error callbacks are not consistently firing, ...

Apply CSS styling to the entire element when hovering over its pseudo-element 'after'

I am working on a button/speech bubble design with a unique hover effect. Here is the current setup: https://i.stack.imgur.com/4OrpL.png Here is the code snippet for the button: <div value="GO" id="go-div" class="bubble"> <input type="submit ...

`Error encountered when JSONP script is returning incorrect MIME Type`

I am currently faced with the task of extracting data from a third-party feed that provides a JSON file. Unfortunately, I do not have access to the server to enable CORS, so after conducting some research I learned about using JSONP. When checking the Chro ...

I'm looking for a creative JavaScript prototype example that can help illustrate the concept of prototypes. Can someone share an interesting sample with me

I've been trying to wrap my head around prototypes, but I just can't seem to grasp their purpose and function. Is there anyone who can provide a straightforward example (such as a collegeStudent object) that will clarify the fundamentals of proto ...

Adjust sliders when buttons are clicked

Looking for advice on how to implement jQuery sliders when clicking buttons on my webpage. Additionally, I would like the slider to switch from slider1 to slider2 upon the second button click. I attempted using ajax but encountered difficulties. Thank yo ...

The binding in Knockoutjs is working properly, but for some reason the href attribute in the anchor tag is not redirecting to

Here is the HTML code snippet I am working with: <ul class="nav nav-tabs ilia-cat-nav" data-toggle="dropdown" data-bind="foreach : Items" style="margin-top:-30px"> <li role="presentation" data-bind="attr : {'data-id' : ID , 'da ...

Welcome to the awe-inspiring universe of Typescript, where the harmonious combination of

I have a question that may seem basic, but I need some guidance. So I have this element in my HTML template: <a href=# data-bind="click: $parent.test">«</a> And in my Typescript file, I have the following code: public test() { alert( ...

Whenever the state of a React component is modified, it does not automatically trigger a re

Currently, I am utilizing the React Infinite Scroller library to display a list of posts. Interestingly, my load more results function seems to be triggered three times, resulting in the update occurring thrice (verified through console.log). For renderi ...

Using backslashes to escape JSON values within a value in Angular

When retrieving JSON data from the backend, I often encounter an issue where the value is set to "key": "\$hello" and it results in an "Unexpected token d". Is there a way in Angular to handle or escape these characters once received from the server? ...

adjusting the width of an HTML table cell

I'm struggling with the code below: <table> <thead> <th class='1'>Date</th> <th class='2'>Start Time</th> <th class='3'>End Time </th> <th class='4 ...

"Preventing the propagation of a click event on an anchor tag with

Is there a way to prevent the parent anchor from executing its href when a child element is clicked, despite using stopPropagation? Here is the markup provided: <div id="parent"> <h5>Parent</h5> <a id="childAnchor" href="https:// ...

Execute a simulated click on the Material-UI Tabbar using a programmatic approach or keyboard shortcut

In my electron/react application, I am implementing Material UI tabs in the following manner: <Tabs> <Tab label="View1" > <View1 /> </Tab> <Tab label="View2"> ...

Create a concise shorthand representation for margins when styling with jss using Material-UI's theme object

When styling the component, I found a way to apply the margin in a specific manner. style.js const styles = theme => ({ button: { margin: '12px 18px', } }) However, I wanted to utilize material-ui's theme.spacing.unit f ...