Categories
JavaScript Answers

How to Add target=“_blank” to window.location in JavaScript?

Use window.open

The window.open method lets us open a new window or tab from a given tab.

For instance, we can write:

window.open('http://example.com', '_blank');

to open a new tab that opens http://example.com.

_blank means we open a new window.

Categories
JavaScript Answers

How to Fix the ‘Cannot read property style of undefined’ Error with jQuery DataTables?

Sometimes, we get the ‘Cannot read property style of undefined’ when we try to add a table with jQuery DataTables.

In this article, we’ll look at ‘Cannot read property style of undefined’ when we try to add a table with jQuery DataTables.

th Element Mismatch

One cause of this error is that the number of th elements in the table header or footer doesn’t match the columns defined in the columns option.

Therefore, we should make sure that both of them match.

colspan Mismatch

If we have colspan in the table header, we should make sure that at least 2 header rows and one unique th element for each column.

Use Zero-Based Colum Index to Refer to Existing Columsn with adding the columnDefs.targets Property

If we add the columnDefs.targets property, we should make sure that the array has indexes that aren’t out of bounds when counting from 0.

For instance, if we have the following HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>
<script src='//cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js'></script>
<link rel='stylesheet' href='//cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css'>
<table>

</table>

Then we can write the following JavaScript code:

const dataSet = [
  ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
  ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
  ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
  ["Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060"],
  ["Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700"],
  ["Brielle Williamson", "Integration Specialist", "New York", "4804", "2012/12/02", "$372,000"],
  ["Herrod Chandler", "Sales Assistant", "San Francisco", "9608", "2012/08/06", "$137,500"],
  ["Rhona Davidson", "Integration Specialist", "Tokyo", "6200", "2010/10/14", "$327,900"],
  ["Colleen Hurst", "Javascript Developer", "San Francisco", "2360", "2009/09/15", "$205,500"],
  ["Sonya Frost", "Software Engineer", "Edinburgh", "1667", "2008/12/13", "$103,600"],
  ["Jena Gaines", "Office Manager", "London", "3814", "2008/12/19", "$90,560"],
  ["Quinn Flynn", "Support Lead", "Edinburgh", "9497", "2013/03/03", "$342,000"],
  ["Charde Marshall", "Regional Director", "San Francisco", "6741", "2008/10/16", "$470,600"],
  ["Haley Kennedy", "Senior Marketing Designer", "London", "3597", "2012/12/18", "$313,500"],
  ["Tatyana Fitzpatrick", "Regional Director", "London", "1965", "2010/03/17", "$385,750"],
  ["Michael Silva", "Marketing Designer", "London", "1581", "2012/11/27", "$198,500"],
]

jQuery('table').DataTable({
  data: dataSet,
  columns: [{
      title: "Name"
    },
    {
      title: "Position"
    },
    {
      title: "Office"
    },
    {
      title: "Extn."
    },
    {
      title: "Start date"
    },
    {
      title: "Salary"
    }
  ],
  columnDefs: [{
    orderable: false,
    targets: [0, 1, 2]
  }]
});

to add the columnDefs.targets property.

0 is the first column, 1 is the 2nd one, and 2 is the 3rd one.

We set orderable to false so we disabled reordering items for those columns.

Conclusion

To fix the ‘Cannot read property style of undefined’ when we try to add a table with jQuery DataTables, we should make sure the th elements and colspan matches the number of columns.

Also, we should make sure the columnDefs.targets property should match the indexes of the columns in the table.

Categories
JavaScript Answers

How to Validate Floats and Decimal Separators with the HTML5 Number Input?

Sometimes, we want to validate floating-point numbers with decimal separators with the HTML5 number input.

In this article, we’ll look at how to validate floats and decimal separators with HTML5 number input.

Add the pattern Attribute

We can add the pattern attribute to an HTML5 number input to add validation to the input.

For instance, we can write:

<input type="number" name="price" pattern="[0-9]+([.,][0-9]+)?" step="0.01" >

Then we can write the following JavaScript code to get the value when we’re done typing on the input and move focus away from the input:

const input = document.querySelector('input')
input.addEventListener('change', (e) => {
  console.log(e.target.value)
})

The pattern attribute will restrict the value that’s entered along with the number input type.

And in the JavaScript code, we call addEventListener to listen to the change event which is triggered when we stop typing and move focus away from the input.

We get the value entered into the input with e.target.input .

Conclusion

We can add the pattern attribute to an HTML5 number input to add validation to the input.

Categories
JavaScript Answers

How to Jump to an Anchor Element by Using JavaScript?

We can use the location.href property to get the URL without the hash.

Then we can append the hash to it.

And then we can remove the hash from the URL in the URL bar with history.replaceState .

For instance, we can write the following HTML:

<button>
  jump
</button>
<div id='a'>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi rhoncus dignissim lacus, ac ullamcorper ex aliquam vel. Donec nec luctus augue, sit amet porttitor diam. Ut sit amet mi ac risus congue ultricies. Donec et condimentum nisi, sit amet consequat felis. Nam velit nibh, blandit non nunc eget, ullamcorper suscipit ex.
</div>
<div id='b'>
  Phasellus faucibus fringilla ullamcorper. Vivamus gravida urna vel odio rutrum rutrum. Vivamus pretium, orci eget cursus tempus, quam elit rutrum est, vel fermentum sapien odio sit amet velit. Etiam cursus pulvinar massa, non maximus dolor vestibulum id. Morbi mi mauris, iaculis ac sem a, porta vehicula risus. Curabitur tincidunt sollicitudin sapien, ac tristique ligula ullamcorper eget. Donec tincidunt orci non ligula auctor ullamcorper. Aliquam mattis elit mauris, at posuere nulla lobortis id.
</div>

Then we can add a button to scroll down to the div with ID b by writing:

const jump = (h) => {
  const url = location.href;
  location.href = "#" + h;
  history.replaceState(null, null, url);
}
`
const button = document.querySelector('button')
button.addEventListener('click', () => {
  jump('b')
})

We have the jump function with the h parameter which is the ID of the element we want to scroll to.

Next, we get the current URL with location.href .

Then we add the hash with the ID h to it to jump to the element with ID h .

And then we call history.replaceState with url as the 3rd argument to replace the hash URL with the original.

Next, we get the button with document.querySelector .

And then we call addEventListener with 'click' to add a click listener.

The 2nd argument is the click listener which calls jump with 'b' to scroll to the div with ID b .

Categories
JavaScript Answers

How to Check if a Value is Within a Range of Numbers in JavaScript?

We can use the JavaScript’s greater than or equal to and less than or equal to operators to check if a number is in between 2 numbers.

For instance, we can write:

const between = (x, min, max) => {
  return x >= min && x <= max;
}
// ...
const x = 0.002
if (between(x, 0.001, 0.009)) {
  // something
}

We create the between function with the x , min and max parameters.

x is the number we want to check if it’s between min and max .

Then we call it in the if statement to see if x is between 0.001 and 0.009.

Use the Lodash inRange Method

We can also use the Lodash inRange method to check if a number is in between 2 numbers.

To use it, we write:

const x = 0.002
if (_.inRange(x, 0.001, 0.009)) {
  // something
}

We call inRange with the number x that we want to check if it’s between 0.001 and 0.009.