-1

I can't figure out how the size of the form can be determined with javascript, and how to change it. I've tried element.style.width but that isn't doing it either for reading or writing. I don't know what I'm looking for in the debugger either. I need to change the width of the form depending on the length of the text in the newNameNode text node.

Thanks very much for any help.

Gerard

Here's my code -

<form name="Q1"  autocomplete="off">
<fieldset>
<legend>1</legend>
Ludwig Van Beethoven<br />
<input type="radio" name="Q1" value="1756-1819"><span>1756-1819</span><br>
<input type="radio" name="Q1" value="1770-1827,Beethoven,correct"><span> 1770-1827</span><br />
<input type="radio" name="Q1" value="1815-1858"><span> 1815-1858</span><br />
<input type="radio" name="Q1" value="1832-1870"><span> 1832-1870</span>
</fieldset>
</form> 

<script >
function buildForm() {

var newForm = document.createElement('form');
    newForm.name = "Q1";
    newForm.autocomplete = "off";

var newFieldset = document.createElement('fieldset');

var newNameNode = document.createTextNode('new text');
var br = document.createElement('br');
var newRadio = document.createElement('input');
    newRadio.type = 'radio';
    newRadio.name = 'Q1';
    newRadio.value = "new value";
var dates ="1770-1827";         
var newDateSpan = document.createElement('span');       
    newDateSpan.innerHTML = " " + dates + "<br />";
    console.log("newSpan.innerHTML: " + newDateSpan.innerHTML); //!!

var newLegend = document.createElement('legend');
    newLegend.innerHTML = newRadio.name;

newFieldset.appendChild(newLegend); 
newFieldset.appendChild(newNameNode);
newFieldset.appendChild(br);
newFieldset.appendChild(newRadio);
newFieldset.appendChild(newDateSpan);
newForm.appendChild(newFieldset);
document.body.appendChild(newForm);     
}
buildForm();
</script></body>
</html>

1 Answer 1

0

To determine the height/width, what you're looking for is Element.scrollHeight or Element.scrollWidth

You can set the width from the CSS (this is the better option), or by DOM manipulation in Javascript, as follows:

  var forms = document.querySelectorAll('form');
  for (var i = 0; i < forms.length; i++) {
      forms[i].style.width = 250 + 'px';//sets the width of all forms to 250px
  }
2
  • That's great, thanks. Those are read-only, what attribute would I need to write to in order to change them?
    – Gerard
    Jul 18, 2015 at 19:53
  • Excellent, thanks! I have a follow-up question. Is it generally better to put something like a form inside a div and change the div's width instead of the form's?
    – Gerard
    Jul 19, 2015 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.