DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on • Updated on

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.

Top comments (1)