I have a HTML file, with some Script inside.
I bring all functions in one Script Tag.
Now I want to use these methods in onload and onclick events.
Here is this HTML file with all scripts :
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js">
</script>
<script src="../configwireless.php">
</script>
<title>configuration</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.center {
margin: auto;
width: 40%;
border: 3px solid #73AD21;
padding: 10px;
text-align: center;
margin-left: auto;
margin-right: auto;
background : url(wall5.jpg) center no-repeat;
}
#font-face {
font-family: myFont;
src: url(fonts/Raleway-Medium.otf);
src: url(fonts/Raleway-Medium.ttf);
src: url(fonts/Raleway-Medium.woff);
}
body {
font-family:myFont;
background : url(wall5.jpg) center;
height: 100%;
font-family:myFont;
background-position: center;
background-repeat: repeat;
background-size: cover;
width: 100%;
}
lable {
font-family:myFont;
}
form{
font-family: myFont;
}
input {
text-align: center;
}
</style>
</head>
<body>
<form name="general" action="" id="general" class="center" method="post">
<div id="wirelessmodediv">
<label>Wireless Mode</label>
<select name="wirelessmode" id="wirelessmode"
onclick="checkGeneralWirelessMode()">
<option value="ap">AP</option>
<option value="xxx">Client</option>
<option value="xxx">Client Bridge(Routed)</option>
<option value="xxx">Adhoc</option>
<option value="xxx">WDS Station</option>
<option value="xxx">WDS AP</option>
</select> <br>
</div>
<div id="networkmodediv">
<label>Wireless Network Mode</label>
<select name="wirelessNetworkMode" id="wirelessNetworkMode">
<option value="disabled">Disable</option>
<option value="mixed">Mixed</option>
<option value="a-only">A-Only</option>
<option value="na-only">NA-Mixed</option>
<option value="n5-only">N-Only(5 GHz)</option>
</select> <br>
</div>
<div id="channelwidthdiv" >
<label> Channel Width </label>
<select id="channelWidth" name="channelWidth">
<option value="20">Full</option>
<option value="40">Wide </option>
<option value="2040">Dynamic </option>
<option value="10">Half (10 MHz)</option>
<option value="5">Quarter(5 MHz)</option>
</select> <br>
</div>
<div id="countrydiv">
<label>Country</label>
<select id="country" name="country"
onchange="fillWirelessChannel();"
onload="fillWirelessChannel();"
onclick="fillWirelessChannel();">
<option value="china" >China</option>
<option value="japan" >japan</option>
</select>
</div>
<br>
<div id="wirelesschannel">
<label>Wireless Channel</label>
<select id="wirelessChannel" name="wirelessChannel">
</select>
</div>
<br>
<div id="extentionchanneldiv">
<label> Extention Channel </label>
<select id="extentionChannel" name="extentionChannel">
<option value="auto">auto</option>
<option value="lower">lower</option>
<option value="upper">upper</option>
</select>
</div>
<br>
<div id="linkname" >
<label>Wireless Link Name</label>
<input type="text" name="ssid" id="ssid" /><br>
</div>
<div id="ssidbroadcast" >
<label>Wireless SSID Broadcast</label>
<input type="radio" name="broadcaststatus" id="enablebroadcaststatus"
value="0"> Enable
<input type="radio" name="broadcaststatus" id="disablebroadcaststatus" value="1" > Disable <br>
</div>
<div id="gatewaydiv" >
<label>Default GW Mode</label>
<input type="radio" name="gateway" id="gateway" value="1" onclick="checkDefaultGateway()"> Auto (DHCP)
<input type="radio" name="gateway" id="gateway" value="0" onclick="checkDefaultGateway()"> Manual <br>
</div>
<div id="gatewayipdiv" >
<label>Gateway</label>
<input type="text" name="gatewayip" id="gatewayip" ><br>
</div>
<label>Advanced Setting</label>
<input type="checkbox" name="advancecheck" id="advancecheck"
onchange="advancecheckChanged()"
onload="advancecheckChanged()"/><br>
<div id="advanceddiv" style="display:none;">
<label>Super Channel</label>
<input type="radio" name="supperchannel" value="ebable"> Enable
<input type="radio" name="supperchannel" value="disable"> Disable <br>
<label>TX Power</label>
<input type="text" name="txpower" id="txpower"><br>
<label>Antenna Gain</label>
<input type="text" name="antennagain" id="antennagain"><br>
<label>Noise Immunity</label>
<input type="radio" name="noise" id="enablenoise" value="1"> Enable
<input type="radio" name="noise" id="disablenoise" value="0"> Disable <br>
<label> Protection Mode </label>
<select id="protection">
<option value="None">one</option>
<option value="CTS">CTS</option>
<option value="RTS/CTS">RTS/CTS</option>
</select> <br>
<label>RTS Threshold</label>
<input type="text" name="rts" id="rts"> <br>
<label>Short Preamble</label>
<input type="radio" name="preamble" id="enablepreamble" value="ebable"> Enable
<input type="radio" name="preamble" id="disablepreamble" value="disable"> Disable <br>
<label>Short GI</label>
<input type="radio" name="gi" id="enablegi" value="1"> Enable
<input type="radio" name="gi" id="disablegi" value="0"> Disable <br>
<label>TX Antenna Chains</label>
<select id="txantennachains">
<option value="1">1</option>
<option value="3">1+2</option>
</select><br>
<label>RX Antenna Chains</label>
<select id="rxantennachains">
<option value="1">1</option>
<option value="3">1+2</option>
</select><br>
<label>Beacon Interval</label>
<input type="text" name="interval" id="interval"><br>
<label>DTIM Interval</label>
<input type="text" name="dtiminterval" id="dtiminterval"><br>
<label>AP Isolation</label>
<input type="radio" name="isolation" id="enableisolation" value="1"> Enable
<input type="radio" name="isolation" id="disableisolation" value="0"> Disable <br>
<label>Sensitivity Range (ACK Timing)</label>
<input type="text" name="sensitiverange" id="sensitiverange"><br>
<label>Max Associated Clients</label>
<input type="text" name="maxassociate" id="maxassociate"><br>
<label>Network Configuration</label>
<input type="radio" name="configuration" id="enableconfiguration" value="0"
onload="checkBridgeMode()"
onclick="checkBridgeMode()"
onchange="checkBridgeMode()"> Unbridge
<input type="radio" name="configuration" id="disableconfiguration" value="1"
onload="checkBridgeMode()"
onclick="checkBridgeMode()"
onchange="checkBridgeMode()"> Bridge<br>
<div id="multicastdiv">
<label>Multicast forwarding</label>
<input type="radio" name="multicast" id="enablemulticast" value="1"> Enable
<input type="radio" name="multicast" id="disablemulticast" value="0"> Disable <br>
<label>Masquerade / NAT</label>
<input type="radio" name="masquerade" id="enablemasquerade" value="1"> Enable
<input type="radio" name="masquerade" id="disablemasquerade" value="0"> Disable <br>
<label>Net Isolation</label>
<input type="radio" name="netisolation" id="enablenetisolation" value="1"> Enable
<input type="radio" name="netisolation" id="disablenetisolation" value="0"> Disable <br>
<label>Forced DNS Redirection</label>
<input type="radio" name="forcedns" id="enableforcedns" value="1"
onload="Checkradiobutton()" onclick="Checkradiobutton()" > Enable
<input type="radio" name="forcedns" id="disableforcedns" value="0"
onload="Checkradiobutton()" onclick="Checkradiobutton()"> Disable <br>
<label>Optional DNS Target</label>
<input type="text" name="optionaldns" id="optionaldns"><br>
<label>IP Address</label>
<input type="text" name="ipaddress" id="ipaddress"><br>
</div>
</div>
<div id="subnetmaskdiv" style="display:none;">
<label>Subnet Mask</label>
<input type="text" name="subnetmask" id="subnetmask"><br>
</div>
<input type="submit" name="apply" id="apply" value="Apply"/>
</form>
<script type="text/javascript">
function checkGeneralWirelessMode() {
if ((document.getElementById('wirelessmode').value == "ap") ||
(document.getElementById('wirelessmode').value == "infra") ||
(document.getElementById('wirelessmode').value == "wdsap"))
{
document.getElementById("channelwidthdiv").style.display = 'block';
document.getElementById("countrydiv").style.display = 'block';
document.getElementById("extentionchanneldiv").style.display = 'block';
document.getElementById("wirelesschannel").style.display = 'block';
document.getElementById("linkname").style.display = 'block';
document.getElementById("ssidbroadcast").style.display = 'block';
document.getElementById("networkmodediv").style.display = 'block';
document.getElementById("gatewayipdiv").style.display = 'none';
document.getElementById("gatewaydiv").style.display = 'none';
} else if (document.getElementById('wirelessmode').value == "wet") {
document.getElementById("networkmodediv").style.display = 'block';
document.getElementById("gatewayipdiv").style.display = 'block';
document.getElementById("linkname").style.display = 'block';
document.getElementById("gatewaydiv").style.display = 'block';
document.getElementById("extentionchanneldiv").style.display = 'none';
document.getElementById("channelwidthdiv").style.display = 'none';
document.getElementById("countrydiv").style.display = 'none';
document.getElementById("wirelesschannel").style.display = 'none';
document.getElementById("ssidbroadcast").style.display = 'none';
} else if (document.getElementById('wirelessmode').value == "sta" ||
document.getElementById('wirelessmode').value == "wdssta") {
document.getElementById("channelwidthdiv").style.display = 'block';
document.getElementById("linkname").style.display = 'block';
document.getElementById("networkmodediv").style.display = 'block';
document.getElementById("extentionchanneldiv").style.display = 'none';
document.getElementById("gatewayipdiv").style.display = 'none';
document.getElementById("gatewaydiv").style.display = 'none';
document.getElementById("countrydiv").style.display = 'none';
document.getElementById("wirelesschannel").style.display = 'none';
document.getElementById("ssidbroadcast").style.display = 'none';
}
}
function advancecheckChanged() {
if (document.getElementById('advancecheck').checked &&
document.getElementById('enableforcedns').checked) {
document.getElementById("advanceddiv").style.display = 'block';
document.getElementById("subnetmaskdiv").style.display = 'block';
} else
document.getElementById("advanceddiv").style.display = 'none';
document.getElementById("subnetmaskdiv").style.display = 'none';
}
function fillWirelessChannel() {
var index;
var selectTag = document.getElementById('wirelessChannel');
selectTag.options.length = 0;
var auto = document.createElement("option");
auto.value = 'auto';
auto.innerHTML = 'auto';
selectTag.appendChild(auto);
// console.log(document.getElementById('country').value);
if (document.getElementById('country').value == "iran") {
for (index = 4920; index <= 5825; index += 5) {
var opt = document.createElement("option");
opt.value = index;
opt.innerHTML = index;
selectTag.appendChild(opt);
}
} else if (document.getElementById('country').value == "japan") {
for (index = 4920; index <= 6075; index += 5) {
var otherOpt = document.createElement("option");
otherOpt.value = index;
otherOpt.innerHTML = index;
selectTag.appendChild(otherOpt);
}
}
}
function checkDefaultGateway() {
if (document.getElementById('gateway').checked) {
document.getElementById("gatewayipdiv").style.display = 'none';
} else
document.getElementById("gatewayipdiv").style.display = 'block';
}
function checkBridgeMode() {
if (document.getElementById('enableconfiguration').checked) {
document.getElementById("multicastdiv").style.display = 'block';
} else
document.getElementById("multicastdiv").style.display = 'none';
}
function Checkradiobutton() {
if (document.getElementById('enableforcedns').checked) {
document.getElementById("subnetmaskdiv").style.display = 'block';
} else
document.getElementById("subnetmaskdiv").style.display = 'none';
}
</script>
</body>
</html>
I can call methods in onclick event via using onclick method in every tag I want use a specific method.
But I want to try all methods in onload.
I tried onload="functionName;" in tags, but no effect.
I used window.onload="functionName"; in end of the script tags, but no effect.
I just could use
window.onload=function somefuntion() {
in function declaration and in worked.
But just for one method I can do that and when I do in this way the onclick method does not work.
How can I use these methods in onload and in onclick both? in my satisfied tags?
Maybe just:
window.addEventListener("load", function(event){
someFunc1();
someFunc2();
},false);
Related
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 have a selector list with two opinions inside. I want to run a block of code if the first is selected, and a different code if the other is selected. I have used if else for this.
So far I have assigned each select opinion a value, and the code works, but won't change if I choose opinion two...
What am I doing wrong here?
< script type = "text/javascript" >
window.onload = checkGender;
function checkGender() {
document.getElementById("btnFortune").onclick = chooseFortune;
}
function chooseFortune() {
if (document.getElementById("male").value === "1") {
var name = document.getElementById("name").value;
var formulaMale = name.length * document.getElementById("age").value - document.getElementById("height").value;
document.getElementById("fortuneTxt").innerHTML = formulaMale;
} else {
document.getElementById("fortuneTxt").innerHTML = "Test";
}
} <
/script>
<!DOCTYPE html>
<html>
<head>
<title>Spådom</title>
<meta charset="utf-8">
<body>
<h1>Fortune teller</h1>
<input type="text" id="name" placeholder="Tell me your name.."><br/>
<input type="number" id="age" placeholder="Your age.."><br/>
<input type="number" id="height" placeholder="And height..(in cm)"><br/>
<select>
<option id="male" value="1">Male</option>
<option id="female" value="2">Female</option>
</select><br/>
<button type="button" id="btnFortune">Tell me my fortune!</button>
<p id="fortuneTxt"></p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Spådom</title>
<meta charset="utf-8">
<script type="text/javascript">
window.onload = checkGender;
function checkGender() {
document.getElementById("btnFortune").onclick = chooseFortune;
}
function chooseFortune() {
if (document.getElementById("male").value === "1") {
var name = document.getElementById("name").value;
var formulaMale = name.length * document.getElementById("age").value - document.getElementById("height").value;
document.getElementById("fortuneTxt").innerHTML = formulaMale;
}
else {
document.getElementById("fortuneTxt").innerHTML = "Test";
}
}
</script>
</head>
<body>
<h1>Fortune teller</h1>
<style type="text/css">
</style>
<input type="text" id="name" placeholder="Tell me your name.."><br/>
<input type="number" id="age" placeholder="Your age.."><br/>
<input type="number" id="height" placeholder="And height..(in cm)"><br/>
<select>
<option id="male" value="1">Male</option>
<option id="female" value="2">Female</option>
</select><br/>
<button type="button" id="btnFortune">Tell me my fortune!</button>
<p id="fortuneTxt"></p>
</body>
</html>
Use onchange="chooseFortune()" to call the function when the select box selected item is changed. And give id to select not option
function chooseFortune() {
if (document.getElementById("gender").value == "1") {
var name = document.getElementById("name").value;
var formulaMale = name.length * document.getElementById("age").value - document.getElementById("height").value;
document.getElementById("fortuneTxt").innerHTML = formulaMale;
} else {
document.getElementById("fortuneTxt").innerHTML = "Test";
}
}
body {
margin: 0;
}
<h1>Fortune teller</h1>
<input type="text" id="name" placeholder="Tell me your name.."><br/>
<input type="number" id="age" placeholder="Your age.."><br/>
<input type="number" id="height" placeholder="And height..(in cm)"><br/>
<select id="gender" onchange="chooseFortune()">
<option value="1">Male</option>
<option value="2">Female</option>
</select><br/>
<button type="button" id="btnFortune">Tell me my fortune!</button>
<p id="fortuneTxt"></p>
You need to select the gender like shown below!
First assign an ID to the select element like.
<select id="gender">
<option id="male" value="1">Male</option>
<option id="female" value="2">Female</option>
</select>
Then using the below javascript lines you can get the selected value!
var select = document.getElementById("gender");
if (select.options[select.selectedIndex].value === "1") {
console.log("Male");
}else{
console.log("Female");
}
window.onload = checkGender;
function checkGender() {
document.getElementById("btnFortune").onclick = chooseFortune;
}
function chooseFortune() {
var select = document.getElementById("gender");
if (select.options[select.selectedIndex].value === "1") {
var name = document.getElementById("name").value;
var formulaMale = name.length * document.getElementById("age").value - document.getElementById("height").value;
document.getElementById("fortuneTxt").innerHTML = formulaMale;
} else {
document.getElementById("fortuneTxt").innerHTML = "Test";
}
}
<!DOCTYPE html>
<html>
<head>
<title>Spådom</title>
<meta charset="utf-8">
<body>
<h1>Fortune teller</h1>
<input type="text" id="name" placeholder="Tell me your name.."><br/>
<input type="number" id="age" placeholder="Your age.."><br/>
<input type="number" id="height" placeholder="And height..(in cm)"><br/>
<select id="gender">
<option id="male" value="1">Male</option>
<option id="female" value="2">Female</option>
</select><br/>
<button type="button" id="btnFortune">Tell me my fortune!</button>
<p id="fortuneTxt"></p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Spådom</title>
<meta charset="utf-8">
<script type="text/javascript">
window.onload = checkGender;
function checkGender() {
document.getElementById("btnFortune").onclick = chooseFortune;
}
function chooseFortune() {
var select = document.getElementById("gender");
if (select.options[select.selectedIndex].value === "1") {
var name = document.getElementById("name").value;
var formulaMale = name.length * document.getElementById("age").value - document.getElementById("height").value;
document.getElementById("fortuneTxt").innerHTML = formulaMale;
} else {
document.getElementById("fortuneTxt").innerHTML = "Test";
}
}
</script>
</head>
<body>
<h1>Fortune teller</h1>
<style type="text/css">
</style>
<input type="text" id="name" placeholder="Tell me your name.."><br/>
<input type="number" id="age" placeholder="Your age.."><br/>
<input type="number" id="height" placeholder="And height..(in cm)"><br/>
<select id="gender">
<option id="male" value="1">Male</option>
<option id="female" value="2">Female</option>
</select><br/>
<button type="button" id="btnFortune">Tell me my fortune!</button>
<p id="fortuneTxt"></p>
</body>
</html>
I have three different forms, when each form is filled the keypress "enter" fires and shows a picture. I have two pictures and both are firing at the same time but I want one to fire when enter is pressed once and the other one fired when the second form is completed but they both fire at the same time.
This is my HTML:
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="Opdracht4_5.js"></script>
<link rel="stylesheet" href="Opdracht%204_5.css">
<title></title>
</head>
<h1 span class="white">Info Day</span> <span class="blue">Registration</span></h1>
<body>
<form name="form1" onsubmit="validateForm()" method="post">
<fieldset id="fieldset1">
<legend>Step 1</legend>
How many people will be attending?
<select name = step1 id="step1" onchange="showField()">
<option value="0">Please Choose</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<br>
<div id="divName"></div>
<img id="check" src="check.png">
</fieldset>
</form>
<form name="form2" onsubmit="return validateForm()" method="post">
<fieldset id= "fieldset2">
<legend>Step 2</legend>
Would you like your company name on your badges?<br>
<input type="radio" id="companyYes" name="company">Yes<input type="radio" id="companyNo" name="company">No<br>
<input type="text" id="companyText">
<br>
<div id="company"></div>
Will anyone in your group require special accommodations?<br>
(if yes) Please explain below:<br>
<input type="radio" name="special" id="specialYes" value="Yes">Yes<input type="radio" id="specialNo" name="special" value="No">No<br>
<input type="text" id="specialText">
<img id="check2" src="check.png">
</fieldset>
</form>
<form>
<fieldset id="fieldset3">
<legend>Step 3</legend>
I confirm that all provided data is accurate? <br>
<input type="checkbox" name="complete" value="complete"><input type="submit" name="register" value="Complete Registration">
</fieldset>
</form>
</body>
</html>
This is my JS:
function showField(){
var selectDropDown = $("#step1");
var value = selectDropDown.val();
var insertDiv = $("#divName");
var innerHtmlString = "";
var value2 = $("#Yes")
if(value > 0){
innerHtmlString = "<b>Please provide full names: </b> <br/>";
}
for(i = 0; i < value; i++){
innerHtmlString += "<i>Attendee " + (i+1) + " Name:</i> <input type='text' name='"+(i+1)+"' /> </br><br/>";
}
insertDiv.html(innerHtmlString);
};
$(document).on("keypress", function (e) {
if (e.which == 13 || e.keyCode == 13){
$("#check").show();
}
});
$(document).on("")
function validateForm(){
alert("test");
}
$(Document).on("click",function(){
});
$( document ).ready(function() {
$("#check").hide();
$("#specialText").hide();
$("#companyText").hide();
$("#check2").hide();
$("#companyYes").on("click", function() {
$("#companyText").show();
});
$("#companyNo").on("click", function() {
$("#companyText").hide();
});
$("#specialYes").on("click", function() {
$("#specialText").show();
});
$("#specialNo").on("click", function() {
$("#specialText").hide();
});
});
$(document).ready();
$(document).on("keypress", function (e) {
if (e.which == 13 || e.keyCode == 13){
$("#check2").show();
}
});
$(document).on("")
How do I fix this?
You have two $(document).on("keypress", function {}) events which should be one and you can check whether the #check is visible. If it is not visible then show this otherwise show the second image as below.
$(document).on("keypress", function (e) {
if (e.which == 13 || e.keyCode == 13){
if($("#check").is(':visible')) {
$("#check2").show();
} else {
$("#check").show();
}
}
});
Notes:
You had two $(document).on("") which is invalid and should be
removed (commented below).
And the Document in $(Document).on("click",function(){}) is also
wrong and should be removed.
Also, in your html the h1 tag is not closed properly as <h1 span
class="white"> which should be <h1> <span class="white">
Working snippet:
function showField(){
var selectDropDown = $("#step1");
var value = selectDropDown.val();
var insertDiv = $("#divName");
var innerHtmlString = "";
var value2 = $("#Yes")
if(value > 0){
innerHtmlString = "<b>Please provide full names: </b> <br/>";
}
for(i = 0; i < value; i++){
innerHtmlString += "<i>Attendee " + (i+1) + " Name:</i> <input type='text' name='"+(i+1)+"' /> </br><br/>";
}
insertDiv.html(innerHtmlString);
};
$(document).on("keypress", function (e) {
if (e.which == 13 || e.keyCode == 13){
if($("#check").is(':visible')) {
$("#check2").show();
} else {
$("#check").show();
}
}
});
//$(document).on("")
function validateForm(){
alert("test");
}
/*$(Document).on("click",function(){
});*/
$( document ).ready(function() {
$("#check").hide();
$("#specialText").hide();
$("#companyText").hide();
$("#check2").hide();
$("#companyYes").on("click", function() {
$("#companyText").show();
});
$("#companyNo").on("click", function() {
$("#companyText").hide();
});
$("#specialYes").on("click", function() {
$("#specialText").show();
});
$("#specialNo").on("click", function() {
$("#specialText").hide();
});
});
/*$(document).ready();
$(document).on("keypress", function (e) {
if (e.which == 13 || e.keyCode == 13){
$("#check2").show();
}
});
$(document).on("")*/
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="Opdracht4_5.js"></script>
<link rel="stylesheet" href="Opdracht%204_5.css">
<title></title>
</head>
<h1> <span class="white">Info Day</span> <span class="blue">Registration</span></h1>
<body>
<form name="form1" onsubmit="validateForm()" method="post">
<fieldset id="fieldset1">
<legend>Step 1</legend>
How many people will be attending?
<select name = step1 id="step1" onchange="showField()">
<option value="0">Please Choose</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<br>
<div id="divName"></div>
<img id="check" src="check.png">
</fieldset>
</form>
<form name="form2" onsubmit="return validateForm()" method="post">
<fieldset id= "fieldset2">
<legend>Step 2</legend>
Would you like your company name on your badges?<br>
<input type="radio" id="companyYes" name="company">Yes<input type="radio" id="companyNo" name="company">No<br>
<input type="text" id="companyText">
<br>
<div id="company"></div>
Will anyone in your group require special accommodations?<br>
(if yes) Please explain below:<br>
<input type="radio" name="special" id="specialYes" value="Yes">Yes<input type="radio" id="specialNo" name="special" value="No">No<br>
<input type="text" id="specialText">
<img id="check2" src="check.png">
</fieldset>
</form>
<form>
<fieldset id="fieldset3">
<legend>Step 3</legend>
I confirm that all provided data is accurate? <br>
<input type="checkbox" name="complete" value="complete"><input type="submit" name="register" value="Complete Registration">
</fieldset>
</form>
</body>
</html>
I want to replace the after-submission checks in the form with on-the-fly completeness and correctness checks that are performed when a form field loses focus.
How can I do this?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>
<head>
<title>Form</title>
<style>
body {
width: 500px;
}
.part {
width: 100%;
padding: 5px;
border-bottom: 1px solid #000;
}
label {
margin-right: 5px;
}
.label-left {
text-align: right;
}
.label-right {
text-align: left;
}
.error {
color: #cc0000;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
//$(document).ready(function() {
function myValidateEMailAddress(email_address) {
var email_pattern = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return email_pattern.test(email_address);
}
function checkPassword(pwd_str) {
var my_pwd_pattern = /^(?=.*[a-zA-Z].*[a-zA-Z])(?=.*\d.*\d)[a-zA-Z0-9_]{6,20}$/;
return my_pwd_pattern.test(pwd_str);
}
function validatePhoneNumber(phone_number) {
var phone_pattern = /^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$/;
return phone_pattern.test(phone_number);
}
$(document).ready(function() {
$('#form').submit(function(e) {
var my_errors = false;
$('.part> .error').remove();
$('#my_submission').empty();
$(':text, :password, textarea').each(function() {
$(this).val($.trim($(this).val()));
if ($(this).val() == '') {
$(this).parent().append('<div class="error">Please provide a value</div>');
my_errors = true;
}
});
if ($('#email').val() != '') {
if (!myValidateEMailAddress($('#email').val())) {
$('#email').parent().append('<div class="error">Please provide a correct e-mail address</div>');
my_errors = true;
}
}
if ($('#your_password').val() != '') {
if (!checkPassword($('#your_password').val())) {
$('#your_password').parent().append('<div class="error">Please provide a correct password.</div>');
my_errors = true;
}
}
if ($('#phone').val() != '') {
if (!validatePhoneNumber($('#phone').val())) {
$('#phone').parent().append('<div class="error">Please provide a correct phone number.</div>');
my_errors = true;
}
}
if ($('#addresses option:selected').val() == '') {
$('#addresses').parent().append('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($(':radio[name="sex"]:checked').length == 0) {
$(':radio[name="sex"]:first').parent().after('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($(':radio[name="subscription"]:checked').length == 0) {
$(':radio[name="subscription"]:first').parent().after('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($('#likes option:selected').val() == '') {
$('#likes').parent().append('<div class="error">Please select one item</div>');
my_errors = true;
}
if (my_errors) {
return false;
}
else {
e.preventDefault();
var my_submission_array = $('#form').serialize().split('&');
if (my_submission_array.length > 0) {
$('#my_submission').html('<h2>Submitted Elements</h2><ul></ul>');
for (var i = 0; i < my_submission_array.length; i++) {
var my_pair = my_submission_array[i].split('=');
$('#my_submission > ul').append('<li>' + my_pair[0] + ': ' + my_pair[1] + '</li>\n');
}
}
}
});
});
// });
</script>
</head>
<body>
<h3>Output:</h3>
<h2>My Questionnaire</h2>
<form name="form" id="form" action="" method="post">
<div class="part">
<label for="addresses" class="label-left">How should you be addressed?</label>
<select name="addresses" id="addresses">
<option value="">Please select one</option>
<option value="first">Mr.</option>
<option value="second">Madam</option>
<option value="third">Miss</option>
<option value="fourth">Dr.</option>
<option value="fifth">Pr.</option>
</select>
</div>
<div class="part">
<fieldset>
<legend>Sex:</legend>
<input type="radio" name="sex" id="group1" value="1">
<label for="group1" class="label-right">Male</label>
<input type="radio" name="sex" id="group2" value="2">
<label for="group2" class="label-right">Female</label>
</fieldset>
</div>
<div class="part">
<label for="last_name" class="label-left">Last Name: </label>
<input type="text" name="last_name" id="last_name">
</div>
<div class="part">
<label for="first_name" class="label-left">First Name: </label>
<input type="text" name="first_name" id="first_name">
</div>
<div class="part">
<label for="email" class="label-left">E-Mail: </label>
<input type="text" name="email" id="email">
</div>
<div class="part">
<label for="your_password">Password:</label>
<input type="password" name="your_password" id="your_password" size="10" maxlength="20">
</div>
<div class="part">
<label for="phone" class="label-left">Phone number: </label>
<input type="text" name="phone" id="phone">
</div>
<div class="part">
<label for="likes" class="label-left">What are your likes?</label>
<select name="likes" id="likes">
<option value="">Please select one</option>
<option value="first">Programming</option>
<option value="second"> African literature</option>
<option value="third">Poetry</option>
<option value="four">Dancing</option>
</select>
</div>
<div class="part">
<fieldset>
<legend>Do you want to receive our newsletter ?</legend>
<input type="radio" name="subscription" id="group1" value="1">
<label for="group1" class="label-right">Yes</label>
<input type="radio" name="letter" id="group2" value="2">
<label for="group2" class="label-right">No</label>
</fieldset>
</div>
<div class="part">
<label for="comments" class="label-left">Write some comments below:</label>
<textarea name="comments" id="comments" cols="40" rows="3"></textarea>
</div>
<div class="part">
<input type="submit" name="submit" id="submit" value="Submit Form">
</div>
<div id="my_submission"></div>
</form>
</body>
</html>
Before I continue answering, I should note that you're putting jQuery script before <html> tag. This is incorrect. It has to be in <head>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
...
performed when a form field loses focus
An element loses focus when you click away from it. jQuery happends to have a blur event for this occasion:
$('input').on('blur', function() {
// your code here
});
So you might want to do it this way:
$('#email').on('blur', function() {
var emailVal = $(this).val();
if (!emailVal || !myValidateEMailAddress(emailVal)) {
$(this).parent().append('<div class="error">Please provide a correct e-mail address</div>');
my_errors = true;
}
});
the rest of the code might look similar.
I have 2 div tags in my HTML code and I have defined a class by which I can expand or hide them.The problem that I have is the fact that when I click on one of the the value of the other changes.
<HTML>
<BODY>
<FORM>
<script language="JavaScript">
function setVisibility(id) {
if (document.getElementById('btnshowhide').value == '-') {
document.getElementById('btnshowhide').value = '+';
document.getElementById(id).style.display = 'none';
} else {
document.getElementById('btnshowhide').value = '-';
document.getElementById(id).style.display = 'inline';
}
}
</script>
<FIELDSET style="width: 600px;">
<LEGEND>
<input type=button name=type id='btnshowhide' value='+' onclick="setVisibility('div1');" ;/>Insert Data:</LEGEND>
<DIV id="div1" style="display: none;">
<LABEL for="351fef76-b826-426f-88c4-dbaaa60f886b">Name:</LABEL>
<TEXTAREA id="351fef76-b826 -426f-88c4-dbaaa60f886b" name="txtname" value="Name" type="text" title="Name:">Name</TEXTAREA>
<BR>
<LABEL for="02973dcc-5677-417c-a9bf-1578f58923ef">Family:</LABEL>
<TEXTAREA id="02973dcc-5677-417c-a9bf-1578f58923ef" name="txtFamiy" value="Family" type="text" title="Family:">Family</TEXTAREA>
<BR>
</DIV>
</FIELDSET>
<BR>
<FIELDSET style="width: 600px;">
<LEGEND>
<input type=button name=type id='btnshowhide' value='+' onclick="setVisibility('div2');" ;/>Insert Data:</LEGEND>
<DIV id="div2" style="display: none;">
<LABEL for="d8876943-5861-4d62-9249-c5fef88219fa">Type of property</LABEL>
<SELECT id="d8876943-5861-4d62-9249-c5fef88219fa" name="PropertyType" value="" type="select" title="Type of property"></SELECT>
<BR>
</DIV>
</FIELDSET>
<BR>
</FORM>
</BODY>
</HTML>
I tried changing the Ids of my buttons but nothing changed.
change you buttons to --
<input type="button" name="type" id="btnshowhide1" value="+" onclick="setVisibility('div1',this.id);";/>
and
<input type="button" name="type" id="btnshowhide2" value="+" onclick="setVisibility('div2',this.id);";/>
And use following function --
function setVisibility(id,buttonid) {
if(document.getElementById(buttonid).value=='-'){
document.getElementById(buttonid).value = '+';
document.getElementById(id).style.display = 'none';
}
else{
document.getElementById(buttonid).value = '-';
document.getElementById(id).style.display = 'inline';
}
}
DEMO
First of all, you shouldn`t have two elements with same ID. You should use class for it.
And it happens because you have both buttons with id="btnshowhide" so when you are trying to do document.getElementById('btnshowhide').value it matches you both buttons.
you can do something like this
<script language="JavaScript">
function setVisibility(id,input)
{
if(input.value=='-')
{
input.value = '+';
document.getElementById(id).style.display = 'none';
}
else
{
input.value = '-';
document.getElementById(id).style.display = 'inline';
}
}
</script>
and in your inputs
onclick="setVisibility('div1', this);"
onclick="setVisibility('div2', this);"