I have a simple form with three textareas each with a different id. I want to be able to press the button and return the id of the textarea where I am typing in. Instead when I press the button I receive the id of the button which is button1:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
function printTagName() {
$("#p1").html($(":focus").attr("id"));
}
</script>
</head>
<body>
<form>
<textarea id="textarea1"></textarea>
<textarea id="textarea2"></textarea>
<textarea id="textarea3"></textarea>
</form>
<p id="p1"></p>
<button type="button" id="button1" onclick="printTagName()">Press</button>
</body>
</html>
How can I fix this problem?
When the button is clicked focus shifts to the button. Save the element when a textarea
receives focus, then print out the id
of the textarea
.
var focusElement = {};
$("textarea").focus(function(){
focusElement = this;
});
$("#button1").click(function(e){
e.preventDefault();
$("#p1").html(focusElement.id);
});
JS Fiddle: http://jsfiddle.net/ZYK7f/