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 th
What are you expecting $(this)
to refer to?
Do you mean sel.attr("id");
perhaps?
You can do
onchange='showHideOther.call(this);'
instead of
onchange='showHideOther(this);'
But then you also need to replace obj
with this
in the function.
In the function context "this" its not referring to the select element, but to the page itself
var ID = $(this).attr("id");
to var ID = $(obj).attr("id");
If obj is already a jQuery Object, just remove the $() around it.
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();
}
});
Because of the way the function is called (i.e. as a simple call to a function variable), this
is the global object (for which window
is an alias in browsers). Use the obj
parameter instead.
Also, creating a jQuery object and the using its attr()
method for obtaining an element ID is inefficient and unnecessary. Just use the element's id
property, which works in all browsers.
function showHideOther(obj){
var sel = obj.options[obj.selectedIndex].value;
var ID = obj.id;
if (sel == 'other') {
$(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
} else {
$(obj).css({'display' : 'none'});
}
}
Remove the inline event handler
and do it completly unobtrusive, like
$('#race').bind('change', function(){
var $this = $(this),
id = $this[0].id;
if(/^other$/.test($(this).val())){
$this.replaceWith($('<input/>', {
type: 'text',
name: id,
id: id
}));
}
});