0

I have met issue while try get a default "no" value from checkbox when it is not "checked" on webpage. however, only the "yes" value pass to the form by name "testName" when I click the checkbox. But I want get result like a list of [yes,yes,no,no] from request.form.getlist

<form action="{{url_for('show_select')}}" method="post">
{% for entry in entries %}
    <tr>
      <td>
        <input name='testName' type='checkbox' onclick="checkboxtest();" value='No'>
     </td>
   </tr>
{%endfor %}
<div align="right">
<button type="submit" class="btn btn-primary">Go</button>
</div>
</form>

<script>
function checkboxtest(){
  var x = document.getElementsByName("testName");
  var i;
  for (i = 0; i < x.length; i++) {
    if (x[i].checked == true) {
      x[i].value = "Yes";}
  }
}
</script>

The_flash
  • 184
  • 1
  • 1
  • 11

2 Answers2

1

The checkbox value is only included in the form data if it is checked. Otherwise, it isn't included at all. Therefore, setting the value of "Yes" or "No" like you want isn't directly possible.

Wherever you are handling this form data, you should interpret a lack of value for the field as unchecked.

Brad
  • 159,648
  • 54
  • 349
  • 530
1

Work with the design of checkboxes (which is that checked ones are successful and unchecked ones are not) instead of trying to change them to send data in a different fashion.

Give each checkbox a unique value:

<fieldset>
    <legend> What pets do you like? </legend>

    <label><input type="checkbox" name="pet" value="cat"> Cats</label>
    <label><input type="checkbox" name="pet" value="dog"> Dogs</label>
    <label><input type="checkbox" name="pet" value="mouse"> Mice</label>
    <label><input type="checkbox" name="pet" value="rabbit"> Rabbits</label>
</fieldset>

and then look at the list of submitted values on the server.

You probably want to be using something like entry.id for the value in your example.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Hi Quentin, I got your point, thank you for your explanation. – The_flash Apr 16 '19 at 23:37
  • Actually, using this way can get default value. but only in first loop the function works. `code` `code` function checkboxtest1(){ if(document.getElementById("testName").checked) { document.getElementById('testNameHidden').disabled = true; } `code` – The_flash Apr 17 '19 at 00:05