Seb Joz
Seb Joz

Reputation: 19

Radio buttons returning final value in list

relatively new to both JS (apps script) and HTML

Please can you help- I have a form that is generally submitting perfectly (text boxes, date box) but the radio is always selecting the final value. Here is the HTML (bootstrap CSS, got from a template site) and JS to gather the data at the end-

  <div class="col-md-6"> 
<label class="radio-inline" for="ST0">
  <input type="radio" name="STRating" id="ST0" value="1">
  1
</label> 
<label class="radio-inline" for="ST1">
  <input type="radio" name="STRating" id="ST1" value="2">
  2
</label> 
<label class="radio-inline" for="ST2">
  <input type="radio" name="STRating" id="ST2" value="3" checked="checked">
  3
</label> 
<label class="radio-inline" for="ST S">
  <input type="radio" name="STRating" id="ST3" value="4">
  4
</label> 
<label class="radio-inline" for="ST4">
  <input type="radio" name="STRating" id="ST4" value="5">
  5
</label>

And the Apps script

 function testing143(){
var form = document.getElementById("myForm").elements;
var obj ={};
for(var i = 0 ; i < form.length ; i++){
    var item = form.item(i);
    obj[item.name] = item.value;
}
google.script.run.withSuccessHandler(success).testing143(obj);

Upvotes: 0

Views: 89

Answers (2)

Francesco M Donini
Francesco M Donini

Reputation: 21

All the five elements of the radio buttons share the same name, hence your code reassigns five times a value to obj['STRating'], and the last assignment (5) is what you get. Instead of doing the unconditional assignment

obj[item.name] = item.value;

You should condition the assignment only for the checked button, like that:

if (item.checked) obj[item.name] = item.value;

This way you still pass through all five buttons, but you memorize only the value of the checked one.

Upvotes: 2

Thobias
Thobias

Reputation: 21

You are using a named array and you have five elements with the same name "STRating". The last loop will set it to "5".

I think you need more like the selected value. More Infos: How to get the selected radio button’s value?

Upvotes: 1

Related Questions