开发者

clear value of text input if checkbox is checked restore value if unchecked using javascript

I have a text field with an image value populated from database. I need to have a checkbox that would clear value when checked and restore value when unchecked.

<input type="text" value="/images/sampleimage.jpg" />
Remove this image <input type="开发者_StackOverflow社区checkbox" name="remove">


Change HTML to :

<input type="text" value="/images/sampleimage.jpg" class="remove"/>

Remove this image <input type="checkbox" name="remove" class="handler">

And js: with jquery

$('.handler').click(function() {
      $('.remove').val("Replace by new value");
});


IE7 won't like this, and YES it's way easier with jQuery.

<input id="A" type="text" value="/images/sampleimage.jpg" />
Remove this image <input id="CHA" onclick="swapOut(this,'A')" type="checkbox" name="remove">

JS:

function swapOut(element,id) {
    target = document.getElementById(id)
        if(element.checked) {
             element.setAttribute('rel',target.value)
              target.value=''
        }
    else {
        target.value  = element.getAttribute('rel')
    }

} 


assumming your checkbox has an id of #check, and your input has an input of #input,

$('#check').change(function(){
  if($(this).is(':checked')){
     $('#input').val(,$('#input').data('previous_value'));
  } else {
     $('#input').data('previous_value',$('#input').val());  
  }
};

This will add an attribute named "data-previous_value" to your input, that holds the value while the checkbox is unchecked, and retrieves it into the input's value when checked.


here's a javascript solution (no jQuery required)

example jsfiddle

HTML:

<input id="imgInput" type="text" value="/images/sampleimage.jpg" />
Remove this image <input type="checkbox" id="remove" name="remove">

JS:

var imgInput = document.getElementById('imgInput'),
remove = document.getElementById('remove'),
val = imgInput.value;

remove.onchange = function() {
    if (this.checked) {
        imgInput.value = "";
    } else {
        imgInput.value = val;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜