jquery擷取選中的文本和值的方法,jquery擷取選中文本
1、說明
(1)擷取select下拉框選中的索引
$("#selection").get(0).selectedIndex;
(2)擷取select下拉框選中的值
$("#selection option:selected").val();
(3)擷取select下拉框選中的文本
$("#selection option:selected").text();
2、實現源碼
html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns="http://www.w3.org/1999/xhtml"> <HEAD> <script type="text/javascript" src="../Documents/未命名網站 2/jquery-1.11.0.js"></script> <script type="text/javascript"> $(function(){ $("#btn").click(function(){ //擷取select下拉框索引 var index = $("#selection").get(0).selectedIndex; //擷取select下拉框的值 var selectVal = $("#selection option:selected").val(); //擷取select下拉框的文本 var selectText = $("#selection option:selected").text(); alert("擷取select下拉框索引:" + index + "\n" + "擷取select下拉框的值:" + selectVal + "\n" + "擷取select下拉框的文本:" + selectText); }); }); </script> <DIV id=select_val> <SELECT id=selection> <OPTION selected value=0>鯉魚</OPTION> <OPTION value=1>鰩魚</OPTION> <OPTION value=2>鯰魚</OPTION> <OPTION value=3>棒棒魚</OPTION> <OPTION value=4>小姐魚</OPTION> <OPTION value=5>紅金花羅漢魚</OPTION> <OPTION value=6>彩虹王羅漢魚</OPTION> <OPTION value=7>泰金羅漢魚</OPTION></SELECT> </DIV> <INPUT id=btn value=擷取選中的文本和值 type=button>
3、實現結果
(1)選中第一項
(2)選中最後一項
用jquery怎擷取select元素中當前選擇的常值內容?(而不是選項的值)問怎寫
試一下這個把,我剛才試過了,可以的
var tt=$("form select[name=selectName]").find('option:selected').text();
alert(tt);
把selectName換成你表單中的下拉框name值就行了
要是使用ID查詢這樣就行了
var tt=$("#selectId").find('option:selected').text();就行
jquery擷取文字框中被選中的內容
<script>function GetSelectedText() { var selText = ""; if (window.getSelection) { // all browsers, except IE before version 9 if (document.activeElement && (document.activeElement.tagName.toLowerCase() == "textarea" || document.activeElement.tagName.toLowerCase() == "input")) { var text = document.activeElement.value; selText = text.substring(document.activeElement.selectionStart, document.activeElement.selectionEnd); } else { var selRange = window.getSelection(); selText = selRange.toString(); } } else { if (document.selection.createRange) { // Internet Explorer var range = document.selection.createRange(); selText = range.text; } } return selText;}function OnSelectInput(input) { selText = GetSelectedText(); alert("The contents of the current selection are\n" + selText);}</script><input size="40" value="Select a part of this text!" onselect="OnSelectInput (this)">來源: help.dottoro.com/ljmwkbaj.php