Categories
JavaScript Answers

How to Limit Number of Tags with jQuery Select2 Drop Down?

To limit number of tags with jQuery Select2 drop down, we can set the maximumSelectionLength property to the max number of values we can select.

For instance, we can write:

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<select id="select2" multiple>
  <option>Foo</option>
  <option>Bar</option>
  <option>Baz</option>
  <option>Some Text</option>
  <option>Other Text</option>
</select>

We create a select element with the multiple attribute.

Then we write:

$('select').select2({
  maximumSelectionLength: 3
});

We call select2 with an object with the maximumSelectionLength property set to 3.

Now we can only select 3 choices max.

Categories
JavaScript Answers

How to Merge Keys Array and Values Array into an Object in JavaScript?

To merge keys array and values array into an object in JavaScript, we can use the JavaScript array’s reduce method.

For instance, we write:

const keys = ['height', 'width'];
const values = ['1px', '2px'];
const merged = keys.reduce((obj, key, index) => ({
  ...obj,
  [key]: values[index]
}), {});
console.log(merged)

We have the keys and values array that has the property keys and their corresponding values.

Next, we call keys.reduce with a callback to get the key and put the key as the property name.

And the values[index] value is set as the value of [key].

We then return that object.

The 2nd argument of reduce is an empty object so obj is set to an empty object initially.

Therefore, merged is:

{height: "1px", width: "2px"}
Categories
JavaScript Answers

How to Only Allow Selected Valued from Suggested List with jQuery UI AutoComplete?

To only allow selected valued from suggested list with jQuery UI AutoComplete, we can listen to the keyup event and check if the option is a valid option in the keyup event listener.

For instance, we write:

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input id="ac">

to add the CSS and JavaScript files for jQuery and jQuery UI.

We also add the input element for the autocomplete.

Then we write:

const validOptions = ["Bold", "Normal", "Default", "100", "200"]
let previousValue = "";

$('#ac').autocomplete({
  autoFocus: true,
  source: validOptions
}).keyup(function() {
  let isValid = false;
  for (const o of validOptions) {
    if (o.toLowerCase().match(this.value.toLowerCase())) {
      isValid = true;
    }
  }
  if (!isValid) {
    this.value = previousValue
  } else {
    previousValue = this.value;
  }
});

We call autocomplete to turn the input into an autocomplete input.

Then we call keyup to listen to the keyup event.

In the event handler, we check is the this.value input value matches the o value in the validOptions list.

If it does, then we set isValid to true.

If isValid is false, then we set the input value to previousValue to restore the input value to the old value.

Otherwise, we set previousValue to this.value to store the valid input value.

Categories
JavaScript Answers

How to Prevent the Default Behavior When Ctrl+S is Pressed in Chrome?

To prevent the default behavior when Ctrl+S is Pressed in Chrome, we can use the jQuery bind method to listen to the keydown event.

Then in the keydown event handler, we can check if Ctrl+S is pressed.

And if it’s pressed, we return false and call preventDefault.

For instance, we can write:

$(document).bind('keydown', (e) => {
  if (e.ctrlKey && (e.which === 83)) {
    e.preventDefault();
    return false;
  }
});

We call bind on $(document) to listen to the keydown event on the whole document.

In the event handler, we check is the Ctrl key is pressed with e.ctrlKey.

And we check if the S key is pressed with e.which. 83 is the key code for the S key.

If both are true, then we call e.preventDefault to stop the default behavior.

And we also return false.

To do the same thing with plain JavaScript, we can use the document.addEventListener method.

To use it, we write:

document.addEventListener("keydown", (e) => {
  if (e.key === 's' && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
    e.preventDefault();
  }
});

We check if e.key is 's' to check if the S key is pressed.

And we check if the Ctrl or Command key is pressed with (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey).

We check if the code is run on a Mac with navigator.platform.match("Mac") and check the key pressed accordingly.

If both are true, we call e.preventDefault.

Categories
JavaScript Answers

How to Check if a Div is Scrolled All the Way to the Bottom with jQuery?

To check if a div is scrolled all the way to the bottom with jQuery, we can call the on method with 'scroll' and a scroll event handler.

For instance, if we have the following div:

<div style='overflow-y: scroll; height: 100px;'>
  Lorem ipsum dolor sit amet, ...
</div>

then we can write:

const chkScroll = (e) => {
  const elem = $(e.currentTarget);
  if (elem[0].scrollHeight - elem.scrollTop() === elem.outerHeight()) {
    console.log("bottom");
  }
}

$(document).ready(() => {
  $('div').on('scroll', chkScroll);
});

to add the chkScroll function which we use as the div’s scroll event handler.

In the function, we get the div being scrolled with:

const elem = $(e.currentTarget);

Then we check if we scrolled the div to the bottom by writing:

elem[0].scrollHeight - elem.scrollTop() === elem.outerHeight()

scrollHeight has the height of all of the content in the div.

scrollTop returns the location that we scrolled to.

outerHeight has the height of the div.

So if elem[0].scrollHeight - elem.scrollTop() is the same as elem.outerHeight(), we know we scrolled to the bottom.

Therefore, when we scrolled to the bottom, 'bottom' is logged.