-1

I am working on a form that gets placed inside of a system I have no control over. One stipulation of this system is that all of the Names and IDs must match.

This poses a problem with Radios since they have to have the same name in order to function, which in turn means they have to have the same ID.

Is there syntax that would allow me to access a specific radio button based on it's Value and ".disabled = true" it that way?

As these are the only 2 radios on the form I think maybe I can loop through the radio elements and use the counter variable to modify them.

Edit: I am dumb, both radios were getting disabled before submission preventing the system from saving the radio selection. So really all I need to do is disable the unchecked radio button after the verify button loses focus and the system should save the checked radio itself. I tried to use the elements loop and target the checked status to disable but it doesn't disable the unchecked radio it seems to clear them both.

Thanks and sorry,

 document.getElementById("btnVerify").onmouseleave = function(){
    var radios = document.getElementsByName('rbRadios');
    for (var r =0; r< radios.length; r++){
     //radios[r].disabled = true;
     if(radios[r].checked = false){
       radios[r].disabled = true;
     }
    }
  }  
  
  function enableButton(){
  document.getElementById("btnVerify").disabled=false;
 }
<input type="radio" name="rbRadios" id="rbRadios" value="Yes" onchange="enableButton()"> <label id="rbRadios">Yes</label>
<input type="radio" name="rbRadios" id="rbRadios" value="No" onchange="enableButton()"> <label id="rbRadios">No</label>

<button type="button" disabled id="btnVerify">Verify</button>
  • Radio buttons don't need same id, only same name works – Munim Munna Feb 01 '18 at 18:08
  • @Munim Munna I know that they only need the same ID typically, the system I am placing the form inside of requires all of the Name and IDs to match for it's own validation. – TheAngryAuditor Feb 01 '18 at 18:10
  • Post your code and specify what do you want to access. – Munim Munna Feb 01 '18 at 18:15
  • @Munim Munna I just have 2 radio buttons, and want to dynamically check them based on their value. I thought maybe I could try using a for loop and check them based on the loop counter variable. – TheAngryAuditor Feb 01 '18 at 18:46
  • Imo, as there can only be one radio button selected you don't need to select it by value. Try [this](https://stackoverflow.com/questions/596351/how-can-i-know-which-radio-button-is-selected-via-jquery) well accepted answer to select the selected radio button – Lukas Feb 01 '18 at 18:48
  • Yes you can loop like that. but why you need to select all of them? – Munim Munna Feb 01 '18 at 18:49
  • I don't know the system in that you are working, but in general it's a bad idea to have multiple elements with the same id – Lukas Feb 01 '18 at 18:50
  • @Munim Munna I am not trying to select all of them. I am trying to dynamically recheck the radio on form load based on what was previously selected by the user. The system won't save the radio button selection, but it will save a hidden field with the selected value. – TheAngryAuditor Feb 01 '18 at 18:58
  • @Lukas I know that it's not ideal, but it is what I am stuck with. I don't know anything about Jquery so I was trying to stick with JavaScript. – TheAngryAuditor Feb 01 '18 at 19:00
  • Is the code running at all after the form is reloaded? Maybe check that first by printing something with `console.log()` or `alert()` – Lukas Feb 01 '18 at 19:07
  • how can you check what was selected on form load if the system wont save the radio button selection? – Munim Munna Feb 01 '18 at 19:07
  • @Munim Munna I am dumb and the system will save radios. It was disabling both radios prior to the submission of the form preventing it from saving the selection. So I change my question to how to disable the unchecked radio. Sorry about that. – TheAngryAuditor Feb 01 '18 at 21:30
  • System does not disable radio buttons. only checked radio buttons and checkboxes are submitted in html form. – Munim Munna Feb 01 '18 at 21:33
  • @Lukas Yeah the code runs at reload because there is other code that works as intended that runs at the onload. I had to change my question because I didn't notice that the radios were being disabled prior to post and had to edit my question. – TheAngryAuditor Feb 01 '18 at 21:34

3 Answers3

0

You should attribute selector to select radio button by value and then use setAttribute method to check the radio button.

var value = "Yes";
document.querySelector('[name="rbRadio"][value="'+value+'"]').setAttribute('checked', 'checked');
<input type="radio" name="rbRadio" id="rbRadio" value="Yes">
<input type="radio" name="rbRadio" id="rbRadio" value="No">
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
0

If there is any way to avoid this, you should definitely rethink it. There are some strange rules in the spec around ids being unique, which come from from keeping backward compatibility with code from way back in the days of Mosaic browser. You can get some pretty wild bugs creeping in.

But as far as typical behavior of <input>s when aiming to use modern best-practice Javascript, this should get the job done:

Just use the checked attribute (and :checked pseudo-selector) as the main identifier to get a current value of a radio. And optionally add a data attribute if you need to be able to grab at a specific radio.

const nextArrayItem = list => x => {
  const nextI = list.indexOf(x) + 1
  return list[nextI] === undefined
    ? list[0] : list[nextI]
}

const radioIds = ['a', 'b', 'c']
const nextRadioId = nextArrayItem(radioIds)

const selectNext = () => {
  const myRadios = Array.from(
    document.querySelectorAll('input#radMyRadio'))
  
  const current = myRadios.find(r => r.checked === true)
  
  // Arbitrary data attribute used to hold a unique consistent
  // value we can use to identify specific radios.
  //
  const nextId = nextRadioId(current.dataset.id)
  const next = myRadios.find(r => r.dataset.id === nextId)
  next.checked = true
}

// Grab the current value from whichever radio is checked.
//
const updateText = () => {
  const textInput = document.querySelector('input#txtRadioVal')
  const currRadio = document.querySelector('input#radMyRadio:checked')
  textInput.value = currRadio.value
}

const form = document.querySelector('form')

// Form submission will overlook your slap-in-the-face to the spec
// and just grab whichever radio has both a `name` and `checked===true`.
//
form.addEventListener('submit', evt => {
  evt.preventDefault()
  const data = Array.from(new FormData(form))
    .reduce((json, entry) => (json[entry[0]] = entry[1], json), {})
  document.querySelector('pre').innerText = JSON.stringify(data, null, 4)
  
})

setInterval(() => {
  selectNext()
  updateText()
}, 2000)
/* Use checked pseudo-selector to find active radio */
input:checked + label {
  font-weight: bold;
}

/* arbitrary data attribute allows styling specific radios */
label[data-id=a] {
  color: blue;
}

label[data-id=b] {
  color: red;
}

label[data-id=c] {
  color: green;
}
<form>
  <div>
    <input type="radio" id="radMyRadio" name="radMyRadio" value="a" data-id="a" checked="true">
    <label for="myRadio" data-id="a">A</label>

    <input type="radio" id="radMyRadio" name="radMyRadio" value="b" data-id="b">
    <label for="myRadio" data-id="b">B</label>
    
    <input type="radio" id="radMyRadio" name="radMyRadio" value="c" data-id="c">
    <label for="myRadio" data-id="c">C</label>
  </div>
  <div>
    <input type="text" id="txtRadioVal" name="txtRadioVal" value="">
  </div>
  <div>
    <button type="submit">Submit</button>
  </div>
</form>

<div id="result">
  <p>Click Submit to show current form data as JSON.</p>
  <pre />
</div>
skylize
  • 1,401
  • 1
  • 9
  • 21
0

I was able to target the unchecked radio button and disable it using querySelector looking for unchecked radios. Thanks @Azim for getting me on the right track.

document.getElementById("btnVerify").onmouseleave = function() {
  document.getElementById('btnVerify').disabled = true;

  document.querySelector('input[name = "rbRadios"]:not(:checked)').disabled = true;
}

function enableButton() {
  document.getElementById("btnVerify").disabled = false;
}
<input type="radio" name="rbRadios" id="rbRadios" value="Yes" onchange="enableButton();">
<label id="rbRadios">Yes</label>
<input type="radio" name="rbRadios" id="rbRadios" value="No" onchange="enableButton();">
<label id="rbRadios">No</label>

<button type="button" disabled id="btnVerify">Verify</button>
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55