Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(this).attr("id") not working

as the title says, I keep getting "undefined" when I try to get the id attribute of an element, basically what I want to do is replace an element with an input box when the value is "other".

Here is the code:

function showHideOther(obj) {
    var sel = obj.options[obj.selectedIndex].value;
    var ID = $(this).attr("id");
    alert(ID);

    if (sel == 'other') {
        $(this).html("<input type='text' name='" + ID + "' id='" + ID + "' />");

    } else {
        $(this).css({
            'display': 'none'
        });
    }
}

The HTML:

          <span class='left'><label for='race'>Race: </label></span>
          <span class='right'><select name='race' id='race' onchange='showHideOther(this);'>
            <option>Select one</option>
            <option>one</option>
            <option>two</option>
            <option>three</option>
            <option value="other">Other</option>
          </select>
          </span>

It is probably something small that I am not noticing, what am I doing wrong?

like image 369
Odyss3us Avatar asked Jul 27 '10 07:07

Odyss3us


People also ask

How can use attr ID in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element. The following example will display the ID of the DIV element in an alert box on button click.

What is the use of ID attribute in HTML?

The id attribute specifies a unique id for an HTML element. The value of the id attribute must be unique within the HTML document. The id attribute is used to point to a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specific id.


2 Answers

Change

var ID = $(this).attr("id");

to

var ID = $(obj).attr("id");

Also you can change it to use jQuery event handler:

$('#race').change(function() {
    var select = $(this);
    var id = select.attr('id');
    if(select.val() == 'other') {
        select.replaceWith("<input type='text' name='" + id + "' id='" + id + "' />");
    } else {
        select.hide();
    }
});
like image 118
fantactuka Avatar answered Oct 30 '22 23:10

fantactuka


your using this in a function, when you should be using the parameter.

You only use $(this) in callbacks... from selections like

$('a').click(function() {
   alert($(this).href);
})

In closing, the proper way (using your code example) would be to do this

obj.attr('id');

like image 39
dockeryZ Avatar answered Oct 30 '22 21:10

dockeryZ