Categories
JavaScript Answers

How to access form elements by HTML ID or name attribute with JavaScript?

To access form elements by HTML ID or name attribute with JavaScript, we use the elements property.

For instance, we write

<form id="myForm">
  <input type="text" name="foo" />
</form>

to add a form.

Then we write

const fooInput = document.getElementById("myForm").elements["foo"];

to get the input inside the form.

We select the form with getElementById.

And then we get the input with the elements["foo"] property.

'foo' is the name attribute value of the input.

Categories
JavaScript Answers

How to determine if an HTML element’s content overflows with JavaScript?

To determine if an HTML element’s content overflows with JavaScript, we check if the parent width is smaller than the element’s width.

For instance, we write

const checkOverflow = (elem) => {
  const elemWidth = elem.getBoundingClientRect().width;
  const parentWidth = elem.parentElement.getBoundingClientRect().width;

  return elemWidth > parentWidth;
};

to get the elem element’s width with elem.getBoundingClientRect().width;.

We get its parent’s width with elem.parentElement.getBoundingClientRect().width;.

And then if elem‘s width is bigger than parentWidth, then elem overflows its parent.

Categories
JavaScript Answers

How to remove whitespaces inside a string in JavaScript?

To remove whitespaces inside a string in JavaScript, we call the string replace method.

For instance, we write

const s = "hello world".replace(/\s/g, "");

to call "hello world".replace to replace all spaces with empty strings.

\s matches spaces.

And the g flag makes replace replace all spaces.

Categories
JavaScript Answers

How to get list of data-* attributes using JavaScript?

To get list of data-* attributes using JavaScript, we use the dataset property.

For instance, we write

const attributes = element.dataset;
const cat = element.dataset.cat;

to get a list of data- attributes as an object with the element.dataset property.

We use the element.dataset.cat property to get the value of the element‘s data-cat attribute.

Categories
Vue Answers

How to get selected option on @change with Vue.js?

To get selected option on @change with Vue.js, we should use v-model to bind the selected value to a reactive property.

For instance, we write

<select
  name="LeaveType"
  @change="onChange($event)"
  class="form-control"
  v-model="key"
>
  <option value="1">Annual Leave/ Off-Day</option>
  <option value="2">On Demand Leave</option>
</select>
<script>
  const vm = new Vue({
      data: {
          key: ""
      },
      methods: {
          onChange(event) {
              console.log(event.target.value)
          }
      }
  }
</script>

to add a select drop down.

We bind the key reactive property to the value of the selected value of the drop down with v-model.

Also we can get the value from event.target.value from the change event handler.