Setting radio button and checkbox in a form using JavaScript

[Hint: choose options from the second part(Get help deciding...) and press the 'Work out my Hosting Configuration' button]

Custom requirements for your web hosting account

Unix / Linux Windows Server 2003
MySQL Microsoft SQL Server Oracle

Get help deciding your hosting configuration by answering a few questions:

Yes
Yes No
Yes No

The code

function setHostingConfiguration(helperFormObj, targetFormObj) {
  var linux;
  var db_performance;
        var data_crucial;

  if(helperFormObj.linux_friendly.checked==true) {
    linux = true;
  } else {
    linux = false;
  }

  if(helperFormObj.db_performance[0].checked==true) {
    db_performance = true;
  } else {
    db_performance = false;
  }

  if(helperFormObj.data_crucial[0].checked==true) {
    data_crucial = true;
  } else {
    data_crucial = false;
  }

  if(linux) {
    targetFormObj.os[0].checked = true;
    if(db_performance) {
      targetFormObj.db[2].checked = true;
    } else {
      targetFormObj.db[0].checked = true;
    }
  } else {
    targetFormObj.os[1].checked = true;
    if(db_performance) {
      targetFormObj.db[2].checked = true;
    } else {
      targetFormObj.db[1].checked = true;
    }
  }

  if(data_crucial) {
    targetFormObj.backups_needed.checked = true;
  } else {
    targetFormObj.backups_needed.checked = false;
  }
}


function showHostingConfiguration(oForm) {
  var msg = "The data that you entered for the form with 'name' attribute='" + oForm.name + "': \n";
 
  for (i = 0; i < oForm.length, oForm.elements[i].getAttribute("type") !== 'button'; i++) {
    msg += oForm.elements[i].tagName + " with 'name' attribute='" + oForm.elements[i].name + "' and value attribute='" + oForm.elements[i].value + "': ";
    if(oForm.elements[i].checked == true) {
    msg += "checked \n";
    } else {
    msg += "not checked \n";
    }
  }

  alert(msg);
}

Download the code here: javascript-form-value-checkbox-example.zip

Back to article: set a form field using Javascript

  • Digg
  • del.icio.us
  • Netscape
  • Reddit
  • StumbleUpon
  • Technorati
  • YahooMyWeb

How to make a form without coding? Click here for a demo.

Follow me on twitter

HTML Forms
HTML Form Tutorial
The Form Tag
The Form Submit Button
Form design software
How to make a web form
Make web forms quickly, without coding

Javascript Form Handling
  Basics
Using getElementById to get the elements in a form
Set value of form element using JavaScript
Get value of form element using JavaScript
Handling multiple forms using JavaScript
JavaScript reset/clear a form
  Advanced
JavaScript Form Validation
Submitting a form using JavaScript
Can JavaScript Email a Form?
Switching the form action field dynamically
JavaScript Button

JavaScript Popup Windows
The window.open method
The window.close method
More ...

 
.   Copyright © 2003-2009 JavaScript-coder.com. All rights reserved.