1

I'm trying to remember and modify values based on radio selections. If radio1 is selected, it should read value1 and value 2's values and save them as the data attribute "previous-value", and then set those values to either 0 or 1. If radio2 is selected, then value1 should be set to 0, and value2 should be set to the previous-value. However that is not happening, the previous-value data doesnt seem to be setting. I don't have any console errors. I'm wondering if setting the values and changing the values with the same action is causing an issue.

$('input[type="radio"]').click(function() {
var $value1 = $('#value1');
var $value2 = $('#value2');

if($(this).attr('id') == 'radio1') { 
  $value1.data('previousvalue', $value1.val());
  $value1.val('1');

  $value2.data('previousvalue', $value2.val());
  $value2.val('0');


} else if($(this).attr('id') == 'radio2') {      
  $value1.val('0');
  $value2.val($value2.data('previousvalue'));
}
});
  • 1
    http://jsfiddle.net/nz62pgwq/ Your script appears to do what you have written it to do. – Taplar Jun 18 '18 at 19:26
  • You may find [attr. vs prop.](https://stackoverflow.com/questions/5874652/prop-vs-attr) interesting. setting $.data(), is setting the dom property, and not the attribute value. You can check the latest value of the elements $.data(), it will be updated. – Sagar Jun 18 '18 at 23:51

1 Answers1

0

First you do a queryselectorAll so as to get all inputs type radio. It return a nodelist. After we do a loop of it with "for" and in that loop we do a condition "if" so as to verify if the radioButtons[i] is cheeked. And if its the case it show a message showing the selectedOne.

Try this code:

let radioButtons=document.querySelectorAll(input[type="radio"]); 
for(let i=0,c=radioButtons.length;i<c;i++){
    if(radioButtons[i].checked){
        alert("am the selectedOne "+radioButtons [i]);
      }
 }
JP. Aulet
  • 4,375
  • 4
  • 26
  • 39
Sidy Mbengue
  • 19
  • 1
  • 5
  • 2
    You should try to explain your answer and not just "code drop" -- If your answer does, in fact, solve the OP's issue .. Explain how, and why. – Zak Jun 18 '18 at 22:50
  • Ok first you do a queryselectorAll so as to get all inputs type radio. It return a nodelist. After we do a loop of it with "for" and in that loop we do a condition "if" so as to verify if the radioButtons[i] is cheeked. And if its the case it show a message showing the selectedOne – Sidy Mbengue Jun 19 '18 at 10:12