Rossitten
Rossitten

Reputation: 1166

change input type color wth js onclick

<script>
function valid() {
    document.getElementById("name").style.borderColor = "#ef0000";
}
</script>

<form method="post" action="">
<input type="text" name="name" id="name">
<input  type="submit" onclick="valid()" value="click">
</form>

why on earth this code doesn't work? I se eonly blick of red and the border is in its initial state again. I beg your pardon guys, really.I know it's a duplicate (I have even found at least one working solution here: http://jsfiddle.net/bcxLz4wh/ ) I jsut wanna know what's wrong with my code and why it returns to its initial state.

Upvotes: 0

Views: 166

Answers (1)

putvande
putvande

Reputation: 15213

It returns to it initial state because you are clicking on a submit button. It's default behaviour is to submit the form which refreshed the page. If you want to only change the border-color you need to override that default behaviour. Something like:

function valid(e) {
    document.getElementById("name").style.borderColor = "#ef0000";
    e.preventDefault();
}


<form method="post" action="">
    <input type="text" name="name" id="name">
    <input type="submit" onclick="valid(event)" value="click">
</form>

Upvotes: 5

Related Questions