0

I am a begginer in JavaScript and I have this problem: HTML code:

<textarea class="text_input" cols="40" rows="1" onclick="init_area();"></textarea>
<textarea class="text_input" cols="40" rows="1" onclick="init_area();"></textarea>

I want that when a user clicks on this textarea element to remove cols attribute for example. But only for the element that is clicked. I dont know how to do that. Can you help, please?

4
  • A tip: this in an eventhandler function refers to the element which an event has been attahed to. Commented Sep 4, 2015 at 15:10
  • @Teemu: But only if the event was bound using JavaScript. An onclick attribute is handled a little differently. I think he'd have to do: onclick="init_area(this);". I haven't used onclick attributes in forever since they are bad practice. Commented Sep 4, 2015 at 15:12
  • 1
    I tried : function init_area() { this.removeAttribute("cols"); } Commented Sep 4, 2015 at 15:13
  • @RocketHazmat You're right, with inline handlers this-value has to be passed (as well as event object). Commented Sep 4, 2015 at 15:13

3 Answers 3

1

You need to use this method : removeAttribute()

<textarea class="text_input" cols="40" rows="1" onclick="init_area();this.removeAttribute('cols'); "></textarea>
Sign up to request clarification or add additional context in comments.

Comments

0

try this.removeAttribute(cols) within your function - this refers to the element that the onclick event is attached to as long as init_area() is only called from your text area.

2 Comments

<textarea class="text_input" cols="40" rows="1" onclick="init_area(this);"></textarea> and the function function init_area() { this.removeAttribute(cols); } setTimeout(init_area,1000); But I get an error in the console Uncaught TypeError: this.removeAttribute is not a function I am lost
Your function doesn't take any arguments, use function init_area(el) {el.removeAttribute(...);}
0

HTML:

<textarea class="text_input" cols="40" rows="1" onclick="init_area(event);"></textarea>
<textarea class="text_input" cols="40" rows="1" onclick="init_area(event);"></textarea>

And in your JS file:

init_area = function(event) {
  event.target.removeAttribute("cols");
}

But you should try to remove the function call from the HTML Element and move it into the JS File:

yourElement.addEventListener(eventName, eventHandler);

https://developer.mozilla.org/en-US/docs/Web/Events/click

1 Comment

Thank you all for your answers. Solution for me to this was Kris solution. init_area = function(event) { event.target.removeAttribute("cols"); } I understand now how it works, and it work in Chrome. I didnt test it on other browser but thanks so much for your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.