I am trying to get checkbox value using jQuery and put it in my table when submitting. The rest of jQuery code is perfectly working, but only checkbox part give me headache. I tried this one, but it does 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>
2
Answers
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:
Might I suggest adding data attributes to point to the targets and then do what you wish for those checked checkboxes targets. I also blanked the unchecked targets but you can build upon that.
I prevented the default of the submit button but you probably have these in a form and want to also prevent that here? Odd to have a submit type perhaps when you are changing the page.