简体   繁体   中英

javascript radio button return previous checked value

So I have this javascript code below. I am trying to make it so whenever the user hits cancel on the confirmation box. The previous selected option they have selected becomes reselected. Another option instead of the previous, is if we could have it select option 2 based on value ' A' instead of my current way of selecting option 2 based on the array of radio names.

<script type="text/javascript">
function confirmUnschedule() {
    var checked = false;
    var element = "";
    var inputs = document.getElementsByName('Acceptance');
        for (var i = 0; i < inputs.length; i++) {
          if (inputs[i].checked) {
           checked = true;
           element = inputs[i];
           break;
          }
        }   
    if(checked==true){
        if (!confirm('Scheduling will be undone if you change the rating. Are you Sure?')){
          inputs[1].checked=true;
        };
    };
   }
</script>

<input type='radio' name='Acceptance' value=' ' checked='checked' onclick='confirmUnschedule()'>option 1
<br/>
<input type='radio' name='Acceptance' value=' A' onclick='confirmUnschedule()'>option 2
<br/>
<input type='radio' name='Acceptance' value=' R' onclick='confirmUnschedule()'>option 3
<br/>

If you let your function return false, the event is aborted and the radio button group returns to previous state.

Edit: use return in the onclick attribute as well.

Html

<input type='radio' name='Acceptance' value=' ' checked='checked' onclick='return confirmUnschedule();'>option 1
<br/>
<input type='radio' name='Acceptance' value=' A' onclick='return confirmUnschedule();'>option 2
<br/>
<input type='radio' name='Acceptance' value=' R' onclick='return confirmUnschedule();'>option 3
<br/>

Javascript

function confirmUnschedule() {

    var checked = false;
    var element = "";
    var inputs = document.getElementsByName('Acceptance');

    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].checked) {
            checked = true;
            element = inputs[i];
            break;
        }
    }
    if (checked === true) {
        if (!confirm('Scheduling will be undone if you change the rating. Are you Sure?')) {
            return false;
        }
    }
}

jsFiddle = http://jsfiddle.net/ahsjoe0x/

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