XDR
XDR

Reputation: 4490

Use CSS to change between displaying normal text fields & inputs

Say I have a web page that displays information for a user account, with fields like user name, first name, last name, birth date, email address, etc.

I would like to provide 2 modes for this info:

  1. Display mode: where the fields are just displayed as field name & value pairs that look like normal text (I don’t want the values to look like they’re displayed in disabled inputs)
  2. Edit mode: where the field names are displayed like labels for field values that are displayed as appropriate editable inputs for the field value

I would like to switch between these modes by applying a CSS class (e.g., edit) to a <div> that displays the fields. This should then change from displaying the data as normal text to displaying it in a form with an appropriate input or other element for each field.

How can I do this using CSS as much as possible, and JavaScript as little as possible?

I can see 2 main approaches:

  1. Always using the input & form elements in HTML, even when not in edit mode, but hiding buttons (like submit) & disabling modifying values unless under a <div class=“edit”>, along with changing the look of the input elements to make them (when not in edit mode) just look like normal display text instead of disabled inputs.
  2. Using non-input elements when just displaying data, then using CSS switch them to input elements when entering edit mode, and vice versa

I don’t know what effect the former would have on SEO, or other aspects around a web page.

I also don’t know which of these is easier to implement,or even if they are possible to implement without causing major problems (either for SEO, UI, etc.).

I know that JavaScript can edit the HTML DOM, but I’d prefer to do this only using CSS, to simplify the switching between the 2 modes.

Upvotes: 0

Views: 646

Answers (1)

Nick
Nick

Reputation: 16586

One option is to have entirely separate DOM trees for the view and edit modes and simply toggle the display of those seperate trees using display. Whether it's reasonable to have this much repetition depends a lot on your use case.

const container = document.querySelector("#container");

function toggle() {
  container.classList.toggle("view");
  container.classList.toggle("edit");
};
.view div {
  display: block;
}

.view form {
  display: none;
}

.edit div {
  display: none;
}

.edit form {
  display: block;
}
<div id="container" class="view">
  <div>
    Name: Steve
  </div>
  <form>
    <label>Name: </label>
    <input value="Steve" />
  </form>
  <button onclick="toggle()">Toggle view</button>
</div>

Upvotes: 0

Related Questions