In the past article, you have already learnt how to get a value from a check box using a JQuery and Javascript. You can check the article in here. Well in addition to that, I will show you how to get a value and text from a combo box or select dropdown input.
Let says we have the following combo box inputs with the following text and values.
We will create 4 different functions to get text and value of a combo box using Javascript and JQuery.
//Function scripts to get value/text using JQuery or Javascript <script text="tetxt/javascript"> function getTextUsingJavascript(){ var cbo = document.getElementById("cboItem"); alert("The selected text is " + cbo.options[cbo.selectedIndex].text); } function getValueUsingJavascript(){ var cbo = document.getElementById("cboItem"); alert("The selected value is " + cbo.options[cbo.selectedIndex].value); } function getTextUsingJQuery(){ alert("The selected text is " + $("#cboItem :selected").text()); } function getValueUsingJQuery(){ alert("The selected value is " + $("#cboItem").val()); } </script> <select id="cboItem"> <option value=''>Select Programming Language</option> <option value='1'>Javascript</option> <option value='2'>JQuery</option> <option value='3'>C#</option> <option value='4'>PHP</option> </select> <button id="btnGetTextJavascript" onclick="getTextUsingJavascript()">Get Text Using Javascript</button> <button id="btnGetValueJavascript" onclick="getValueUsingJavascript()">Get Value Using Javascript</button> <button id="btnGetTextJQuery" onclick="getTextUsingJQuery()">Get Text Using JQuery</button> <button id="btnGetValueJQuery" onclick="getValueUsingJQuery()">Get Value Using JQuery</button>
Pretty easy right? Hopefully it helps for newbie that just start learning JQuery and Javascript programming.