Categories
JavaScript Answers

How to prevent a click on a ‘#’ link from jumping to top of page with JavaScript?

To prevent a click on a ‘#’ link from jumping to top of page with JavaScript, we set the href attribute to some JavaScript code.

For instance, we write

<a href="javascript:void(0);">link</a>

to set the href attribute to javascript:void(0); to stop the link from jumping when we click it.

void(0) does nothing so nothing will happen when we click the link.

Categories
JavaScript Answers

How to clear an HTML file input with JavaScript?

To clear an HTML file input with JavaScript, we set its value property to an empty string.

For instance, we write

document.querySelector("#input-field").value = "";

to select the file input with querySelector.

Then we set its value property to an empty string to clear the file input.

Categories
Vue Answers

How to display unescaped HTML in Vue.js?

To display unescaped HTML in Vue.js, we can use the v-html directive.

For instance, we write

<template>
  <div id="logapp">
    <table>
      <tbody>
        <tr v-repeat="logs">
          <td v-html="fail"></td>
          <td v-html="type"></td>
          <td v-html="description"></td>
          <td v-html="stamp"></td>
          <td v-html="id"></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

to set v-html to the reactive properties with the HTML we want to render dynamically.

Categories
JavaScript Answers

How to unescape HTML entities in JavaScript?

To unescape HTML entities in JavaScript, we can use the DOMParser constructor.

For instance, we write

const htmlDecode = (input) => {
  const doc = new DOMParser().parseFromString(input, "text/html");
  return doc.documentElement.textContent;
};

console.log(htmlDecode("&lt;img src='myimage.jpg'&gt;"));

to define the htmlDecode function.

In it, we get the input string and parse it into a DOM object.

We create a DOMParser object and call it parseFromString method with the input and MIME type string to parse the input into a DOM object.

Then we get the textContent from the DOM object to get the HTML string unescaped.

Categories
JavaScript Answers

How to stop form submission with JavaScript?

To stop form submission with JavaScript, we call the preventDefault method.

For instance, we write

<form onsubmit="submitForm(event)">
  <input type="text" />
  <input type="submit" />
</form>

to add a form.

We set its onsubmit attribute to call the submitForm function with the submit event object.

Then we write

function submitForm(event) {
  event.preventDefault();
}

to define the submitForm function.

In it, we call event.preventDefault to stop form submissmision when we click on the submit button in the form.