So I have this form which takes in a string of numbers that needs to be split at each semi colon and space. Afterwards, it sorts the numbers and returns the sorted list.
For some reason, when I click on the button, it does not post the value in the text box.
Can anyone help me solve my problem please! Thank you.
Edit 1: Added the name to the form and added the fieldset
function sort() {
var allNumbers = document.mainForm.mainSet.numbers.value.split("; ");
allNumbers.parseFloat;
for (var i = 0; i < allNumbers.length; i++) {
allNumbers[i] = parseInt(allNumbers[i], 10);
}
allNumbers.sort();
document.mainForm.mainSet.sorted.value = allNumbers.toString();
}
<form name="mainForm">
<fieldset name="mainSet">
Enter Numbers:
<input type="text" class="text" name="numbers" />
<br/>
<br/>Select Option:
<select name="sortOption" id="dropDown">
<option value="Ascending" class="select">Ascending</option>
<option value="Descending" class="select">Descending</option>
</select>
<br/>
<br/>Sorted Numbers:
<input type="text" class="text" name="sorted">
<br/>
<br/>
<input type="button" value="Sort Numbers" id="submit" onclick="sort()" />
</fieldset>
</form>
I think this is what you are looking for. This will order the number by what you have selected in your sortOption field.
var order;
function sort() {
order = document.getElementById("dropDown").value;
var allNumbers = document.getElementById("numbers").value.split("; ");
var nums = [];
for (var i = 0; i < allNumbers.length; i++) {
nums.push(parseInt(allNumbers[i], 10));
}
nums.sort(function(a, b) {
if (a > b)
return order == 'asc' ? 1 : -1;
else
return order == 'asc' ? -1 : 1;
});
document.getElementById("sorted").value = nums.toString();
}
<form name="mainForm">
<fieldset name="mainSet">
Enter Numbers:
<input id="numbers" type="text" class="text" name="numbers" />
<br/>
<br/>Select Option:
<select name="sortOption" id="dropDown">
<option value="asc" class="select">Ascending</option>
<option value="desc" class="select">Descending</option>
</select>
<br/>
<br/>Sorted Numbers:
<input id="sorted" type="text" class="text" name="sorted">
<br/>
<br/>
<input type="button" value="Sort Numbers" id="submit" onclick="sort()" />
</fieldset>
</form>
I don't see any elements named "mainForm" or "mainSet" in the HTML. Likewise, I'm not entirely sure what the purpose of "allNumbers.parseFloat;" is, either, since that's not how to invoke a function, and parseFloat isn't a member of Array.
function sort() {
function asc(a,b)
{
return a - b;
}
function desc(a,b)
{
return b - a;
}
var allNumbers = document.getElementById("numbers").value.split("; ");
var nums = [];
var order = document.getElementById("dropDown").value;
for (var i = 0; i < allNumbers.length; i++) {
nums.push(parseInt(allNumbers[i], 10));
}
nums.sort((order == 'asc') ? asc : desc);
document.getElementById("sorted").value = nums.toString(',');
}
<form name="mainForm">
<fieldset name="mainSet">
Enter Numbers:
<input id="numbers" type="text" class="text" name="numbers" />
<br/>
<br/>Select Option:
<select name="sortOption" id="dropDown">
<option value="asc" class="select">Ascending</option>
<option value="desc" class="select">Descending</option>
</select>
<br/>
<br/>Sorted Numbers:
<input id="sorted" type="text" class="text" name="sorted">
<br/>
<br/>
<input type="button" value="Sort Numbers" id="submit" onclick="sort()" />
</fieldset>
</form>
Related
Background: I'm practicing arrays and functions and am having trouble computing the sum of array items. I'm pretty sure there is something wrong with the function I'm writing but I'm not sure what. Using 8 input fields I'm pulling data into a array one item at a time and converted to floating numbers(for now...I'll try to fix that later). I've created a function that will compute the total of this list but it only outputs NaN.
Any suggestions are highly appreciated!
function myfunction() {
list = [];
list[0] = parseFloat(document.getElementById('number1').value);
list[1] = parseFloat(document.getElementById('number2').value);
list[2] = parseFloat(document.getElementById('number3').value);
list[3] = parseFloat(document.getElementById('number4').value);
list[4] = parseFloat(document.getElementById('number5').value);
list[5] = parseFloat(document.getElementById('number6').value);
list[6] = parseFloat(document.getElementById('number7').value);
list[7] = parseFloat(document.getElementById('number8').value);
function total(myvals) {
let total = 0;
for (let i = 0; i <= myvals.length; i++) {
total += myvals[i];
}
return total;
}
document.getElementById('results').innerHTML = total(list);
}
<form>
<input type="text" name="number1" id="number1"><br>
<input type="text" name="number2" id="number2"><br>
<input type="text" name="number3" id="number3"><br>
<input type="text" name="number4" id="number4"><br>
<input type="text" name="number5" id="number5"><br>
<input type="text" name="number6" id="number6"><br>
<input type="text" name="number7" id="number7"><br>
<input type="text" name="number8" id="number8"><br>
<input type="submit" value="Compute Score" onclick="javascript:myfunction()">
</form>
<div id="results"></div>
Here is a simple example using a for loop with querySelectorAll.
Additionally, I cleaned up your code a bit. Run the snippet below:
EDIT: Included some comments to show what's happening.
function myfunction() {
let total = 0;
//get the value for each element being called by querySelectorAll
//add values to total to get a sum
document.querySelectorAll('input').forEach(el => total += +el.value);
//append the new value to the results div
document.querySelector('#results').innerHTML = total;
}
<form>
<input type="text" name="number1" id="number1"><br>
<input type="text" name="number2" id="number2"><br>
<input type="text" name="number3" id="number3"><br>
<input type="text" name="number4" id="number4"><br>
<input type="text" name="number5" id="number5"><br>
<input type="text" name="number6" id="number6"><br>
<input type="text" name="number7" id="number7"><br>
<input type="text" name="number8" id="number8"><br>
</form>
<br/><br/>
<button type="submit" onclick="myfunction()">Compute Score</button>
<br/><br/>
<div id="results"></div>
This is resolved. I was able to fix my source code by removing
"<=" in the for loop and adding "<" in its place. Thanks everyone, I will look over everything else for extra practice!
1 - in HTML forms and their elements use names.
2 - each element of a form can be accessed by name with the form as parent
3 - if several elements have the same name (with the same type of preference) then they form an object collection
PS: I have used here [... myForm.numX] to transform the myForm.numX collection to array, so that it can accept the arry.map () method
this way:
const myForm = document.forms['my-form']
, res = document.getElementById('results')
;
myForm.onsubmit = evt =>
{
evt.preventDefault() // disable submit
let list = [...myForm.numX].map(inp => parseFloat(inp.value))
res.textContent = list.reduce((t,v)=>t+v,0)
// control...
console.clear()
console.log( myForm.numX.length, JSON.stringify(list) )
}
<form name="my-form">
<input type="text" name="numX" placeholder="num 1"><br>
<input type="text" name="numX" placeholder="num 2"><br>
<input type="text" name="numX" placeholder="num 3"><br>
<input type="text" name="numX" placeholder="num 4"><br>
<input type="text" name="numX" placeholder="num 5"><br>
<input type="text" name="numX" placeholder="num 6"><br>
<input type="text" name="numX" placeholder="num 7"><br>
<input type="text" name="numX" placeholder="num 8"><br>
<button type="submit">Compute Score</button>
</form>
<div id="results">..</div>
I am trying to create a JS function to generate 6 random, secure numbers that are inputted in a HTML form. I currently have:
function secureRandomNums(len) {
let array = new Uint8Array(len);
window.crypto.getRandomValues(array);
return array;
}
function getRandomNumbers() {
let elements = form.getElementsByName("number[]");
let nums = secureRandomNums(elements.length);
for (let i = 0; i < nums.length; i++) {
elements[i].value = nums[i]
}
}
In the HTML file I am calling the getRandomNumbers here:
<form action="AddUserNumbers" id="add_numbers_form" method="post" class="forms">
<label for="number1">Number 1:</label><br>
<input type="text" id="number1" name="number[]"><br>
<label for="number2">Number 2:</label><br>
<input type="text" id="number2" name="number[]"><br>
<label for="number3">Number 3:</label><br>
<input type="text" id="number3" name="number[]"><br>
<label for="number4">Number 4:</label><br>
<input type="text" id="number4" name="number[]"><br>
<label for="number5">Number 5:</label><br>
<input type="text" id="number5" name="number[]"><br>
<label for="number6">Number 6:</label><br>
<input type="text" id="number6" name="number[]"><br>
<input type="button" value="Generate numbers!" onclick="getRandomNumbers()"><br>
<input type="submit" id="submit_numbers" value="Submit your numbers" form="add_numbers_form"><br>
</form>
But it is not displaying the values. What am I doing wrong?
I had it working with an implementation of the Math.random() function but this is not as secure as window.crypto.
getElementsByName() is a document level method and not available at element level
Use querySelectorAll() instead to query elements that only exist in the specific form
const form = document.forms[0]
function secureRandomNums(len) {
let array = new Uint8Array(len);
window.crypto.getRandomValues(array);
return array;
}
function getRandomNumbers() {
let elements = form.querySelectorAll('input[name="number[]"]');
let nums = secureRandomNums(elements.length);
for (let i = 0; i < nums.length; i++) {
elements[i].value = nums[i]
}
}
<form>
<input name="number[]" />
<input name="number[]" />
<input name="number[]" />
<input type="button" value="Generate numbers!" onclick="getRandomNumbers()"><br>
</form>
I need some guidance in how to add my selection list to my total. I am still new to javascript so i did what i could but for some reason, i cannot figure out how to add the selection list to my total. the textboxes with 0.00 are there for me to see if the radios, checkboxes and selection are adding up properly.
``
`
function customerInfo(cName){
var dinerName = document.getElementById(cName).value;
document.getElementById('cust_name').innerHTML = dinerName;
}
// format val to n number of decimal places
function formatDecimal(val, n) {
n = n || 2;
var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
while (str.length <= n) {
str = "0" + str;
}
var pt = str.length - n;
return str.slice(0,pt) + "." + str.slice(pt);
}
function getRadioVal(form, name) {
var radios = form.elements[name];
var val;
for (var i=0, len=radios.length; i<len; i++) {
if ( radios[i].checked == true ) {
val = radios[i].value;
break;
}
}
return val;
}
function getToppingsTotal(e) {
var form = this.form;
var val = parseFloat( form.elements['tops_tot'].value );
if ( this.checked == true ) {
val += parseFloat(this.value);
} else {
val -= parseFloat(this.value);
}
form.elements['tops_tot'].value = formatDecimal(val);
updatePizzaTotal(form);
}
function getSizePrice(e) {
this.form.elements['sz_tot'].value = parseFloat( this.value );
updatePizzaTotal(this.form);
}
function getDeliveryPrice(e){
selectElement = document.querySelector('#pick_delivery');
output = selectElement.options[selectElement.selectedIndex].value;
console.log(output);
}
function updatePizzaTotal(form) {
var sz_tot = parseFloat( form.elements['sz_tot'].value );
var tops_tot = parseFloat( form.elements['tops_tot'].value );
form.elements['total'].value = formatDecimal( sz_tot + tops_tot );
}
// removes from global namespace
(function() {
var form = document.getElementById('pizzaForm');
var el = document.getElementById('pizza_toppings');
// input in toppings container element
var tops = el.getElementsByTagName('input');
for (var i=0, len=tops.length; i<len; i++) {
if ( tops[i].type === 'checkbox' ) {
tops[i].onclick = getToppingsTotal;
}
}
var sz = form.elements['size'];
for (var i=0, len=sz.length; i<len; i++) {
sz[i].onclick = getSizePrice;
}
// set sz_tot to value of selected
form.elements['sz_tot'].value = formatDecimal( parseFloat( getRadioVal(form, 'size') ) );
updatePizzaTotal(form);
})(); // end remove from global namespace and invoke
<form name="pizzaOrder" method="post" id="pizzaForm" enctype="text/plain">
<fieldset style="width: 60%;">
<legend>Create Your Pizza</legend>
<h3>Customer's Name:</h3>
<p>
<input type="text" name="client_name" id="client_name" value="First and Last Name" size="30" value="" />
<input type="button" onclick="customerInfo('client_name')" value="Enter"></button>
</p>
<h3>Pick Your Size:</h3>
<p>
<label><input type="radio" name="size" value="8" /> Small</label>
<label><input type="radio" name="size" value="10" /> Medium</label>
<label><input type="radio" name="size" value="12" /> Large</label>
<label><input type="radio" name="size" value="14" checked/> Extra Large</label>
<input type="text" name="sz_tot" value="0.00" />
</p>
<h3>Pick Your Toppings</h3>
<p id="pizza_toppings">
<label><input type="checkbox" name="Pineapple" value="1.50" /> Pineapple</label>
<label><input type="checkbox" name="Onions" value="1.50" /> Onions </label>
<label><input type="checkbox" name="Ham" value="1.50" /> Ham</label>
<label><input type="checkbox" name="Sausage" value="1.50" /> Sausage</label>
<label><input type="checkbox" name="Pepperoni" value="1.50" /> Pepperoni</label>
<input type="text" name="tops_tot" value="0.00" />
</p>
<h3>Delivery Or Pick Up</h3>
<p>
<select class="delivery" id="pick_delivery" size="2">
<option value="0">Pick Up: Free</option>
<option value="2">Delivery: $2</option>
</select>
<input type="button" onclick="getDeliveryPrice()" id="delivery_pick" value="enter" /></button>
</p>
<p>
<label>Total: $ <input type="text" name="total" class="num" value="0.00" readonly="readonly" /></label>
</p>
<p>
<input type="button" value="Confirm" />
<input type="button" value="Cancel">
</p>
</fieldset>
</form>
<div>
<h2>Your Order:</h2>
<p>
<h4>Your Name: <span id="cust_name"> </span></h4>
<h4>Your Pizza Size:</h4>
<h4>Toppings Selected:</h4>
</p>
</div>
</fieldset>
</form>```
On the bottom of the page the results should look similar to this:
Your Name: Pam Love
Pizza Size Selected: Extra Large
Toppings Selected: Bacon, Pineapple, Ham
Total: 20.50
When clicked on confirm order, the onclick button should redirect the page to a new tab that says:
Your order will be ready in 20 minutes.
or if cancelled then the user clicks the cancel button also redirected to a new tab:
Your order is cancelled.
You can just use some css selectors to accomplish most of this.
Here is how you can get your selected size:
document.querySelector('input[type="radio"][name="size"]:checked').value
And here is how you can get the list of toppings:
[...document.querySelectorAll('input[type="checkbox"][name="topping"]:checked')].map((t) => t.value).join(', ')
The remaining things should be pretty easy to find using querySelector or getElementById
I really don't know how to program in Javascript, yet I've tried to do some stuff. I have values to be summed if some are selected. The following function does sum operation and show result at once without clicking a button only for checkbox fields, not for the dropdown list and text fields.
However, I need to involve the selected values as well from the dropdown lists and entered both text fields in the same manner of the checkboxes and their immediate responses(output).
I think change method can be used in the same manner.
#Edit:
Sorry, I forgot the tell but, I need to multiply the m2 entered value by before summing with 3134,204499 and Bina Yasi with -566,2202888.
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
$('#housepriceguesslist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#housepriceguesslist :checkbox').change(calcAndShowTotal).change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housepriceguesslist">
<select id="ilce">
<option value="0">Choose a state</option>
<option value="63999.50712318567">Adalar</option>
<option value="6259.918435398593">Ataşehir</option>
<option value="46285.35729304834">Beykoz</option>
<option value="54258.92953697798">Kadıköy</option>
<option value="-3500.620905653726">Kartal</option>
<option value="12889.41219909602">Maltepe</option>
<option value="-33711.83156847153">Pendik</option>
<option value="-34577.42485251657">Sancaktepe</option>
<option value="-52183.1608811019">Sultanbeyli</option>
<option value="-34760.71735007784">Tuzla</option>
<option value="-27379.87966213786">Çekmeköy</option>
<option value="-5332.203990418937">Ümraniye</option>
<option value="26485.33532820411">Üsküdar</option>
<option value="-18732.62070553167">Şile</option>
</select>
<select id="odasalon">
<option value="0">Choose room number</option>
<option value="5940.027623576261">1+0</option>
<option value="-1399.625767475593">1+1</option>
<option value="-3033.638999060459">2+1</option>
<option value="11519.83954756076">3+1</option>
<option value="-7018.52116545078">4+1</option>
<option value="-6008.081239150166">5+1</option>
</select>
m2: <input type="text" id="m2" /> Bina Yasi: <input type="text" id="binayasi" />
<br/>
<br/> Features:
<br/>
<br/>
<input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> <label for="Bati">Bati</label>
<br/>
<input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> <label for="Dogu">Dogu</label>
<br/>
<input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> <label for="Guney">Guney</label>
<br/>
<input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> <label for="Kuzey">Kuzey</label>
<br/>
<input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> <label for="Amerikan Mutfak">Amerikan Mutfak</label>
<br/>
<input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> <label for="Dusakabin">Dusakabin</label>
<br/>
<input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> <label for="Akilli Ev">Akilli Ev</label>
<br/>
<input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> <label for="Ebeveyn Banyosu">Ebeveyn Banyosu</label>
<br/>
<input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> <label for="Kiler">Kiler</label>
<br/>
<input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> <label for="Kuvet">Kuvet</label>
<br/>
<input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> <label for="Parke Zemin">Parke Zemin</label>
<br/>
<input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> <label for="Seramik Zemin">Seramik Zemin</label>
<br/>
<input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> <label for="Sauna">Sauna</label>
<br/>
<input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> <label for="Spor Salonu">Spor Salonu</label>
<br/>
<input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> <label for="Tenis Kortu">Tenis Kortu</label>
<br/>
</div>
<input type="text" id="total" value="0" />
You can loop over all the <select> boxes and text inputs with:
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
$('#housepriceguesslist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$("#housepriceguesslist select, #housepriceguesslist :text").each(function() {
let multiplier = 1;
if (this.id == "m2") {
multiplier = 3134.204499;
}
else if (this.id == "binayasi") {
multiplier = -566.2202888;
}
if (this.value) {
total += parseFloat(this.value) * multiplier;
}
});
$('#total').val(total);
}
And if you change the checkboxes to use value instead of price, you can do them all in one loop:
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
$('#housepriceguesslist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$("#housepriceguesslist select, #housepriceguesslist :text, #housepriceguesslist :checkbox:checked").each(function() {
let multiplier = 1;
if (this.id == "m2") {
multiplier = 3134.204499;
else if (this.id == "binyasi") {
multiplier = -566.2202888;
}
if (this.value) {
total += parseFloat(this.value) * multiplier;
}
});
$('#total').val(total);
}
And call the function when any of the inputs are changed:
$('#housepriceguesslist input, #housepriceguesslist select').change(calcAndShowTotal).change();
This solution is simple, just the get the list of all the inputs (i.e. checkbox, and dropdown) using the .find() method and the selector 'input:checkbox, input:text, select'. Then verify if each one of these inputs elements has the attribute checked or select for the checkbox and select input types respectively, or it is a multiplier for the text inputs. This verification ca be done inside of the each() method callback. Finally, just convert then the value to a number, using the parseFloat() method and add it to the total accumulator.
Finally, sum the value to the total input. Like this:
let container;
let inputs;
let total;
function calcAndShowTotal() {
let sum = 55435.04798; // it is constant value which must be the beginning value.
let value;
inputs.each(function() {
if ($(this).is('input:checkbox:checked')) {
// If is a checkbox
value = parseFloat($(this).attr('price')) || 0;
sum += value;
} else if ($(this).is('input:text:not(#total)')) {
// If is a text wait until you move to another element
let factor = 1;
if (this.id == 'm2') {
factor = 3134.204499;
} else if (this.id == 'binayasi') {
factor = -566.2202888;
}
value = parseFloat($(this).val()) * factor || 0;
sum += value;
} else if ($(this).is('select')) {
// If is a option from the select element
value = parseFloat($('option:selected', this).val()) || 0;
sum += value;
}
});
total.val(sum);
}
function initHandlers() {
inputs.on('keydown', function(e) {
let focusable, next;
if (e.keyCode == 13) {
focusable = inputs.filter(':visible');
next = focusable.eq(focusable.index(this) + 1);
if (next.length) {
next.focus();
}
return false;
}
});
inputs.change(calcAndShowTotal);
calcAndShowTotal();
}
$(function() {
console.log('ready!');
total = $('#total');
container = $('#housepriceguesslist');
inputs = container.find('input:checkbox, input:text, select');
initHandlers();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housepriceguesslist">
Total: <input type="text" id="total" value="0" />
<br/>
<br/>
<select id="ilce">
<option value="0">Choose a state</option>
<option value="63999.50712318567">Adalar</option>
<option value="6259.918435398593">Ataşehir</option>
<option value="46285.35729304834">Beykoz</option>
<option value="54258.92953697798">Kadıköy</option>
<option value="-3500.620905653726">Kartal</option>
<option value="12889.41219909602">Maltepe</option>
<option value="-33711.83156847153">Pendik</option>
<option value="-34577.42485251657">Sancaktepe</option>
<option value="-52183.1608811019">Sultanbeyli</option>
<option value="-34760.71735007784">Tuzla</option>
<option value="-27379.87966213786">Çekmeköy</option>
<option value="-5332.203990418937">Ümraniye</option>
<option value="26485.33532820411">Üsküdar</option>
<option value="-18732.62070553167">Şile</option>
</select>
<select id="odasalon">
<option value="0">Choose room number</option>
<option value="5940.027623576261">1+0</option>
<option value="-1399.625767475593">1+1</option>
<option value="-3033.638999060459">2+1</option>
<option value="11519.83954756076">3+1</option>
<option value="-7018.52116545078">4+1</option>
<option value="-6008.081239150166">5+1</option>
</select>
m2: <input type="text" id="m2" />
Bina Yasi: <input type="text" id="binayasi" />
<br/>
<br/> Features:
<br/>
<br/>
<input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> <label for="Bati">Bati</label>
<br/>
<input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> <label for="Dogu">Dogu</label>
<br/>
<input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> <label for="Guney">Guney</label>
<br/>
<input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> <label for="Kuzey">Kuzey</label>
<br/>
<input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> <label for="Amerikan Mutfak">Amerikan Mutfak</label>
<br/>
<input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> <label for="Dusakabin">Dusakabin</label>
<br/>
<input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> <label for="Akilli Ev">Akilli Ev</label>
<br/>
<input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> <label for="Ebeveyn Banyosu">Ebeveyn Banyosu</label>
<br/>
<input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> <label for="Kiler">Kiler</label>
<br/>
<input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> <label for="Kuvet">Kuvet</label>
<br/>
<input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> <label for="Parke Zemin">Parke Zemin</label>
<br/>
<input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> <label for="Seramik Zemin">Seramik Zemin</label>
<br/>
<input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> <label for="Sauna">Sauna</label>
<br/>
<input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> <label for="Spor Salonu">Spor Salonu</label>
<br/>
<input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> <label for="Tenis Kortu">Tenis Kortu</label>
<br/>
</div>
Note:
Remember to round the numbers to get more precision. The text modification will apply after you tab, or move to another element. So I added an enter listener so when you press enter is gonna move to the next element like when you press tab. Also, I moved the total to the top so you can see the results in the preview.
Update:
I recommend you to use the $(function(){}); to get the document when is ready. Inside you can assign the values of your elements. I notice that there was a bug in my code whenever ever you uncheck a checked element the Total should be 55435.04798, but it shows the double it is because total is also a text input.
Similar to Barmar's, I added all elements to the .each() loop but also added the .change() handler to all elements:
var context = $('#housepriceguesslist');
var elems = $('input:checkbox, input:text, select', context);
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
elems.each(function() {
if ( $(this).is('input:checkbox:checked') ) {
total += parseFloat($(this).attr('price')) || 0;
} else if ( $(this).is('#m2') ) {
total += parseFloat($(this).val()) * 3134.204499 || 0;
} else if ( $(this).is('#binayasi') ) {
total += parseFloat($(this).val()) * -566.2202888 || 0;
} else if ( $(this).is('select') ) {
total += parseFloat($('option:selected',this).val()) || 0;
}
});
$('#total').val(total);
}
elems.change(calcAndShowTotal); // handlers
calcAndShowTotal(); // first run
See example here: https://jsfiddle.net/qgvsern4/1/
I've seen similar questions posted and tried to change them to meet my needs but I don't know enough about javascript to do it. All I want to do is limit a form input to 2 characters if they select "state" as their search option. This is what I have:
function changeValue(){
var option=document.getElementById('searchtype').id;
if (option == ("A") || ("B") ){
document.getElementById('field').size="40";
}
else if(option=="C"){
document.getElementById('field').size="2";
<form action="results.php" method="post">
Search By:<br />
<select id="searchtype" name="searchtype" onchange="changeValue();">
<option id="A" value="name">Hospital Name<br /></option>
<option id="B" value="city">City</option>
<option id="C" value="state">State</option>
</select>
<br /><br />
Search:<br />
<input id="field" name="searchterm" type="text" size="0">
Am I doing something wrong or is there a better way to do this?
I used Jack's code below and added a field.size attribute so my input matched the max allowed characters: (thanks Jack)
script type="text/javascript">
function changeValue(dropdown) {
var option = dropdown.options[dropdown.selectedIndex].value,
field = document.getElementById('field');
if (option == 'name' || option == 'city') {
field.maxLength = 40;
field.size = 40;
} else if (option == 'state') {
field.value = field.value.substr(0, 2);
field.maxLength = 2;
field.size = 2;
}
}
</script>
<h1>Hospital Search</h1>
<form action="results.php" method="post">
Search By:<br />
<select id="searchtype" name="searchtype" onchange="changeValue(this);">
<option id="name" value="name">Hospital Name<br /></option>
<option id="city" value="city">City</option>
<option id="state" value="state">State</option>
</select><br />
Search:<br />
<input id="field" name="field" type="text" size="40">
</input>
After deciding a dropdown with a list of states would be better, I changed it to this:
<form action="results.php" method="post">
Hospital Name:<br />
<input name="searchterm_name" type="text" size="40">
<br />
<input type="submit" name="submit" value="Search">
</form><br />
<form action="results.php" method="get">
City Name:<br />
<input name="searchterm_city" type="text" size="40"><br />
<select name="select_state">
<option value="">None
<option value="AL" Selected>Alabama
<option value="AK">Alaska
<option value="AZ">Arizona
</SELECT>
<input type="submit" name="submit" value="Search">
</form>
ED: Using form method "post" caused the browser to throw a warning every time I hit the back button to get to the results page. I changed to "get" since the information is not sensitive and now it goes back w/o warning.
Set the maxlength property:
document.getElementById('field').maxlength = 2;
I realize now that the rest of the code is not likely to work:
function changeValue(dropdown) {
var option = dropdown.options[dropdown.selectedIndex].value,
field = document.getElementById('field');
if (option == 'name' || option == 'city') {
field.maxLength = 40;
} else if (option == 'state') {
field.value = field.value.substr(0, 2); // before reducing the maxlength, make sure it contains at most two characters; you could also reset the value altogether
field.maxLength = 2;
}
}
Then in your HTML:
<select id="searchtype" name="searchtype" onchange="changeValue(this);">
try this
function changeValue() {
var option2 = document.getElementById('searchtype').options[document.getElementById('searchtype').selectedIndex].id;
if (option2 == ("A") || option2 == ("B")) {
document.getElementById('field').size = "40";
}
else if (option2 == "C") {
document.getElementById('field').size = "2";
}
}
Try this.
document.getElementById('field').setAttribute('size', "10");