Тёмный

JS Checkbox Challenge!  

Wes Bos
Подписаться 178 тыс.
Просмотров 30 тыс.
50% 1

Today we build a Gmail style interaction for holding shift while you select checkboxes. Grab all the exercises and starter files over at JavaScript30.com

Наука

Опубликовано:

 

29 авг 2017

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 87   
@uncleslo910
@uncleslo910 2 месяца назад
Thank you for all the effort you put into these videos.
@k3tna
@k3tna 4 года назад
Simply genius, Wes. Thanks! These flags can do some real magic with little code, and then you try to do it without the flag - it takes too much time and effort.
@SuprunAlexey
@SuprunAlexey 6 лет назад
Nice video, nice tutorials, nice channel! Thank you! Good luck!
@Suneriins234
@Suneriins234 4 года назад
I learn coding through fun and laughing in videos. I really enjoy it.
@moreshwardalavi
@moreshwardalavi 6 лет назад
really awesome tutorial, thank you ;)
@nepalcodetv6298
@nepalcodetv6298 6 лет назад
Love this series
@MolinaNilson
@MolinaNilson 6 лет назад
Really nice solution! There is a small bug where if you check a box, then uncheck it, then hold shift and click it again for a third time, all the boxes below it get checked as well. The way I fixed this was to simply add a check to confirm that the lastChecked is not the currently checked box. Before: if (e.shiftKey && this.checked) After : if (e.shiftKey && this.checked && lastChecked != this)
@vitfl2580
@vitfl2580 5 лет назад
There is also another bug, if you click on checkbox, then uncheck it, it will still remain as lastChecked and when you will click on another checkbox holding shift all checkboxes between them will be checked. The sollutions is quite simple: if (e.shiftKey && lastChecked.checked && this.checked && lastChecked != this) Here is a working example of my solution: codepen.io/vitfl/pen/aPMwGm
@yongjianbai5565
@yongjianbai5565 4 года назад
@@vitfl2580 Hey, bro. There is an error message in the console when you hold shift and click on the checkbox for the first click checkbox. The solution : let lastChecked = {checked: false};
@kirillvoloshin2065
@kirillvoloshin2065 4 года назад
I love how simple your code is! I tried to first generate a list, where each task had a data property (with its index: 0,1,2...). Get the indexes of previously clicked and current clicked checkboxes. Generate indexes between these checkboxes. And only then (having indexes of the checkboxes between) iterate through the array and change the state of a checkbox . Your tutorials are very good.
@pramodbhadana
@pramodbhadana 3 года назад
I did the exactly same thing as you. Wes's solution is really good.
@nazrulhassan6310
@nazrulhassan6310 5 лет назад
Forget trying I had a hard time wrapping my head around this code ,but it cleared lot of my concepts.
@perveenneha1423
@perveenneha1423 2 года назад
same here feels like banging my head on the wall. how did u clear the concepts tho
@talhaabbas1816
@talhaabbas1816 3 года назад
amazing man you rock!!!!
@aleksanderwalczuk6520
@aleksanderwalczuk6520 4 года назад
I retrieved first clicked element and the second, then just filtered the checkboxes array and set filtered items to the state of the first clicked element. So there's no trouble with lastChecked stored as let.
@NickSackman
@NickSackman 5 лет назад
A couple bugs in addition to the one Nilson listed: If you check a box, uncheck it, then hold shift and click somewhere else it will still check all in between. I fixed this by adding to the if statement: && lastChecked.checked). If you hold shift for the first box you check it will check all boxes below. This is fixed with my above solution but will throw an error because lastChecked is undefined on the first check. So I just assigned lastChecked to the first checkbox: let lastChecked = checkboxes[0];. You could also add a typeof if statement to check if lastChecked is undefined before the main if statement.
@migueldemaria3830
@migueldemaria3830 3 года назад
So much nicer than the way I figured out. I used one flag (counter = false) and looped over the checkboxes, but to do that I had to force the nodelist into an array: Array.from(checks). While there, I just set the counter to true the first checked box I found, checked the rest, until I came to one that wasn't checked, and then set the counter back to false and breaked. Pretty hacky, but it worked!
@yanneyesbreakers9220
@yanneyesbreakers9220 2 года назад
amazingly useful , thanks a lot
@sonyuinthesky
@sonyuinthesky Год назад
Not sure if this is a good solution but it works haha. 1. I kept track of shift-clicked item and last non-shift clicked item. 2. Used indOf on the input array to get their positions then used slice to return array of all items in between. 3. I then looped through the sliced array and just marked all items to "checked = true"
@LuisPintado
@LuisPintado 6 лет назад
you make it pretty easy and funny!! =)
@adzulfikarsr
@adzulfikarsr 6 лет назад
i need to know the intro songs
@slackergeek2007
@slackergeek2007 6 лет назад
Cool script. I find it nice that if I click a checkbox while holding SHIFT it will check all boxes below that. that gives a quick check all from a a given starting point. Now I need to mod the script to perform an uncheck range
@lukemeadows2223
@lukemeadows2223 5 лет назад
Did you manage to solve the uncheck problem? I tried checkbox.checked = !checkbox.checked but it unchecks the first box because its reversing its original state - Haha if that makes sense
@shivamgupta2842
@shivamgupta2842 6 лет назад
that's great logic applied
@MichaelImo
@MichaelImo 3 года назад
Now how can I set this up so that it can delete the check boxes that are checked and outside of the isbetween = true; valued dom.elements
@moritzhfm
@moritzhfm 4 года назад
yay ~ was able to solve this challenge by myself
@arpanbanerjee8584
@arpanbanerjee8584 4 года назад
If i use an arrow function for handle check then how can i assign the this variable? it points to the window object and not the checkbox checked
@danbuild977
@danbuild977 6 лет назад
Excellent Tutorial as always. Wish I could say I got it first time, but I was no where near. Please could you explain the lastChecked and this values on the checkboxes? I am not sure what set them apart.
@danbuild977
@danbuild977 6 лет назад
Nope all good watched it again and now I understand.
@kittyle7060
@kittyle7060 6 лет назад
Could you explain it to me?
@danbuild977
@danbuild977 6 лет назад
Yep sure, this = context of the function and relates to the first clicked checkbox in this scenario. lastChecked = The last checked checkbox by the users mouse click. The rest of the tutorial then goes onto explain how you tell the computer to only target and change the value of checkboxes inside of those two values. Let me know if you have any further questions on this. Also would recommend watching that part again.
@kittyle7060
@kittyle7060 6 лет назад
Okay thank you I think I get it (but I think It's the other way around 'this' refers to the one we are currently checking and 'lastChecked' refers to the first one we checked) but either way, thank you!
@danbuild977
@danbuild977 6 лет назад
Aha, you are a star! Yes indeed. I completely missed that. That way you can select an item at the bottom of the list, and still have the same effect if you select an item further up the list on the second click. The method he provides allows the Shift + Select feature to work both ways!
@TheJohnniePlays
@TheJohnniePlays 2 года назад
How does browser know which element is which when they all have the same content?
@sanajaveria3317
@sanajaveria3317 Год назад
I have a doubt, why do we write 'lastChecked=this' at the end of the 'handleCheck' function rather than in the beginning of the function?
@Darkurge666
@Darkurge666 6 лет назад
Can you explain if there is a reason why to use forEach instead of map?
@WesBos
@WesBos 6 лет назад
Good question - You use Map when you want to return a new, modified, array. You use foreach when you just wish to loop over an array or list of items.
@johongirrahimov8921
@johongirrahimov8921 5 лет назад
Coz in short forEach always returns undefined but map returns the new array as the length of the array it is called on for example if you call map method on array which has length of 4 it returns new array with the length of. so here he is not returning anything he just looping through to get his result. so
@KHANSOFFICIAL
@KHANSOFFICIAL 4 года назад
Plus map isn't available on a more list
@eotikurac
@eotikurac 5 лет назад
when you check one, and then another, and then uncheck one of them, hold shift and check one unchecked box. the last box that was unchecked gets checked again. i wanted to look for a solution but my head hurts i don't wanna play anymore.
@anokhps3088
@anokhps3088 Год назад
if(e.shiftKey&&this.checked&&lastChecked.checked) This can fix it
@spir1tfly
@spir1tfly 4 года назад
thank u
@greenworld7085
@greenworld7085 4 года назад
just wanna start by saying I'm a huge fan of yours. I took the challange before watching the solution part and turned out I found couple Bug/limitations in your finished code mentioned at bottom here. My solution didn't have those Bugs/limitations. here's what I did : hz-tyfoon.github.io/vanillaJsCheckMultipleCheckboxsByHoldingShiftKey/ here's the couple bug found in your solution: bug-1: if at the very first time a checkbox is checked while holding the shift button, then all the checkboxs from the bottom to that clicked item gets checked. bug-2: In gmail U can both check and also "uncheck" multiple checkbox by holding shift key but, in this code unchecking multiple "checked" item don't work. Again, Thanks a tonn for these videos. You're one of the best frontEnd teachers for me. Felt really excited after I finished this challenge on my own, that's why I shared it by commenting. Thanks again. Love from Bangladesh.
@whisperSSG8
@whisperSSG8 Год назад
Wow didnt know there was a way to do this without using indexes
@borsaniasushant1
@borsaniasushant1 5 лет назад
Why do we need to put lastChecked = this at last? If we put before if statement - why doesn't it work? Thanks
@luffymdh
@luffymdh 4 года назад
so that when u check the second box, the lastChecked will remain as the first checkbox until the foreach statement is ended
@anokhps3088
@anokhps3088 Год назад
Because we nee to store the firstchecked into a variable and should apply inbetween in between the firstchecked and the currently checkedone
@eugenekhristo7252
@eugenekhristo7252 6 лет назад
Nice. First of as you suggested I've implemented on my own. And then watched yours soltion. And I found a bug in this app. For example if you checked first one and after that check input below first one (a few times) (without Shift) - and after you checked AGAIN THIS CHECKBOX but with Shift - it will work out in some strange way. (Hope my poem is understandable).
@eugenekhristo7252
@eugenekhristo7252 6 лет назад
Mine solution of course is not so elegant, but it works without bugs (I guess) )) const $itemCheckboxes = document.querySelectorAll('.item input') let prevCheckedIndexBuffer = null let prevCheckedIndex = null document.querySelector('.inbox').addEventListener('click', e => { if(e.target.tagName !== 'INPUT') return if(!e.shiftKey) { if(e.target.checked) { prevCheckedIndexBuffer = prevCheckedIndex prevCheckedIndex = Array.from($itemCheckboxes).findIndex(item => item == e.target) } else { prevCheckedIndex = prevCheckedIndexBuffer } } else { const index = Array.from($itemCheckboxes).findIndex(item => item == e.target) const [minId, maxId] = [prevCheckedIndex, index].sort((a, b) => a - b) for(let i = minId; i
@khotambakhromov
@khotambakhromov 4 года назад
please, fix this bug
@trophydevice7624
@trophydevice7624 3 года назад
This is where I struggle the most. I understand the how and why, but as soon as I have to do it myself I struggle alot...
@hsenghaddar7337
@hsenghaddar7337 2 месяца назад
yes exactly how did u solve this problem
@johnylab
@johnylab 6 лет назад
I expected the last one would be unchecked! Why did it work?
@sridharbelide
@sridharbelide 6 лет назад
João Ferreira yes I too feel the same as for last one Boolean toggles and becomes false right?
@johnylab
@johnylab 6 лет назад
sridhar belide how come
@kriffos
@kriffos 6 лет назад
Why do you expect that? Nothing will ever be unchecked as (in line 126) checked is explicitly set to true.
@johnylab
@johnylab 6 лет назад
if it's still in between! oooh right
@sessonid5082
@sessonid5082 6 лет назад
Mah boi
@cloudalfakhre6931
@cloudalfakhre6931 2 года назад
it took me alot to get it
@baguette7869
@baguette7869 3 года назад
what IDE plugin is he using ?
@baguette7869
@baguette7869 3 года назад
I dont Know
@nikoladraskovic5857
@nikoladraskovic5857 4 года назад
Did anyone solve this on their own?
@Ludo045
@Ludo045 2 года назад
nop.
@MarcelRobitaille
@MarcelRobitaille 6 лет назад
Why not loop from the first checked index plus one to the second checked index minus one? It would be faster but more importantly better code imo. I try to avoid flags when possible.
@johnylab
@johnylab 6 лет назад
Marcel Robitaille you mean capture the indexes first?
@MarcelRobitaille
@MarcelRobitaille 6 лет назад
João Ferreira yeah. I think it makes for cleaner code rather than looping and checking each time.
@missgreendayfan
@missgreendayfan 6 лет назад
I did that!! But thought it wasn't as fast... As it is checking a box one at a time. I thought Wes' solution would be a better way in terms of performance. Hmmm...Here's my solution: codepen.io/Tubbie/live/rrYjZB Can you share yours too?
@YuvalBlass
@YuvalBlass 6 лет назад
What font is it?
@AjaySolleti
@AjaySolleti 6 лет назад
www.typography.com/fonts/operator/overview/
@WesBos
@WesBos 6 лет назад
I wrote a bit of info here → wesbos.com/uses
@saurabhlohiya6376
@saurabhlohiya6376 4 года назад
Uncaught TypeError: checkboxes.forEach is not a function Here's my code const checkboxes = $('.inbox input[type="checkbox"]'); function handleCheck(e) { console.log(e); } checkboxes.forEach(checkbox => { checkbox.on('click', handleCheck); }); Please explain me the bugg
@ccrsxx
@ccrsxx 2 года назад
const checkboxes = document.querySelectorAll('input'); let lastChecked; function handleMultipleChecked({ shiftKey }) { if (shiftKey && this.checked) { if (!lastChecked) lastChecked = -1; const [min, max] = [lastChecked, this.dataset.input].sort((a, b) => a - b); checkboxes.forEach((input, index) => { if (index > min && index < max) { input.checked = true; } }); } else { lastChecked = this.dataset.input; } } checkboxes.forEach((input) => { input.addEventListener('click', handleMultipleChecked); }); took me solid 30 minutes trying to solve it on my own.
@Ludo045
@Ludo045 2 года назад
you good. too bad, im not decent enough to be able to do this alone. For some reason javascript is so challenging for me.. it's less "mathematical" than java.
@ccrsxx
@ccrsxx 2 года назад
@@Ludo045 well, im gonna be honest, i already know javascript beforehand lol, i also already learn react (web framework). I just watch this series to know how vanilla js work.
@Ludo045
@Ludo045 2 года назад
@@ccrsxx Still learning and doing these challenge is still something.. I dont think I've been to do a single of these challenge until now.. from 1 to 11
@ccrsxx
@ccrsxx 2 года назад
@@Ludo045 Yeah, i think you shouldn't do any of these projects just yet, before knowing a basic understanding in javascript. I also struggle a lot when I did these project two weeks ago. This series is definitely for folks that are already know a basic of javascript.
@Ludo045
@Ludo045 2 года назад
@@ccrsxx What are these basic supposed to be ? 😅 I mean I think i did take them and understanding how their work, array, conditional structure, DOM, css, html etc.. Sure for now i cant do kickass html/css page, but i have no problem reading and understanding a code. 😅
@just_a_living_being
@just_a_living_being Год назад
const checkboxes = document.querySelectorAll('.inbox input[type="checkbox"]') checkboxes.forEach(checkBox => { checkBox.addEventListener('click', handleClick) }) let lastChecked function handleClick(e) { let inBetween = false if (e.shiftKey && this.checked && lastChecked) { checkboxes.forEach(checkbox => { if (this === checkbox || lastChecked === checkbox) { inBetween = !inBetween } if (inBetween) { checkbox.checked = true } }) } if (this.checked) { lastChecked = this } else { lastChecked = null } } some bug fixes to your code, It handle case when someone click on a checkbox with shift key and there no previous checked box
@rakibulshawonorib
@rakibulshawonorib 9 месяцев назад
wonderful. You solved that. Thank you for this one.
Далее
💜☀️✨
00:47
Просмотров 165 тыс.
아이스크림으로 체감되는 요즘 물가
00:16
Ajax Type Ahead with fetch() - #JavaScript30 6/30
17:22
100+ Linux Things you Need to Know
12:23
Просмотров 57 тыс.
Check / Uncheck All Checkboxes With Javascript
10:32
Просмотров 43 тыс.
Build this JS Digital Clock in 10 minutes! 🕐
10:48
Learn useMemo In 10 Minutes
10:42
Просмотров 468 тыс.
Get checkbox values with vanilla JavaScript
7:05
Просмотров 10 тыс.
All Select Checkbox in React JS - In Hindi
14:18
Просмотров 61 тыс.
YOTAPHONE 2 - СПУСТЯ 10 ЛЕТ
15:13
Просмотров 170 тыс.
Мои любимые Android смартфоны
0:55