Select all inputs text from body with JQuery
I just want to get all the <input type="text"></input>
from the body of the html.
So far I have this:
function toUpper() {
var elements = $("body input:text");
for(var i=0; i<elements.lenght; i++){
elements[i].val(elements[i].val().toUpperCase());
}
}
But it doesn't work... I might be missing something on the JQuery S开发者_JAVA百科elector... But I don't know what.
Thank you!
function toUpper() {
$("input:text").val(function(i, val) {
return val.toUpperCase();
});
}
This is probably more convenient.
Demo: http://www.jsfiddle.net/4yUqL/85/
$("body input:text").each(function(){
$(this).val($(this).val().toUpperCase());
});
Your selector is fine, although the body
part is a bit unnecessary (I hope you don't have any input
s outside of the body).
But the rest is problematic. When you index a jquery object, you get the actual HtmlInputElement
(or whatever) object, not a jquery wrapper around that object. So you can't use the jquery .val()
command without first turning it into a jquery object. Here's a corrected version of your current code:
var elements = $("input:text");
for(var i = 0; i< elements.length; i++)
$(elements[i]).val($(elements[i]).val().toUpperCase());
But the functional approach suggested by jAndy is a much cleaner way of doing it.
精彩评论