Wednesday, October 01, 2008

jQuery attributes selectors usage example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" charset="utf-8" src="/lib/jquery/jquery-1.2.6.js"></script>
</head>
<body>
<input name="milkman" />
<input name="letterman2" />
<input name="newmilk" />
<input name="newsletter" />
<input name="jobletter" />
<input name="jobletter2" />
<input id="man-news" name="man-news" />
<input id="letterman" name="new-letterman" />
<div>
<input type="radio" name="newsletter" value="Hot Fuzz" />
<span>name?</span>
</div>
<div>
<input type="radio" name="newsletter" value="Cold Fusion" />
<span>name?</span>
</div>
<div>
<input type="radio" name="accept" value="Evil Plans" />
<span>name?</span>
</div>
<div>no id</div>
<div id="hey">with id</div>
<div id="there">has an id</div>
<div>no id</div>

<script type="text/javascript" charset="utf-8">
// $("input[@name*='man']").val("has man in it!"); // the same below using XPath
$("input[name*='man']").val("has man in it!"); // attributeContains( String attribute, String value )
$("input[name^='news']").val("news here!");
$("input[name$='letter']").val("a letter"); // attributeEndsWith( String attribute, String value )
$("input[name='newsletter']").next().text(" is newsletter");
$("input[name!='newsletter']").next().text(" is not newsletter");

// one() function, The handler is executed only once for each element
$("div[id]").one("click", function(){
var idString = $(this).text() + " = " + $(this).attr("id");
$(this).text(idString);
});

$("input[id][name$='man']").val("only this one"); // Matches elements that have the specified attribute and it contains a certain value.
</script>
</body>
</html>

No comments :