
もくじ
値の取得
値を1つだけ取得する
JS
var section_id = $('#select_section').val();
HTML(Laravel Brade)
<select class="form-control" id="select_section" name="section_id">
@foreach ($sections as $section)
<option value="{{ $section->section_id }}">{{ $section->section_name }}</option>
@endforeach
</select>
配列の値を取得
SELECTボックス
複数のSELECTボックスで選択されている同名クラスの値を取得する
var customer_ids = $('[name="customer_ids[]"] option:selected').map(function() {
return $(this).val();
}).get();
HTML
<select class="form-control" name="user_ids[]"></select>
Input
JS
var user_ids = $('input[name="user_ids[]"]').map(function() {
return $(this).val();
}).get();
HTML(Laravel Brade)
@foreach ($users as $user)
<input type="hidden" name="user_ids[]" value="{{ $user->user_id }}">
@endforeach
削除
HTML
<div id="input_staff_wrapper">
<div id="parent2">
<div id="parent1">
<div class="btn-ok">ボタン</div>
</div>
</div>
</div>
JS
$("#input_staff_wrapper").on('click', '.btn-ok', function () {
$(this).parent().parent().remove();
return false;
});
- parent2の範囲でまるっと消す
- $(this)はイベントが発生した要素を表す
- parent()を利用した削除
parent()は親要素を取得する
こうなる
<div id="input_staff_wrapper"> </div>
foreach
出力
配列dataからforeachで出力する
$.each(data, function(index, value) {
$(".section_users").append($("<option>").val(index).text(value));
})
配列から要素を複数して削除
指定する要素の配列を用意して対象の配列のキーを指定して削除を行う
foreachを利用してキーを指定して配列から要素を削除する
例) 配列dataから配列user_idsのuser_idのキーが一致するものをループで削除する
$.each(user_ids, function(index, user_id) {
delete data[user_id];
})


