DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on • Edited on

1 1

My Javascript note ( include JQuery )

Selector

Find by multi classes

<element class="a b">
Enter fullscreen mode Exit fullscreen mode
$('.a.b')
$('.b.a')
Enter fullscreen mode Exit fullscreen mode

Find the last element

<div id='hello'>
  <p class='world'>a</p/>
  <p class='world'>b</p/>
  <p class='world'>c</p/>
</div>
Enter fullscreen mode Exit fullscreen mode
$(#hello).find('.world:last')
// => c
Enter fullscreen mode Exit fullscreen mode

form

metaprogramming like form submit

Good for grecapcha call-back v2 workaround.

onSubmit = function(){
  const formName = $('.agreement').find('input').attr('name').split('[')[0]
  $(`form[id*=${formName}]`)submit();
}
Enter fullscreen mode Exit fullscreen mode

stop event bubbling

event.preventDefault();
Enter fullscreen mode Exit fullscreen mode

Manipulation

add/append a element

It appends hidden input that gives a param 'force_invalid'.

<form class="my-form">
</form>
Enter fullscreen mode Exit fullscreen mode
function invalid_submit(document) {
  $(document).append("<input name='force_invalid' value='1' type='hidden'></input>" );
  $(document).closest('form').submit();
}
Enter fullscreen mode Exit fullscreen mode

set a value

$('input[name="some_request[policy_agreement]"]').val("0");
Enter fullscreen mode Exit fullscreen mode

if checkbox is checked, open a panel

$.each($(".checkbox"), function(){
    // scope of 'this' is the checkbox
    if($(this).is(":checked")){
        $(this).closest("div").slideToggle("fast");
    }
});
Enter fullscreen mode Exit fullscreen mode

Tips

expression substitution inside a string literal. (式展開)

${} inside the backquote (`) substitute the expression.

const formName = 'my-form'
$(`form[id*=${formName}]`)submit();

$('form[id*=`formName`]').submit(); // ❌doesn't work
$('form[id*=formName]').submit();   // ❌doesn't work
Enter fullscreen mode Exit fullscreen mode

Uncaught Syntaxerror: Unexpected token u

It's same as console.log(JSON.parse(undefined));.
JSON.parse is actually undefined.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay