developer tip

JavaScript로 옵션 텍스트 / 값 얻기

optionbox 2021. 1. 8. 08:09
반응형

JavaScript로 옵션 텍스트 / 값 얻기


답변 :var option_user_selection = element.options[element.selectedIndex].text

나는 사람의 명령을 채우는 양식을 작성하려고합니다.

<form name="food_select">
    <select name="maincourse" onchange="firstStep(this)">
        <option>- select -</option>
        <option text="breakfast">breakfast</option>
        <option text="lunch">lunch</option>
        <option text="dinner">dinner</option>
    </select>
</form>

내가하려는 것은 선택 개체를 보내고 옵션 메뉴에서 이름과 텍스트 / 값을 가져오고 옵션 태그의 데이터를 가져 오는 것입니다.

function firstStep(element) {
    //Grab information from input element object
    /and place them in local variables
    var select_name = element.name;
    var option_value = element.value;
}

이름과 옵션 값을 얻을 수 있지만 선택 개체에서 text = ""또는 value = ""를 얻을 수없는 것 같습니다. 사용자가 선택한 옵션 메뉴의 텍스트 / 값만 필요합니다. 배열로 배치 할 수 있다는 것을 알고 있지만 도움이되지 않습니다.

var option_user_selection = element.options[ whatever they select ].text 

또한 나머지 코드에서 설정되는 방식이므로 전달 된 선택 참조를 사용해야합니다.

나중에 해당 텍스트 / 값은 다음 선택 양식을 동적으로 채울 XML 문서를 가져 오는 데 사용됩니다.


당신이 사용할 수있는:

var option_user_selection = element.options[ element.selectedIndex ].text

jquery에서 이것을 시도 할 수 있습니다. $("#select_id>option:selected").text()


form.MySelect.options[form.MySelect.selectedIndex].value

var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text

참조 URL : https://stackoverflow.com/questions/4641962/getting-an-option-text-value-with-javascript

반응형