Reputation: 135
this is my code in index.blade.php
@foreach($sesis as $sesi)
<td>{{ $sesi->waktu }}
<label class="switch switch-text switch-info switch-pill" id="label-switch{{ $sesi->id }}">
<input type="checkbox" id="switch-sesi{{ $sesi->id }}" name="status" value="{{ $sesi->id }}" class="switch-input">
<span data-on="Ada!" data-off="Absen" class="switch-label"></span>
<span class="switch-handle"></span>
</label>
</td>
@endforeach
@foreach($sesis as $sesi)
$('#switch-sesi{{ $sesi->id }}').on('change', function(){
if($(this).is(":checked")){
console.log($(this).val());
}else{
console.log('tidak checked');
}
});
@endforeach
there is no problem with my code, but it looks like my code not efficient (see my jquery code). I'm trying to get id attributes from the input type checkbox with looping all the block code. I'm just wondering, is there anyway to efficient it ?
Upvotes: 0
Views: 63
Reputation: 6160
$(".switch-input").on("change",function(){
if($(this).is(":checked")){
alert($(this).val());
}else{
alert("Unchecked.");
}
});
input{
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="switch-input" value="A">
<input type="checkbox" class="switch-input" value="B">
<input type="checkbox" class="switch-input" value="C">
<input type="checkbox" class="switch-input" value="D">
<input type="checkbox" class="switch-input" value="E">
Since you already have the class switch-input in your input field (checkbox), you could just use that reference in your jquery instead of looping through them to add the event handler.
Instead of foreach, just have one;
$('.switch-input').on('change', function(){
if($(this).is(":checked")){
console.log($(this).val());
}else{
console.log('tidak checked');
}
});
Upvotes: 0
Reputation: 27051
You don't need to create the jquery for every element, you can use something like the id^=switch-sesi
to select all elements who's id
is starting with sesi
$('*[id^=switch-sesi]').on('change', function() {
if ($(this).is(":checked")) {
console.log($(this).val());
} else {
console.log('tidak checked');
}
});
Working demo
$('*[id^=switch-sesi]').on('change', function() {
if ($(this).is(":checked")) {
console.log($(this).val());
} else {
console.log('tidak checked');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td>
<label class="switch switch-text switch-info switch-pill" id="label-switch1">
<input type="checkbox" id="switch-sesi1" name="status" value="1" class="switch-input">
<span data-on="Ada!" data-off="Absen" class="switch-label"></span>
<span class="switch-handle"></span>
</label>
</td>
<td>
<label class="switch switch-text switch-info switch-pill" id="label-switch2">
<input type="checkbox" id="switch-sesi2" name="status" value="2" class="switch-input">
<span data-on="Ada!" data-off="Absen" class="switch-label"></span>
<span class="switch-handle"></span>
</label>
</td>
Upvotes: 1