Expanding the div with jQuery and HTML

Having some trouble with my code here. I need to remove a link (a) and replace it with a new link (a) that has different text.

This is the current code:

HTML:

<label for="name" class="control-label">Username:</label> 
@<a href="<?php echo $username ?>">
    <p class="text-info-username">
        <?php echo strtolower($username) ?><i class="icon-star"></i></a></p>
<div class="controls-username">
    <a href='#' id="edit-username" class="btn"><i class="fa fa-pencil"></i> Edit</a>
</div>

Script:

$('#edit-username').click(function() {
 var text = $('.text-info-username').text();
 var input = $('<input type="text" placeholder="' + text + '" id="editTextBox" />')

 $('.text-info-username').text('').append(input);
 $('#edit-username').remove();
 $('<a href='#' id="update" class="btn">Update</a>').appendTo('.controls-username');
 $('<br /><br />').insertAfter('.controls-username');

});

Answer №1

It seems like there was a problem with the way you used quotations in your code. Here is an updated version of your JavaScript:

$('#edit-username').click(function() {
 var text = $('.text-info-username').text();
 var input = $('<input type="text" placeholder="' + text + '" id="editTextBox" />');

 $('.text-info-username').text('').append(input);
 $('#edit-username').remove();
 $('<a href="#" id="update" class="btn">Update</a>').appendTo('.controls-username');
 $('<br /><br />').insertAfter('.controls-username');

});

You can also view it on jsFiddle: http://jsfiddle.net/qhcf39oo/

Answer №2

There are several concerns to address:

  1. Incorrect HTML element nesting with the first -Tag.
  2. A missing semicolon in your javascript after defining input.
  3. Manipulating HTML from javascript can make debugging harder and is not necessary. Consider pre-loading the html on initial pageload and using css/javascript to toggle visibility instead.

I've created a quick jsFiddle example for you:

$('#button-edit-username').click(function() {

  // Hide the user list
  $('.text-info-username').hide();

  // Show a form with pre-filled contents
  var text = $('.text-info-username').text();
  $('#editTextBox').attr('placeholder', text);
  $('#editForm').show();

  // Swap the visible link
  $('#button-edit-username').hide();
  $('#button-update').show();

});

$('#button-update').click(function() {

  // Hide the form again
  $('#editForm').hide();

  // Show the user list again
  $('.text-info-username').show();

  // Swap the visible link
  $('#button-update').hide();
  $('#button-edit-username').show();


  // Report success.. implement save function here
  var newName = $('#editTextBox').val();
  alert('Successfully edited .. '+ newName +' !');    

});

You can view the complete example at https://jsfiddle.net/8xhwugu/, demonstrating this approach.

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

When the screen size is decreased, one card begins to appear behind another card

In my attempt to create a set of responsive cards using Bootstrap, I have written the following code for the cards: <div class="col-xl-4 col-md-6 col-sm-6 p-2"> <div class="card shadow" style=" ...

Can scrollHeight ever be less than clientHeight or offsetHeight?

Is it guaranteed that the output of Math.max(el.scrollHeight, el.offsetHeight, el.clientHeight) will always be equal to el.scrollHeight? Typically, clientHeight <= offsetHeight <= scrollHeight. While there are rare instances where clientHeight > ...

Image failed to load

Issue Encountered in Browser Console: https://static.food2fork.com/pastaallavodkaa870.jpg.jpg 404 While attempting to display the image on the browser, I am uncertain if the problem lies within my code or with food2fork. Code from index.js: // Alway ...

issue with transmitting PHP data through ajax causing data to be undefined

This function is responsible for calling and changing the values <select width="100" name="produto" id="produto-list" class="produtoInputBox" onChange="getapolice(this.value);" <?php echo $permissao; ?> > Here's the function in actio ...

Interacting with Rails controllers through AJAX to trigger a JavaScript function

After exploring numerous stack overflow posts without finding a working solution, I decided to seek help for a well-documented use case. I have a button that should perform the following tasks: When clicked, call a custom controller method to update th ...

What is the best way to make my div collapse after it has been expanded with jQuery?

I recently found a solution to a coding issue I was having by borrowing code from someone else's similar question. After some tweaks, I managed to get it to work on my website. Now, when you click 'Expand', additional text appears; however, ...

Issues arising from code that computes percentages

I currently have three boxes in my HTML template that are meant to calculate and display various values. The first box is calculating a score, the second box represents the total amount of points possible, and the third box is supposed to show the percenta ...

Unable to access specific route in Angular if default route contains a parameter

Here is a list of my routes: const routes: Routes = [ { path: '', component: BlogLayoutComponent, children: [ { path: ':pageNumber', component: HomeComponent }, { path: '&apo ...

What is the method for defining a CSS property for the ::before pseudo element within an Angular component?

Can TypeScript variables be accessed in SCSS code within an Angular component? I am looking to achieve the following: <style type="text/css"> .source-status-{{ event.status.id }}::before { border-left: 20px solid {{ event.status.colo ...

What is the best way to ensure that three images stretching across the entire width of the website are responsive?

I am looking to showcase 3 images across the full width of my website, with each image taking up one-third of the space. I want these images to be responsive and adjust accordingly to different screen sizes while maintaining their aspect ratio. Do you have ...

Unable to change color of SVG icon when active

I seem to be having trouble getting my SVG element to fill with a specific color in the active state. Despite searching online for examples, I couldn't find much relevant information on this topic. Most of the resources available online focus on hover ...

Finding the filename using the event object in JavaScript: A step-by-step guide

Picture this scenario: an HTML file named page1.html includes a script tag for base.js. Within base.js (an external JavaScript file), I assign an onclick listener to a button that exists in page1.html. This base.js file is also included in script tags on o ...

Content and picture within a <button> element do not align on the same row when using flexbox in Firefox browser

I need assistance in aligning a button with an image and text in the center of the same row. However, in Firefox, the image and text appear on separate lines. How can I resolve this issue? This is my current code snippet: button { display: inline-fle ...

I kept encountering random jQuery errors

After creating a website using jQuery and JavaScript, I encountered some issues with the JS files not loading properly. The following errors were reported in the console: Uncaught ReferenceError: jQuery is not defined(anonymous function) @ jquery.easing ...

Utilizing Wordpress for Geocoding with a map or directions

I'm currently working on setting up a Wordpress page where users can specify a location either by entering an address or browsing a map. However, I am encountering an issue with the map not loading on the page () despite verifying the API Key and the ...

What is the best way to delete only the current occurrence of the array, without removing all other instances?

Is there a way to remove only the current instance of the array, without affecting all other instances? var persons = []; showAllButton.onclick = function() { while (showList.firstChild) showList.removeChild(showList.firstChild); New node instances h ...

Challenges with CSS arise when creating a custom dropdown navigation menu using ul and li elements in Internet Explorer, specifically dealing with the overflow:visible bug

The issue with the ie6 bug (where dropdown entries need to be truncated using overflow hidden to prevent ie from incorrectly expanding instead of behaving as overflow:visible) can clearly be seen in its current (hacky) form in the screenshot below, and als ...

The necessity of enclosing const names in curly braces in ReactJS

display () { const { parameters } = this.props.parameters return ( <div>{ parameters.post }</div> ) } Is there a specific reason why the parameters must be enclosed in curly brackets? Couldn't it simply be 'const params = th ...

filtering multiple items using checkboxes in vanilla JavaScript

Currently, I am facing a challenge in creating filters for a dynamically generated table. I have implemented checkboxes as part of my solution, but I seem to be stuck at this point. Despite conducting extensive research, I have been unable to find a suita ...

The transition animations on a mouseover accordion effect are not smooth

Looking to set up a simple website for a project that fetches data from a server using AJAX and displays it as depicted in the image? The issue isn't with JavaScript but rather with pure HTML+CSS. To view this page on jsfiddle, you can click here. Al ...