3

I am trying to activate a text input using a button. My function is like this.

function showHide4()
{
 document.getElementById('snack').readOnly=false;
 document.getElementById('snack').style.backgroundColor"#ffffff";   
}

This function makes text input writable and changes background to white, but it gets activated only after I click on it.

Note:- My idea of activated text input is cursor(|) blinking in it. maybe activated is not a correct word for it but I don't know what else to call it.

EDIT:- I tried focus(), Problem in using focus() is Default value in my text input is getting selected automatically, which is not what I want, I want to put cursor(|) after that value.

1
  • 4
    it is called focus. .focus() Commented Aug 5, 2013 at 12:46

3 Answers 3

4

Try this, I think focus() is what you are looking for:

function showHide4() {
    var el = document.getElementById('snack');
    el.readOnly = false;
    el.style.backgroundColor = "#ffffff";
    el.focus();
    el.value = el.value;
};

To do what you want you need to cheat a bit, just reset (set again) the value of the input and it will work as you want.

DEMO HERE

Sign up to request clarification or add additional context in comments.

4 Comments

@AdityaPonkshe, great!
but the problem is value in the text input is getting selected automatically.
@AdityaPonkshe, did you see the demo?
my bad man didn't notice the link, and yes your demo is working which means i am doing something wrong
1
function showHide4()
{
 document.getElementById('snack').readOnly = false;
 document.getElementById('snack').style.backgroundColor = "#ffffff";  
 document.getElementById('snack').focus(); 
}

This will work!

1 Comment

See this post. I think this will help you to place cursor pointer at the end.
0

How to activate text input on a button click in React

This is how i did it using react.

export default function App() {
  function showHide4() {
    var el = document.getElementById("snack");
    el.style.backgroundColor = "#fdd";
    el.focus();
  }

  return (
    <div className="App">
      <input type="text" id="other" value="100" readonly="true" />
      <input type="text" id="snack" />

      <button type="button" onClick={showHide4} id="button">
        Click
      </button>
    </div>
  );
}

Comments

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.