简体   繁体   中英

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);

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM