Reputation:
I have a button/link like this
<a href='#' id='button-element'><span class='fa fa-comment' ></span></a>
Comment form like this
<form method="POST" id="comment_form">
....
<textarea name="comment_content" id="comment_content" class="form-control" rows="5"></textarea>
</form>
And I've added this JS so when I click on the button should go, focus and put border around the comment_content textarea.
var $code = $('#comment_content');
$('#button-element').on('mousedown', function () {
$(this).data('inputFocused', $code.is(":focus"));
}).click(function () {
if ($(this).data('inputFocused')) {
$code.blur();
} else {
$code.focus();
}
});
The problem is that I have multiple items with multiple comment buttons and the above solution works only when I click on the first item. If I click on other button it doesn't work.
Bellow is how it is working currently. What can be the problem?
var $code = $('#comment_content');
$('#button-element').on('mousedown', function () {
$(this).data('inputFocused', $code.is(":focus"));
}).click(function () {
if ($(this).data('inputFocused')) {
$code.blur();
} else {
$code.focus();
}
});
#comment_content:focus, #comment_content:active {
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href='#' id='button-element'><span class='fa fa-comment' ></span>Button 1</a>
<a href='#' id='button-element'><span class='fa fa-comment' ></span>Button 2</a>
<a href='#' id='button-element'><span class='fa fa-comment' ></span>Button 3</a>
<a href='#' id='button-element'><span class='fa fa-comment' ></span>Button 4</a>
<form method="POST" id="comment_form">
<textarea name="comment_content" id="comment_content" class="form-control" rows="5"></textarea>
</form>
Upvotes: 0
Views: 263
Reputation: 3205
id
must be unique in the document. You may use class
instead.
var $code = $('#comment_content');
$('.button-element').on('mousedown', function () {
$(this).data('inputFocused', $code.is(":focus"));
}).click(function () {
if ($(this).data('inputFocused')) {
$code.blur();
} else {
$code.focus();
}
});
#comment_content:focus, #comment_content:active {
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href='#' class='button-element'><span class='fa fa-comment' ></span>Button 1</a>
<a href='#' class='button-element'><span class='fa fa-comment' ></span>Button 2</a>
<a href='#' class='button-element'><span class='fa fa-comment' ></span>Button 3</a>
<a href='#' class='button-element'><span class='fa fa-comment' ></span>Button 4</a>
<form method="POST" id="comment_form">
<textarea name="comment_content" id="comment_content" class="form-control" rows="5"></textarea>
</form>
Upvotes: 1