Categories
JavaScript Answers

How to Handle Function KeyPress Events (F1-F12) using JavaScript?

To handle function keypress events (F1-F12) using JavaScript, we can add a key-down event handler.

And in it, we call preventDefault to stop the default action from executing.

And then we can do what we want instead when a function key is pressed.

For instance, we can write:

window.onkeydown = (evt) => {  
  switch (evt.keyCode) {  
    //ESC  
    case 27:  
      evt.preventDefault();  
      console.log("esc");  
      break;  
    //F1  
    case 112:  
      evt.preventDefault();  
      console.log("f1");  
      break;  
    default:  
      return;  
  }  
};

to set the window.onkeydown property to an event handler that checks what the keyCode property is pressed with a switch statement.

keyCode returns a numeric code for the key that’s pressed.

Keycode 27 is the escape key, and 112 is the F1 key.

We call evt.preventDefault to stop the default action in each case clause.

So pressing F1 will stop the help screen from displaying and will log 'f1' instead.

Categories
JavaScript Answers

How to Change the Placeholder Text of an Input Element with JavaScript?

To change the placeholder text of an input element with JavaScript, we can set the placeholder property of an element.

For instance, if we have the following input elements:

<input type="text" name="Email" placeholder="Some Text">
<input type="text" name="firstName" placeholder="Some Text">
<input type="text" name="lastName" placeholder="Some Text">

Then we can set the placeholder attribute value for each input element by writing:

document.getElementsByName('Email')[0].placeholder = 'new text for email';
document.getElementsByName('firstName')[0].placeholder = 'new text for fname';
document.getElementsByName('lastName')[0].placeholder = 'new text for lname';

We call document.getElementsByName to get the element with the given name attribute value.

Then we use index 0 to get the first element returned.

Next, we set the placeholder property of each to a string with the new placeholder property value.

And now we see the text we set in the JavaScript code is displayed as the placeholder text.

Categories
JavaScript Answers

How to Find the Index of an Object by Key and Value in a JavaScript Array?

To find the index of an object by key and value in a JavaScript array, we can use the JavaScript array’s findIndex method.

For instance, we can write:

const peoples = [{
    "attr1": "bob",
    "attr2": "pizza"
  },
  {
    "attr1": "john",
    "attr2": "sushi"
  },
  {
    "attr1": "larry",
    "attr2": "hummus"
  }
];
const index = peoples.findIndex((person) => {
  return person.attr1 === "john"
});
console.log(index)

We create the peoples array with objects that have the attr1 and attr2 properties.

Then we call findIndex on peoples with a callback that returns person.attr1 === 'john' .

This will return the index of the first object that has the attr1 property value set to 'john' .

Therefore, index is 1 as a result.

Categories
JavaScript Answers

How to Sort Arrays in JavaScript by Object Key Value?

To sort arrays in JavaScript by object key value, we can use the JavaScript array’s sort method.

For instance, we can write:

const arr = [{
  name: "alex"
}, {
  name: "clex"
}, {
  name: "blex"
}];
const sorted = arr.sort((a, b) => (a.name > b.name ? 1 : -1))
console.log(sorted)

to sort the arr array by the value of the name properties.

We call arr.sort with a callback that compare the name properties of entries a and b in the arr object.

If a.name is bigger than b.name , we return 1.

Otherwise, we return -1.

The comparison operator will compare 2 string’s by their lexical order.

Therefore, sorted is:

[
  {
    "name": "alex"
  },
  {
    "name": "blex"
  },
  {
    "name": "clex"
  }
]
Categories
JavaScript Answers

How to Split a String Once in JavaScript?

To split a string once in our JavaScript code, we can use the JavaScript string’s indexOf method with the JavaScript string’s slice method to find the index of the first instance of the separator and then do the slicing.

For instance, we can write:

const s = "1|Ceci n'est pas une pipe: | Oui";
const i = s.indexOf('|');
const splits = [s.slice(0, i), s.slice(i + 1)];
console.log(splits)

We have the s string that we want to split by the first | .

Then we call indexOf with '|' to get the index of the first instance of the | symbol.

Next, we call slice with 0 and i to get the substring before the first | .

And likewise, we call slice with i + 1 to get the part after the first | .

We then put both substrings into the splits array.

Therefore, splits is:

["1", "Ceci n'est pas une pipe: | Oui"]