Hàm :text Selector trong jQuery - JQuery API
Example $( "<input>" ).is( "[type=text]" ); // false $( "<input>" ).is( ":text" ); // true
Text Selector sẽ lựa chọn tất cả các phần tử có type="text".
Text Selector sẽ chọn tất cả các thẻ <input type="text">, cũng giống như các selector giả định khác(các selector bắt đầu bởi dấu ":") chúng nên được đặt trước bởi một tên thẻ hoặc một selector nào đó nếu không nó sẽ được hiểu là bộ chọn toàn bộ("*"). Nói cách khác $( ":text" ) sẽ tương đương với $( "*:text" ), do đó nên sử dụng $( "input:text" ) để thay thế.
Từ Jquery 1.5.2, :text sẽ lựa chọn cả những thẻ input không được thiết lập thuộc tính type. Sự khác nhau giữa $( ":text" ) và $( "[type=text]" ) như sau:
$( "<input>" ).is( "[type=text]" ); // false $( "<input>" ).is( ":text" ); // true
Chú ý: Bởi vì :text là một Jquery extension và không phải là một phần thiết lập của CSS, các truy vấn sử dụng :text sẽ không thể phát huy hiệu quả của phương thức querySelectorAll(). Để đạt được hiệu quả cao nhất, sử dụng [type="text"] để thay thế.
Ví dụ
Tìm kiếm các phần tử có type="text" và đổi màu cho chúng:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Học lập trình miễn phí tại Zaidap.com.net</title>
<script src="https://Zaidap.com.net/cnd/js/jquery/jquery-3.2.1.min.js"></script>
<style type="text/css">
td{
background: black;
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<h1>Học lập trình miễn phí tại Zaidap.com.net</h1>
<form>
<div>
password:<input type="password">
</div>
<hr>
<div>
radio1:<input type="radio" name="radio">
</div>
<div>
checkbox:<input type="checkbox">
</div>
<div>
radio3:<input type="radio" name="radio">
</div>
<hr>
<div>
reset:<input type="reset">
</div>
<hr>
<div>
submit:<input type="submit">
</div>
<hr>
<div>
text:<input type="text">
</div>
<hr>
<div>
not set type:<input>
</div>
<hr>
<div>
select:
<select>
<option>Option</option>
</select>
</div>
<hr>
<div>
textarea:<textarea></textarea>
</div>
<hr>
<div>
Button:<button>Button</button>
</div>
</form>
<hr>
<button onclick="myFunction()">Click vào đây để xem kết quả</button>
<script>
function myFunction(){
$( ":text" ).css("background", "red");
}
</script>
</body>
</html>Kết quả:
Tham khảo: jquery.com
Nguồn: Zaidap.com.net