简体   繁体   中英

on change function in plain JavaScript

I've tried to make a function that fires on a change event, but nothing's working. Here's my code:

var PayContent = document.querySelectorAll('.details'); 

function OnChange() { 
         var webForm = document.getElementById('webFormWrap');
            webForm.onchange = function(){

              PayContent[0].style.display = "none";
              button.style.cursor = "default";

            document.getElementById('input_field').value = "";

            } 
//        });
    }

I've tried calling the function on load and within a set interval; also within the console as well.

Not entirely sure what you are hoping to accomplish here, especially since you didn't post any HTML, but this should get you close.

HTML:

<body>
    <div class="details" id="hideMe">This element will be hidden</div>
    <form id="webFormWrap" onchange="OnChange()">
        <input type="text">
    </form>
</body>

Notice that I added an id "hideMe" to the element you are trying to hide.

JavaScript (externally loaded)

function OnChange() { 
    var PayContent = document.querySelectorAll('div.details'); 

         document.getElementById(PayContent[0].id).style.display = "none";
         button.style.cursor = "default";

       document.getElementById('input_field').value = "";  
}

JavaScript doesn't require the use of "#" in query selectors.

You can't just call a function onchange and expect it to work. You have to add the event listener to the element. (I'm assuming you have it on a <form id="form"> element):

document.getElementById("form").addEventListener("change", OnChange);

This will add the change event to the element with ID of form .

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