简体   繁体   中英

How to find dropdown's selected option's index/value using javascript, before the selection change

I am not sure if the title of my question is meaningful enough, so here is my problem : I have a dropdown dynamically generated from server side as below:

sb.append("<SELECT NAME='selectedQAStatuses' id='selectedReleaseQAStatuses' onchange='javascript:changeReleaseQAStatus(\""+releaseId+"\",\""+depEventSeq+"\",this);' >");
    sb.append("<OPTION>Please select a QA status...</OPTION>");
    for (String status : statusArray) {
        if(status.equals(releaseStatus))
            sb.append("<OPTION VALUE='"+status+"' selected>"+status+"</OPTION>");
        else
            sb.append("<OPTION VALUE='"+status+"'>"+status+"</OPTION>");

    }

Now javascript : changeReleaseQAStatus() is getting called. In this javascript method I am calling a confirm() to see if user is sure or not. If user selects "OK" in the confirm popup then from the "IF" block i make a Ajax call etc., but if user selects "Cancel" in the confirm popup, then from the "ELSE" block I return from the JS method.

However, in "Cancel" scenario i see that although the user seems to have "Cancelled" his selection, still on the browser screen the dropdown seems to show the new option as "selected". Therefore I think, in Javascript's "ELSE" block i should write something which should revert the selection to the original selection. How am I supposed to 'remember' what was the original value of the dropdown when the page had rendered on the browser, so that I can user this initial value in my 'ELSE' block to restore my dropdown.

My Javascript to handle 'OK' and 'CANCEL':

function changeReleaseQAStatus(releaseSeq, depEventSeq, element1){
    var selectedIndex   = element1.selectedIndex;
    var selectedStatus  = element1.options[selectedIndex].value;

    if (confirm("Do you want to change Release QA status to \"" + selectedStatus + "\" ?")){
        url = contextPath + "/changeQAStatusOfRelease.action?selectedStatus="+selectedStatus+"&releaseSeq="+releaseSeq+"&depEventSeq="+depEventSeq;
        ajaxUpdate({url:url,
           elementId:'compReleasesDtlsDiv',
        });
    }else{
        /// No Code needed to execute here...
    }
}

by using javascript you can use something like this

var arr = document.getElementsById('select_id');
alert(arr[0].options[arr[0].selectedIndex].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