开发者

How can i retrieve a fields name

I have a simple javascript function to check if a field is not empty:

function notEmpty( field , alert_text ){ 
if (field.val() === "" || 
    field.val() === null ||
    field.length === 0) {
    if ( alert_text ){
        alert ( 'Error: please enter some text - ' + alert_text );
    } // end if 
    field.addClass( 'hightlight' );
    fiel开发者_如何学God.focus();
    return false;
} // end if
else {
    field.removeClass('hightlight');
    return true;
} // end else

I want to get the name of field to show in the alert without using the alert_text argument. I tried a whole load of things, with no luck, so I've left the function as is and I'm using the alert_text argument to pass the field name. All my form input tags are something like this:

  <input    type=       "text" 
    name=       "artist" 
    id=     'artistfield' 
    size=       "60" 
    tabindex=   "1" />

So they all have 'name' defined. There must be a way to get it into my alert box but I can't figure it out yet. I'm sure it's easy, I'm just very new to this. Thanks.


You can retrieve the name with this:

field_name = field.attr('name');


You can use jQuery's attr() method to get the name (and almost any other HTML attribute):

function notEmpty(field) { 
    if (field.val() === "" || field.val() === null || field.length === 0) {
        if (field.attr('name')) {
            alert('Error: please enter some text - ' + field.attr('name'));
        }
        field.addClass('hightlight');
        field.focus();
        return false;
    } else {
        field.removeClass('hightlight');
        return true;
    }
}


You can use:

field.attr('name')

To get the name attribute from the field. You could change name for id if you wanted the fields ID for example.


To get the name-attribute of an element you can use the attr-function. It can get the value of any attribute.

Eg: http://jsfiddle.net/mqchen/LjFdC/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜