简体   繁体   中英

How to activate text input on a button click in javascript

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.

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

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

This will work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM