changing HTML form with javascript - javascript

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>

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
}

Related

How to include check all box in html sidebar

I have the following code for generating checkboxes in a Google Docs sidebar:
for( var i = 0;i < values.length; i ++)
{
var cb = document.createElement( "input" );
cb.type = "checkbox";
cb.id = values[i][1];
cb.value = values[i][0];
var text = document.createTextNode( values[i][0].substring(0, 30) );
var br = document.createElement('br');
document.getElementById( 'class_list' ).appendChild( cb );
document.getElementById( 'class_list' ).appendChild( text );
document.getElementById( 'class_list' ).appendChild( br );
}
Is there a way to include a check all box at the top of this list and then pass all of the selected values and ids to another function?
Here is the HTML and client side JavaScript that will do what you want:
<div class="inputFormElement"><!-- Beginning of input -->
<button onmouseup="checkAllBoxes()">Select All</button>
<br>
<br>
<div class="chkBoxListElement">
<input type="checkbox" id="idOne" value="1">One<br>
<input type="checkbox" id="idTwo" value="2">Two<br>
<input type="checkbox" id="idThree" value="3">Three<br>
<input type="checkbox" id="idFour" value="4">Four<br>
<input type="checkbox" id="idFive" value="5">Five<br>
<input type="checkbox" id="idSix" value="6">Six<br>
</div>
</div><!-- End of input -->
<script>
window.checkAllBoxes = function() {
var allCheckBoxes,dataAsString,elementHoldingChkBoxes,i,L,objectOfData,thisChkBox,thisID;
objectOfData = {};
elementHoldingChkBoxes = document.getElementsByClassName('chkBoxListElement')[0];
console.log('elementHoldingChkBoxes: ' + elementHoldingChkBoxes)
console.log('typeof elementHoldingChkBoxes: ' + typeof elementHoldingChkBoxes)
allCheckBoxes = elementHoldingChkBoxes.getElementsByTagName('input');//Get all inputs
L = allCheckBoxes.length;
for (i=0;i<L;i++) {
thisChkBox = allCheckBoxes[i];//Get this check box
if (thisChkBox) {//Not null, undefined or empty string - truthy
thisChkBox.checked = true;
thisID = thisChkBox.id;
objectOfData[thisID] = thisChkBox.value;
}
}
dataAsString = JSON.stringify(objectOfData);//Convert object to a string
console.log('dataAsString: ' + dataAsString)
mySecondFunction(objectOfData);
}
window.mySecondFunction = function(data) {
console.log(data)
}
</script>
If you want the input boxes to dynamically change whenever the sidebar is loaded, some code will be needed to build the HTML. But that is another question.

Nn algorithm that divides a single number three times Javascript

I'm trying to create an algorithm that divides a single number three times.
I've created this code, but it for some reason it doesn't work and I've got no clue why.
Could some one give me insight into what i'm doing wrong?
HTML
<form id="frm1">
Budget: <input id="budget" type="text" name="budget" value="110"><br>
<br>
Domestic:
<input id="low" type="text" name="low" value="20">%<br>
<input id="lowresult" type="text" name="low" oninput="calculate()"><br>
Continental:
<input id="med" type="text" name="med" value="30">% <br>
<input id="medresult" type="text" name="med" oninput="calculate()"><br>
International:
<input id="high" type="text" name="high" value="50">% <br>
<input id="highresult" type="text" name="high" oninput="calculate()"><br>
<br>
</form>
Javascript
function calculate() {
var budget = document.getElementById("budget").value;
var low = document.getElementById('low').value;
var med = document.getElementById('med').value;
var high = document.getElementById('high').value;
var lowResult = document.getElementById('lowresult');
var medResult = document.getElementById('medresult');
var highResult = document.getElementById('highresult');
var lowFinalResult = (budget /100)*low;
lowResult.value = lowResult;
var medFinalResult = (budget /100)*med;
medResult.value = medResult;
var highFinalResult = (budget /100)*high;
highResult.value = highResult;
}
adjust javascript
this
var lowFinalResult = (budget /100)*low;
lowResult.value = lowFinalResult;
insetad of
var lowFinalResult = (budget /100)*low;
lowResult.value = lowResult;
full code
function calculate() {
var budget = document.getElementById("budget").value;
var low = document.getElementById('low').value;
var med = document.getElementById('med').value;
var high = document.getElementById('high').value;
var lowResult = document.getElementById('lowresult');
var medResult = document.getElementById('medresult');
var highResult = document.getElementById('highresult');
var lowFinalResult = (budget /100)*low;
lowResult.value = lowFinalResult;
var medFinalResult = (budget /100)*med;
medResult.value = medFinalResult;
var highFinalResult = (budget /100)*high;
highResult.value = highFinalResult;
}
You wrote in the comment that you're "trying to input one amount into the 'budget' input". So I'd like to add that you do that calculate() in the budget input:
<form id="frm1">
Budget: <input id="budget" type="text" name="budget"
value="110" oninput="calculate()"><br>
So the oninput attribute of the other inputs can be removed.

Why won't .trim() work with me?

I'm having trouble getting this bit of javascript to work. Whenever I try it inputs nothing into my div. It just adds ?weight=NumberInputed&measure=lbsOrkgs&submit=Submit to the URL.
<h2>How small must you be to become a black hole?</h2>
<form name="form1">
<input id="howMuch" type="number" name="weight" placeholder="How much do you weigh?">
<input type="radio" name="measure" value="lbs" checked="true">lbs
<input type="radio" name="measure" value="kgs">kgs
<input type="submit" name="submit" value="Submit" onClick="calc(); return false;">
</form>
<br/>
<div id="insert"><div/>
<script language="JavaScript" type="Text/JavaScript">
function calc() {
var speedOfLight = 299792458.0;
var gravityConstantYoctometre = 66738400000000.0;
var finalHeight = 0.0;
var weight = document.form1.weight.value;
var measure = document.form1.measure.value;
measure = measure.trim();
if (measure !== "kgs"){
weight *= 0.4536;
}
finalHeight = (4.0 * gravityConstantYoctometre * weight)/Math.pow(speedOfLight,2);
finalHeight = (finalHeight).toFixed(5);
var message = '<em>You would have to be ' + finalHeight + ' yoctometres (1 metre x 10<sup>-24</sup>) tall before you would become a black hole.</em>';
document.getElementById('insert').innerHTML = message;
}
</script>
Without the .trim() function, it executes perfectly, except for the fact that it will not recognize measure equaling anything resembling 'lbs' or 'kgs'. What is happening here?
Here: http://jsfiddle.net/dJJjr/1/
function calc() {
var speedOfLight = 299792458.0;
var gravityConstantYoctometre = 66738400000000.0;
var finalHeight = 0.0;
var weight = document.getElementById("howMuch").value;
var radio = document.getElementsByName('measure');
var measure = ""
for(var i =0; i< radio.length; i++)
{
if(radio[i].checked)
measure = radio[i].value;
}
measure = measure.trim();
alert(measure); //For testing purpose
alert(weight); //For testing purpose
if (measure !== "kgs"){
weight *= 0.4536;
}
finalHeight = (4.0 * gravityConstantYoctometre * weight)/Math.pow(speedOfLight,2);
finalHeight = (finalHeight).toFixed(5);
var message = '<em>You would have to be ' + finalHeight + ' yoctometres (1 metre x 10<sup>-24</sup>) tall before you would become a black hole.</em>';
document.getElementById('insert').innerHTML = message;
}

Getting error "Unexpected Token" in HTML DOM script for a HTML form

I'm developing an android app with phonegap. I'm trying to use an HTML form in one of the pages and I've been told that I should use HTML DOM. I've made the script but I got a error saying: Unexpected token.
Here's the sample code in HTML:
<form name="editNoteForm" id="formaltera" method="post" action="index.html">
<div data-role="fieldcontain">
<label for="primeiroNome">Primeiro Nome</label>
<input type="text" name="primeiroNome" id="primeiroNome">
</div>
<div data-role="fieldcontain">
<label for="ultimoNome">Ultimo Nome</label>
<input type="text" name="ultimoNome" id="ultimoNome">
</div>
<div data-role="fieldcontain">
<label for="numeroTelefone">Telefone</label>
<input type="number" name="numeroTelefone" id="numeroTelefone">
</div>
<div data-role="fieldcontain">
<input type="submit" id="submit" value="Guardar">
</div>
</form>
And here's the script I made so I can get something like the HTML code above.
<form name="formaltera" id="formaltera" method="post" action="index.html"></form>
<script charset="utf-8" language="javascript">
var temp1 = localStorage.getItem("selected");
var temp = localStorage.getItem(temp1);
temp = temp.split(";");
var firstName = temp[0];
var lastName = temp[1];
var phoneNumber = temp[2];
var form = document.getElementById('formaltera');
var formBody = form.childNodes[0];
var div = document.createElement('div');
var inputTextA = document.createElement('input');
var inputTextB = document.createElement('input');
var inputTextC = document.createElement('input');
var inputSubmit = document.createElement('input');
var labelA = document.createElement('label');
var labelB = document.createElement('label');
var labelC = document.createElement('label');
var labelTextA = document.createTextNode('Primeiro Nome');
var labelTextB = document.createTextNode('Ultimo Nome');
var labelTextC = document.createTextNode('Telefone');
div.data-role = "fieldcontain";
labelA.for = "primeiroNome"; //I'm getting an error in here
labelB.for = "ultimoNome";
labelC.for = "numeroTelefone";
inputTextA.type = "text";
inputTextA.name = "primeiroNome";
inputTextA.id = "primeiroNome";
inputTextA.value = firstName;
inputTextB.type = "text";
inputTextB.name = "ultimoNome";
inputTextB.id = "ultimoNome";
inputTextB.value = lastName;
inputTextC.type = "number";
inputTextC.name = "numeroTelefone";
inputTextC.id = "numeroTelefone";
inputTextC.value = phoneNumber;
inputSubmit.type = "submit";
inputSubmit.name = "submit";
inputSubmit.id = "submit";
inputSubmit.value = "Guardar";
form.appendChild(div);
div.appendChild(labelA);
labelA.appendChild(labelTextA);
div.appendChild(inputTextA);
form.appendChild(div);
div.appendChild(labelB);
labelA.appendChild(labelTextB);
div.appendChild(inputTextB);
form.appendChild(div);
div.appendChild(labelC);
labelA.appendChild(labelTextC);
div.appendChild(inputTextC);
form.appendChild(div);
div.appendChild(inputSubmit));
</script>
The HTML code could be a bit different from the script I've made because I wrote it just to elucidate you. Thanks in advance. Hope I'm explaining myself well.
the for attribute should be assigned through htmlFor property
labelA.htmlFor = ...
See https://developer.mozilla.org/en-US/docs/DOM/HTMLLabelElement for further reference

spit items into different arrays and retrieving it back

this related to my previous question asked and thanks to every one here who is helping me to learn coding :D
i was previously working on an undo button which kind of works but not there yet :(
here is what i have done click here. But the problem is since it goes step by step backwards it has to wait till the item where the previous color was applied in the same part. Is there a way i can split something like this click here will this idea work out?
here is the test html code:
<div id="colour">
<input type="submit" name="r1" id="r1" value="1" />
<input type="submit" name="r2" id="r2" value="2" />
<input type="submit" name="r3" id="r3" value="3" />
<input type="submit" name="r4" id="r4" value="4" />
<input type="submit" name="r5" id="r5" value="5" />
<input type="submit" name="r6" id="r6" value="6" />
</div>
<div id="map">
<input type="radio" name="radio" id="layer_a" value="a" />
<label for="layer">layer_a</label>
<input type="radio" name="radio" id="layer_b" value="b" />
<label for="layer">layer_b</label>
<input type="radio" name="radio" id="layer_c" value="c" />
<label for="layer">layer_c</label>
<input type="radio" name="radio" id="layer_d" value="d" />
<label for="layer">layer_d</label>
</div>
<input name="selected" id="selected" type="hidden" value="" />
<input type="submit" name="undo" id="undo" value="undo" />
<div id="result"></div>
here is the test jQuery code:
$("#colour input").click(function() {
$("input[name='selected']").val(this.id);
});
var arraymap = [];
var array_a = [];
var array_b = [];
var array_c = [];
var array_d = [];
$("#map input").click(function() {
var mape = $(this).attr('id');
var ccurrent = $("input[name='selected']").val();
arraymap.push(mape);
// trying to split it into diffrent arrays //
if (mape == "layer_a") {
array_a.push(ccurrent);
var araycurrent = array_a;
} else if (mape == "layer_b") {
array_b.push(ccurrent);
var araycurrent = array_b;
} else if (mape == "layer_c") {
array_c.push(ccurrent);
var araycurrent = array_c;
} else if (mape == "layer_d") {
array_d.push(ccurrent);
var araycurrent = array_d;
};
var mapid = arraymap[arraymap.length - 1];
var colid = arraycurrent[arraycurrent.length - 1];
var loca = mapid + colid;
$("#result").append(mapid);
});
$("#undo").click(function() {
arraymap.pop();
var remover_map = arraymap[arraymap.length - 1];
// trying get it back from split arrays //
if (remover_map == "layer_a") {
array_a.pop();
var remover_col = array_a[array_a.length - 1];
} else if (remover_map == "layer_b") {
array_b.pop();
var remover_col = array_b[array_b.length - 1];
} else if (remover_map == "layer_c") {
array_c.pop();
var remover_col = array_b[array_c.length - 1];
} else if (remover_map == "layer_d") {
array_d.pop();
var remover_col = array_a[array_d.length - 1];
};
var remove = remover_map + remover_col;
$("#result").append(remove);
});
You can store you layer arrays in an object to use it as an associative array. That way you can easily reference them by the layer name.
Here's my version of your example: (Working demo: http://jsfiddle.net/qbdyp/)
var step_layer = []; // layers affected by each step
var step_colour = { // selected colours by layer
"a": [],
"b": [],
"c": [],
"d": []
};
var $map = $("#map"), $result = $("#result"); // cache
$("#colour > input").click(function() {
var layer = $map.find("input[name='radio']:checked").val(); // current layer
var colour = this.value; // selected colour
step_layer.push(layer);
step_colour[layer].push(colour);
$result.append("Added " + colour + " to layer " + layer + "<br/>");
});
$("#undo").click(function() {
var layer = step_layer.pop(); // get most recently changed layer
if (typeof layer === "undefined") {
$result.append("(Nothing to undo)<br />");
return;
}
var colour = step_colour[layer].pop(); // get latest change in that layer
$result.append("Removed " + colour + " from layer " + layer + "<br/>");
});
And here's a more elaborate example, one that's hopefully closer to what you're trying to achieve: http://jsfiddle.net/uWUve/

Categories