I need to change the class
of the input based on text value. When the value
is empty it should be default, when there is a value
it should change the class to inputtext
.
<style>
.inputnotext{ background:#ddd; }
.inputtext{ background:transparent } /* when their is text */
</style>
<form>
<input class="inputnotext" type="text" name="firstname" /><br />
<input class="inputnotext" type="text" name="lastname" />
</form>
<script>
/* script to write ??? */
</script>
I need to change the class
of the input based on text value. When the value
is empty it should be default, when there is a value
it should change the class to inputtext
.
<style>
.inputnotext{ background:#ddd; }
.inputtext{ background:transparent } /* when their is text */
</style>
<form>
<input class="inputnotext" type="text" name="firstname" /><br />
<input class="inputnotext" type="text" name="lastname" />
</form>
<script>
/* script to write ??? */
</script>
Share
Improve this question
edited Nov 29, 2011 at 10:25
Rory McCrossan
338k41 gold badges320 silver badges351 bronze badges
asked Nov 29, 2011 at 10:18
alexalex
1131 gold badge4 silver badges6 bronze badges
2
- 3 What have you tried so far? Stack Overflow is for help fixing errors and problems, not to write your code for you. – Rory McCrossan Commented Nov 29, 2011 at 10:25
- do you use jQuery or any other library? – Variant Commented Nov 29, 2011 at 10:26
3 Answers
Reset to default 3This is a javascript which you can use:
var input = document.getElementsByTagName('input');
keyupHandler = function(input){
if (input.value.length){
input.setAttribute('class', 'inputnotext');
}
else {
input.setAttribute('class', '');
}
}
for (i=0; i<input.length; i++){
input[i].onkeyup = function(){
keyupHandler(this);
}
input[i].onchange = function(){
keyupHandler(this);
}
}
jsFiddle example
Up-to-date version (using event listener and classList):
var input = document.getElementsByTagName('input');
input.addEventListener('keyup', (e) => {
e.target.classList.toggle("inputnotext", e.target.value );
});
jsFiddle example
Try the following code:
<style>
.inputnotext{ background:#ddd; }
.inputtext{ background:transparent } /* when their is text */
</style>
<form>
<input class="inputnotext" type="text" name="firstname" onblur="checkValue(this);"/><br />
<input class="inputnotext" type="text" name="lastname" onblur="checkValue(this);"/>
</form>
<script>
function checkValue(c){
var val = c.value;
var id = c.id;
if(val.length > 0){
document.getElementById(id).className += "inputtext";
}else{
document.getElementById(id).className += "inputnotext";
}
}
</script>
Hope it helps you :-)
You could do something like this using jQuery:
$(document).ready($(input:text[name=firstname]).change(function() {
var val = $(input:text[name=firstname]).val()
if(val!="")
{
$(input:text[name=firstname]).removeClass("inputnotext").addClass("inputtext");
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745675786a4639677.html
评论列表(0条)