Home > Net >  Stop Input From Inheriting Another Input's Value On Button Click
Stop Input From Inheriting Another Input's Value On Button Click

Time:09-08

I'm creating a post slug input, so when editing post title input it'll inherit it's value to the disabled slug input amd there is a button when clicking it enables the disabled input. It is working good, but I want on clicking the button it'll stop Inheriting values. Here is my code :

<input type="text" id="a"/>
<input type="text" id="b" disabled/>
<button id="btn">Stop</button>
<script>
    document.querySelector('#a').addEventListener('keyup', () => {
        document.querySelector('#b').value = document.querySelector('#a').value;
    });
    
    document.querySelector('#btn').addEventListener('click', () => {
        document.querySelector('#b').disabled = false;
    });
</script>

I've googled, but i haven't found.

Thank You

CodePudding user response:

You can removeEventListener of the a element keyup after clicking the button.

    function onAKeyup() {
        document.querySelector('#b').value = document.querySelector('#a').value;
    }
    
    document.querySelector('#a').addEventListener('keyup', onAKeyup);
    
    document.querySelector('#btn').addEventListener('click', () => {
        document.querySelector('#b').disabled = false;
        document.querySelector('#a').removeEventListener('keyup', onAKeyup)
    });
<input type="text" id="a"/>
<input type="text" id="b" disabled/>
<button id="btn">Stop</button>

  • Related