简体   繁体   中英

(DOM issue) not returning anything

I'm new to JavaScript and I was trying to manipulate the value of an HTML h2 element with the class of "text" when the users clicks on the button with the id "push" and change it to the value of the input class="inputV" , however i noticed that when there's no value in the input field the whole block just disappears so I tried to return a different value if the input is not true! so how do i go out about doing this! that's what I've tried so far.

    function input(){
    var inputValue= document.getElementById('inputV').value;
    var text = document.querySelector('.text').textContent;

    if (inputValue){
            text = inputValue;
            }else{
                text = 'Null';
        }
        return text;
    };

    document.getElementById('push').addEventListener('click',input);



    <div class=container><h1>JavaScript OOP</h1>
            <div>
                <form class="input">
                    <input id="inputV" type="text" name="name" placeholder="Enter your Name">
                </form>
            </div>
            <div><h2 class="text">Results</h2></div>
            <button id="push" value="Sign me in" onclick="input()">Sign me in</button>
        </div>

Initialization of text is not needed, just declare it.
Replace your return text with assignment to <h2> as below

function input(){
    var inputValue= document.getElementById('inputV').value;
    //var text = document.querySelector('.text').textContent;
    var text;

    if (inputValue){
        text = inputValue;
    }
    else{
        text = 'Null';
    }
    // return text;
    document.querySelector('.text').textContent = text;
}

document.getElementById('push').addEventListener('click',input);

Once you set onclick="input()" for the button you don't need to extra define an event listener. Also you can make the function body a bit shorter

 function input(){ var inputValue= document.getElementById('inputV').value; var text = document.querySelector('.text'); text.textContent = inputValue || 'Null'; }; // document.getElementById('push').addEventListener('click',input);
 <div class=container><h1 class="text">JavaScript OOP</h1> <div> <form class="input"> <input id="inputV" type="text" name="name" placeholder="Enter your Name"> </form> </div> <div><h2 class="text">Results</h2></div> <button id="push" value="Sign me in" onclick="input()">Sign me in</button> </div>

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