anonymous2
anonymous2

Reputation: 89

Checkbox and input field value

I have a check box which will change the value of a textfield to 1 when checked and change it back to zero when unchecked, how can I do this? I want it in javascript.

Upvotes: 0

Views: 4194

Answers (4)

Sarfraz
Sarfraz

Reputation: 382686

You can do like this:

  var chk = document.getElementById('checkbox_id');
  var txt = document.getElementById('textbox_id');

  chk.onclick = function(){
    if (this.checked === true){
      txt.value = '1';
    }
    else{
      txt.value = '0';
    }
  };

Upvotes: 1

MatTheCat
MatTheCat

Reputation: 18721

<input type="checkbox" name="foo" onclick="document.getElementById('idtextfield').value = +this.checked;" />

Upvotes: 1

ArK
ArK

Reputation: 21068

  if(document.getElementById("checkbox1").checked)
  {
    document.getElementById('textbox1').value=1;
  }

  else
  {
    document.getElementById('textbox1').value='';
  }

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

window.onload = function() {
    var checkBox = document.getElementById('idofcheck');
    if (checkBox == null) {
        return;
    }

    checkBox.onclick = function() {
        var textField = document.getElementByd('ifoftextfield');
        if (textField == null) {
            return;
        }

        if (this.checked) {
            textField.value = '1';    
        } else {
            textField.value = '0';
        }
    };
};

Upvotes: 0

Related Questions