Categories
JavaScript Answers

How to make checkbox behave like radio buttons with JavaScript?

Sometimes, we want to make checkbox behave like radio buttons with JavaScript.

In this article, we’ll look at how to make checkbox behave like radio buttons with JavaScript.

How to make checkbox behave like radio buttons with JavaScript?

To make checkbox behave like radio buttons with JavaScript, we can listen to the body element’s click listener.

And in the listener, we uncheck all the checkboxes and the check off the one that matches the one that’s clicked.

For instance, we write:

<label>
  <input type="checkbox" name="cb1" class="chb" />
  CheckBox1
</label>
<label>
  <input type="checkbox" name="cb2" class="chb" />
  CheckBox2
</label>
<label>
  <input type="checkbox" name="cb3" class="chb" />
  CheckBox3
</label>
<label>
  <input type="checkbox" name="cb4" class="chb" />
  CheckBox4
</label>

to add the checkboxes.

Then we write:

const checkboxes = document.querySelectorAll('.chb')

document.body.addEventListener('click', (e) => {
  for (const c of checkboxes) {
    c.checked = false
  }

  const clickedCheckbox = [...checkboxes].find(c => c === e.target)
  clickedCheckbox.checked = true
})

We select the checkboxes with document.querySelectorAll.

Then we add a click listener to the body element with document.body.addEventListener.

In the click listener, we loop through the checkboxes with the for-of loop and set the checked property of all of them to false.

Then we find the checkbox that matches the one we clicked by spreading the checkboxes into an array and then use the find method and check which one matches the e.target.

e.target has the item that’s clicked.

Then finally, we set the checked property of the checkbox that matches to true.

Conclusion

To make checkbox behave like radio buttons with JavaScript, we can listen to the body element’s click listener.

And in the listener, we uncheck all the checkboxes and the check off the one that matches the one that’s clicked.

Categories
JavaScript Answers

How to remove values from select list based on condition with JavaScript?

Sometimes, we want to remove values from select list based on condition with JavaScript.

In this article, we’ll look at how to remove values from select list based on condition with JavaScript.

How to remove values from select list based on condition with JavaScript?

To remove values from select list based on condition with JavaScript, we can watch the selected value of the drop down.

Then we can remove the values accordingly.

For instance, we write:

<select>
  <option value="A">Apple</option>
  <option value="C">Cars</option>
  <option value="H">Honda</option>
  <option value="F">Fiat</option>
  <option value="I">Indigo</option>
</select>

to add a select drop down.

Then we write:

const select = document.querySelector("select");

select.addEventListener('change', () => {
  if (select.value === 'F') {
    const aIndex = [...select.options].findIndex(o => o.value === 'A')
    select.options.remove(aIndex);
    const cIndex = [...select.options].findIndex(o => o.value === 'C')
    select.options.remove(cIndex);
  }
})

We get the select element with document.querySelector.

Then we add a change event listener with addEventListener.

In the event listener, we check if select.value if 'F'.

If it is, then we get the ones that we want to remove by spreading the options into an array.

Then we call findIndex with a function that checks the value of the option to look for the index of the ones we want to remove.

Then we call select.options.remove to remove them.

Now when we select Fiat, we see that the Apple and Cars options are removed.

Conclusion

To remove values from select list based on condition with JavaScript, we can watch the selected value of the drop down.

Then we can remove the values accordingly.

Categories
JavaScript Answers

How to validate dates in format MM-DD-YYYY with JavaScript?

Sometimes, we want to validate dates in format MM-DD-YYYY with JavaScript.

In this article, we’ll look at how to validate dates in format MM-DD-YYYY with JavaScript.

How to validate dates in format MM-DD-YYYY with JavaScript?

To validate dates in format MM-DD-YYYY with JavaScript, we can use a regex to get the date parts.

And then we can compare the parts when we put them into the Date constructor to create a new date from them.

For instance, we write:

const isValidDate = (date) => {
  const matches = /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/.exec(date);
  if (matches === null) {
    return false;
  }
  const [_, m, d, y] = matches
  const composedDate = new Date(+y, +m - 1, +d);
  return composedDate.getDate() === +d &&
    composedDate.getMonth() === +m - 1 &&
    composedDate.getFullYear() === +y;
}
console.log(isValidDate('10-12-1961'));

We use the /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/ regex to extract the date parts with the exec method.

Then we destructure the matches and assign the month to m, day to d, and year to y.

Next, we create a new date object with the Date constructor with the date parts.

We’ve to subtract 1 from m to conform with with the Date constructor accepts as the month value.

Finally, we compare the date, month and year from the composedDate object with the values extracted from the regex.

We use the unary + operator to convert each value to numbers.

Therefore, the console log should log true.

Conclusion

To validate dates in format MM-DD-YYYY with JavaScript, we can use a regex to get the date parts.

And then we can compare the parts when we put them into the Date constructor to create a new date from them.

Categories
JavaScript Answers

How to add a dialog box with jQuery and make it show more than once?

Sometimes, we want to add a dialog box with jQuery and make it show more than once.

In this article, we’ll look at how to add a dialog box with jQuery and make it show more than once.

How to add a dialog box with jQuery and make it show more than once?

To add a dialog box with jQuery and make it show more than once, we can use the jQuery UI’s dialog method with the modal option set to true.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />

<button>
  show
</button>

<div id="dialog" title="Basic dialog">
  <p>hello world.</p>
</div>

We add the show button and a div for the dialog.

Then we write:

$(() => {
  $("#dialog").hide()

  $('button').click(() => {
    $("#dialog")
      .dialog({
        modal: true,
      })
  })
});

We select the dialog div with $("#dialog").

And we call hide on it to hide it initially.

Then we select the button with $('button').

And we call click on it with a callback that calls dialog with an object with modal set to true.

Now when we click the button, we see the dialog displayed. And we can close it with the ‘x’ button and click show to open it again.

Conclusion

To add a dialog box with jQuery and make it show more than once, we can use the jQuery UI’s dialog method with the modal option set to true.

Categories
JavaScript Answers Lodash

How to get duplicate values from an array with Lodash?

Sometimes, we want to get duplicate values from an array with Lodash.

In this article, we’ll look at how to get duplicate values from an array with Lodash.

How to get duplicate values from an array with Lodash?

To get duplicate values from an array with Lodash, we can use the filter and includes methods.

For instance, we write:

const arr = [1, 2, 2, 3, 3]
const dups = _.filter(arr, (val, i, iteratee) => _.includes(iteratee, val, i + 1));

console.log(dups)

We have an arr array that has some duplicate values.

Then we call filter with arr and a callback that calls includes to check if the array has the duplicate entries of val.

Therefore, dups is [2, 3].

Conclusion

To get duplicate values from an array with Lodash, we can use the filter and includes methods.