Categories
JavaScript Answers

How to prevent browser from loading a drag-and-dropped file with JavaScript?

To prevent browser from loading a drag-and-dropped file with JavaScript, we stop the default behavior for the dragover and drop events.

For instance, we write

window.addEventListener(
  "dragover",
  (e) => {
    e.preventDefault();
  },
  false
);

window.addEventListener(
  "drop",
  (e) => {
    e.preventDefault();
  },
  false
);

to call addEventListener to add event listeners for the window’s dragover and drop events.

In the event handlers, we call e.preventDefault to stop the default drtag and drop behavior to stop the loading of dragged and dropped files.

Categories
JavaScript Answers

How to get an element’s id with JavaScript?

To get an element’s id with JavaScript, we use the id property.

For instance, we write

const id = myDOMElement.id;

to get the myDOMElement‘s ID with the id property.

Categories
JavaScript Answers

How to disable form auto submit on button click with JavaScript?

To disable form auto submit on button click with JavaScript, we return false in the form submit event handler.

For instance, we write

myForm.onsubmit = () => {
  // ...
  return false;
};

to set the myForm.onsubmit property to a function that returns false to prevent the default form submission behavior.

Categories
JavaScript Answers

How to get selected option text with JavaScript?

To get selected option text with JavaScript, we can use the selectedIndex property.

For instance, we write

<select id="box1" onChange="onChange(this);">
  <option value="98">dog</option>
  <option value="7122">cat</option>
  <option value="142">bird</option>
</select>

to add a select drop down.

We set the onchange attribute to call onChange with the select element.

Then we write

function onChange(sel) {
  console.log(sel.options[sel.selectedIndex].text);
}

to define the onChange function.

We get the selected option with sel.options[sel.selectedIndex].

And we get the option’s text with the text property.

Categories
HTML

How to make an HTML text box show a hint when empty?

To make an HTML text box show a hint when empty, we set the placeholder attribute.

For instance, we write

<input name="email" placeholder="Email Address" />

to set the placeholder attribute to Email Address to show that as the placeholder when the input is empty.