1

I need to get the values "trade" or "public" depending on which of these radio buttons is clicked:

<input name="customerType" type="radio" id="customerTypeTrade" class="filled-in valid" value="trade" required="">

<input name="customerType" type="radio" id="customerTypePublic" class="filled-in valid" value="public" checked="" required="">

Ive tried this but it returns 'undefined":

function() {
  var radioName = "customerType";
  var checked = {{Form Element}}.querySelector('[id="' + customerType + '"]:checked');
  return checked ? checked.value : undefined;
}
chappers
  • 466
  • 1
  • 6
  • 17
  • What's `{{Form Element}}`? Are you using angular? – j08691 Apr 18 '18 at 14:52
  • customerType isn't a variable -- you need to use the variable `radioName` which has your string "customerType" -- plus go line by line with your JS (`console.log()` is a huge help) -- (1) does the function get called? (2) does "{Form Element}" exist? (3) can you target your radio buttons (regardless if checked or not)? – Doug Apr 18 '18 at 14:52

1 Answers1

0

You can try the following way:

var radio = document.querySelectorAll('[name=customerType]');
var checkedValue = document.querySelector('[name=customerType]:checked').value;
console.log(checkedValue);

function getValue(thatRad){
  checkedValue = thatRad.checked ? thatRad.value : undefined;
  console.log(checkedValue);
}
<input name="customerType" type="radio" id="customerTypeTrade" class="filled-in valid" value="trade" required="" onchange="getValue(this)">

<input name="customerType" type="radio" id="customerTypePublic" class="filled-in valid" value="public" checked="" required="" onchange="getValue(this)">
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • I need this for Google Tag Manager. It says it needs a return value? – chappers Apr 18 '18 at 15:17
  • @chappers, then how do you attach the event handler function? – Mamun Apr 18 '18 at 15:21
  • I dont know as i dont know anything about javascript thats why i post on here. – chappers Apr 18 '18 at 15:33
  • @chappers, as I am not quite clear about your requirements and specially how you use the returned value it is difficult to answer the question exactly to the point. I have updated the answer to `return` the value from function to print that in `console`.....thanks. – Mamun Apr 18 '18 at 15:44
  • Sorted it: function() { var checked = document.querySelectorAll('[name=customerType]'); var checkedValue = document.querySelector('[name=customerType]:checked').value; if (checkedValue) return checkedValue; else return "customer not selected"; } – chappers Apr 18 '18 at 15:47