Im trying to figure out how can Javascript check if input field has any value, then it removes class value "is-invalid".
I have this code so far:
<form>
<label for="inputName">Username</label>
<input type="text" class="is-invalid" id="inputName">
</form>
<script>
var checkInput = document.getElementById("inputName");
if (checkInput.value) {
element.classList.remove("is-invalid");
}
</script>
As you can see theres a red border (class="is-invalid") around the input. As soon as user puts any value in the inputfield, Javascript will remove class value "is-invalid".
Or might there be an easier option with jQuery?
You have a mistake in your code. You have used
element.classList.remove("is-invalid");
which is wrong, you have to use it like
checkInput.classList.remove("is-invalid");
You can use like this in javascript.
function check(){ var checkInput = document.getElementById("inputName"); if (checkInput.value) { checkInput.classList.remove("is-invalid"); } else { checkInput.classList.add("is-invalid"); } }
<form> <label for="inputName">Username</label> <input type="text" class="is-invalid" id="inputName" onkeyup="check()"> </form>
In Jquery you can try like
$('#inputName').keyup(function(e){ if ($('#inputName').val()) { $('#inputName').removeClass("is-invalid"); } else { $('#inputName').addClass("is-invalid"); } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <label for="inputName">Username</label> <input type="text" class="is-invalid" id="inputName"> </form>
You need to add an event listener to the element to know when it changes.
var checkInput = document.getElementById("inputName");
checkInput.addEventListener('keyup', (e)=>{
if (e.target.value!==''){
e.target.classList.remove("is-invalid");
}
})
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.