I am trying to get checkbox value using JQuery and put it in my table when submitting. The rest of JQeury code is perfectly working, but only checkbox part give me headache. I tried this one, but it do not work
Yours suggestions, please.
Thanks in advance
// HTML
if ($('#screen_').is(":checked")) {
$('#screen_display').val();
} else if ($('#garantie').is(":checked")) {
$('#garantie_display').val();
} else if ($('#imprimante').is(":checked")) {
$('#printer_display').val();
} else if ($('#souris').is(":checked")) {
$('#mouse_display').val();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="checkbox" id="screen_" value="screen_" />
<label for="screen">Screen</label>
</div>
<div>
<input type="checkbox" id="garantie" value="garantie" />
<label for="garantie">Garantie</label><br>
</div>
<div>
<input type="checkbox" id="printer" value="printer" />
<label for="Printer">Printer</label><br>
</div>
<div>
<input type="checkbox" id="mouse" value="mouse" />
<label for="mouse">Mouse</label><br><br>
</div>
<hr><br>
<input type="submit" class="btn_commander" value="Commander">
<table id="Display">
<tr>
<td>1</td>
<td id="screen_display"></td>
<td></td>
</tr>
<tr>
<td>2</td>
<td id="garantie_display"></td>
<td></td>
</tr>
<tr>
<td>3</td>
<td id="printer_display"></td>
<td></td>
</tr>
<tr>
<td>4</td>
<td id="mouse_display"></td>
<td></td>
</tr>
>Solution :
Your code is checking if the input is checked in the starting. You need to check when the form is submitted. Secondly, you are not correctly updating the text of the table. Try this:
function submit(){
if ($('#screen_').is(":checked")) {
$('#screen_display').html($("#screen_").val());
}
if ($('#garantie').is(":checked")) {
$('#garantie_display').html($("#garantie").val());
}
if ($('#printer').is(":checked")) {
$('#printer_display').html($("#printer").val());
}
if ($('#mouse').is(":checked")) {
$('#mouse_display').html($("#mouse").val());
}
}
// changed else if to only if to check on all input clicks.
// fixed your ids since some were invalid
<div>
<input type="checkbox" id="screen_" value = "screen_" />
<label for="screen">Screen</label>
</div>
<div>
<input type="checkbox" id="garantie" value="garantie"/>
<label for="garantie">Garantie</label><br>
</div>
<div>
<input type="checkbox" id="printer" value="printer"/>
<label for="Printer">Printer</label><br>
</div>
<div>
<input type="checkbox" id="mouse" value="mouse"/>
<label for="mouse">Mouse</label><br><br>
</div>
<hr><br>
<input type="submit" class="btn_commander" onclick="submit()" value="Commander">
<table id="Display">
<tr>
<td>1</td>
<td id="screen_display"></td>
<td></td>
</tr>
<tr>
<td>2</td>
<td id="garantie_display"></td>
<td></td>
</tr>
<tr>
<td>3</td>
<td id="printer_display"></td>
<td></td>
</tr>
<tr>
<td>4</td>
<td id="mouse_display"></td>
<td></td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>