If else statement with string JavaScript - javascript

I am designing a page where can display score when the users make their choices.
However, this code seems not working and does not show any result in the 'score' field.
My Html code:
<tr>
<td>
<div>
<input list="typeList" name="type" id="type">
<datalist id="typeList">
<option value="basketball">
<option value="soccer">
<option value="table tenis">
</datalist>
</div>
</td>
<td><input type="text" id="score" name="score" autocomplete="off"></td>
</tr>
My Script is below:
var type = document.getElementById("type");
var score = document.getElementById("score");
if (type === 0) {
score.value = 0;
} else if (type === 'basketball') {
score.value = 1;
} else if (type === 'soccer') {
score.value = 2;
} else if (type === 'table tenis') {
score.value = 3;
}

I have used Jquery in this, The mistake you made is, there is no watch for the event.
$('#type').on('input',function(e){
var type = document.getElementById("type").value;
var score = document.getElementById("score");
if (type === 0) { score.value = 0; }
else if (type === 'basketball') { score.value = 1; }
else if (type === 'soccer') { score.value = 2; }
else if (type === 'table tenis') { score.value = 3; }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<div>
<input list="typeList" name="type" id="type">
<datalist id="typeList">
<option value="basketball">
<option value="soccer">
<option value="table tenis">
</datalist>
</div>
</td>
<td><input type="text" id="score" name="score" autocomplete="off"></td>
</tr>
Hope this helps

var type = document.getElementById("type");
//...
here should be var type = document.getElementById("type").value;
and also
if (type === 0) {
to
if (type === "0") {

You were able to access the element. You just need to use the value attribute of the element. You need to add the event change with dropdown so that it can bind the data in the score textbox when index is changed.
var type = document.getElementById("type");
var score = document.getElementById("score");
type.addEventListener('change', function() {
if (type.value === 0) {
score.value = 0;
} else if (type.value === 'basketball') {
score.value = 1;
} else if (type.value === 'soccer') {
score.value = 2;
} else if (type.value === 'table tennis') {
score.value = 3;
}
});
<tr>
<td>
<div>
<input list="typeList" name="type" id="type">
<datalist id="typeList">
<option value="basketball">
<option value="soccer">
<option value="table tennis">
</datalist>
</div>
</td>
<td><input type="text" id="score" name="score" autocomplete="off" ></td>
</tr>

You need to add a event listener (or two, one for change and one for input) and then wrap your code in a function:
var type = document.getElementById("type");
var score = document.getElementById("score");
type.addEventListener("change", function() {
myFunction(type.value);
});
type.addEventListener("input", function() {
myFunction(type.value);
});
var myFunction = function(type) {
if (type === 0) {
score.value = 0;
} else if (type === 'basketball') {
score.value = 1;
} else if (type === 'soccer') {
score.value = 2;
} else if (type === 'table tenis') {
score.value = 3;
}
}
<tr>
<td>
<div>
<input list="typeList" name="type" id="type">
<datalist id="typeList">
<option value="basketball">
<option value="soccer">
<option value="table tenis">
</datalist>
</div>
</td>
<td><input type="text" id="score" name="score" autocomplete="off"></td>
</tr>

in your if it should be
type.value
to get the value of the input box. Also when are you running the script?

// you forgot to attach the value property of the type element
var typeValue = document.getElementById("type").value;
// the result for typeValue is allways a string or undefined
var scoreElement = document.getElementById("score");
// a swtich case is more efficient here
swtich(typeValue){
case 'basketball':
scoreElement.value = 1;
break;
case 'soccer':
scoreElement.value = 2:
break;
case 'table tenis'
scoreElement.value = 3;
break;
default:
sourceElement.value = 0;
}

Here you go with pure JavaScript along with jsfiddle https://jsfiddle.net/4oyrw61w/
document.getElementById('type').addEventListener('input', function () {
var type = document.getElementById("type").value;
var score = document.getElementById("score");
if (type === '0') {
score.value = 0;
} else if (type === 'basketball') {
score.value = 1;
} else if (type === 'soccer') {
score.value = 2;
} else if (type === 'table tenis') {
score.value = 3;
}
});

Related

Using Conditionals in JavaScript to print a message in HTML

I created a calculator using HTML and JavaScipt. The calculator works, so that is fine. However, I would like to write a message in the html that lets the user know they have to enter a variable, if the result is NaN. While I know I need to use a conditional statement, I am not sure how to code it.
Here is my code:
function calc(){
var n1 = parseFloat(document.getElementById("n1").value);
var n2 = parseFloat(document.getElementById("n2").value);
var oper = document.getElementById("operators").value;
if( oper === "+"){
document.getElementById("result").value = n1+n2;
}
if( oper === "-"){
document.getElementById("result").value = n1-n2;
}
if( oper === "*"){
document.getElementById("result").value = n1*n2;
}
if( oper === "/"){
document.getElementById("result").value = n1/n2;
}
if( oper === NaN ){
document.getElementById("Comments").innerHTML= "Write something in the boxes, you silly ass." ;
}
}
<input type="text" id="n1"/><br/><br/>
<input type="text" id="n2"/><br/><br>
<select id="operators">
<option value="+">+</option>
<option value="-">-</option>
<option value="X">X</option>
<option value="/">/</option>
</select>
<input type="text" id="result"/>
<button onclick="calc();">=</button>
<p id="Comments"></p>
To improve your code you can add else if and isNaN, like this:
function calc(){
var n1 = parseFloat(document.getElementById("n1").value);
var n2 = parseFloat(document.getElementById("n2").value);
var oper = document.getElementById("operators").value;
if( oper === "+"){
document.getElementById("result").value = n1+n2;
} else if( oper === "-"){
document.getElementById("result").value = n1-n2;
} else if( oper === "*"){
document.getElementById("result").value = n1*n2;
} else if( oper === "/"){
document.getElementById("result").value = n1/n2;
} else if( isNaN(oper) ){
document.getElementById("Comments").innerHTML= "Write something in the boxes, you silly ass." ;
}
}
<input type="text" id="n1"/><br/><br/>
<input type="text" id="n2"/><br/><br>
<select id="operators">
<option value="+">+</option>
<option value="-">-</option>
<option value="X">X</option>
<option value="/">/</option>
</select>
<input type="text" id="result"/>
<button onclick="calc();">=</button>
<p id="Comments"></p>
Use the isNaN function to check for it
function calc(){
var n1 = parseFloat(document.getElementById("n1").value);
var n2 = parseFloat(document.getElementById("n2").value);
var oper = document.getElementById("operators").value;
if( oper === "+"){
document.getElementById("result").value = n1+n2;
}
if( oper === "-"){
document.getElementById("result").value = n1-n2;
}
if( oper === "*"){
document.getElementById("result").value = n1*n2;
}
if( oper === "/"){
document.getElementById("result").value = n1/n2;
}
if( isNaN(oper) ){
document.getElementById("Comments").innerHTML= "Write something in the boxes, you silly ass." ;
}
}
<input type="text" id="n1"/><br/><br/>
<input type="text" id="n2"/><br/><br>
<select id="operators">
<option value="+">+</option>
<option value="-">-</option>
<option value="X">X</option>
<option value="/">/</option>
</select>
<input type="text" id="result"/>
<button onclick="calc();">=</button>
<p id="Comments"></p>
I'll provide this as a more concise version. There's no reason to select an element more than once if you plan on altering it later. Using the object as a container for your options allows you to validate and execute a bit easier.
const options = {
'+'(a, b) { return a + b },
'-'(a, b) { return a - b },
'*'(a, b) { return a * b },
'/'(a, b) { return a / b }
};
function calc(){
var n1 = parseFloat(document.getElementById("n1").value);
var n2 = parseFloat(document.getElementById("n2").value);
var oper = document.getElementById("operators").value;
const resEl = document.getElementById("result");
resEl.value = '';
const comEl = document.getElementById("Comments");
comEl.innerHTML = '';
let result;
let targetEl;
if (isNaN(n1) || isNaN(n2)) {
targetEl = comEl;
result = "Write something valid in the boxes, silly.";
}
else if (options[oper]) {
target = resEl;
result = options[oper](n1, n2);
}
else {
targetEl = comEl;
result = "Pick an operation." ;
}
let prop = typeof result === 'string' ? 'innerHTML' : 'value';
targetEl[prop] = result;
}

HTML/Javascript Form How do I serialize form data as JSON and displayed in a class?

Pretty straight forward.
When a user clicks "submit", I need the form serialized and the JSON data displayed in the class"debug".
How do I do this with my current Javascript?
Cannot use jQuery. Cannot edit HTML. Only pure Javascript.
Thanks!
HTML
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
JS
function validate(form) {
fail = validateAge(form.age.value)
fail += validateRel(form.rel.value)
if (fail == "") return true
else {
alert(fail);
return false
}
}
function validateAge(field) {
if (isNaN(field)) return "No age was entered. \n"
else if (field < 1 || field > 200)
return "Age must be greater than 0. \n"
return ""
}
function validateRel(field) {
if (field == "") return "Please select a relationship \n"
return ""
}
document.querySelector("form").onsubmit = function() {
return validate(this)
}
document.querySelector(".add").onclick = function(event) {
event.preventDefault();
createinput()
}
count = 0;
function createinput() {
field_area = document.querySelector('.household')
var li = document.createElement("li");
var p1 = document.createElement("p");
var p2 = document.createElement("p");
var p3 = document.createElement("p");
var x = document.getElementsByName("age")[0].value;
var y = document.getElementsByName("rel")[0].value;
var z = document.getElementsByName("smoker")[0].checked;
if (!z) {
z = "Non smoker \n";
} else {
z = "Smoker \n";
}
p1.innerHTML = x;
p2.innerHTML = y;
p3.innerHTML = z;
li.appendChild(p1);
li.appendChild(p2);
li.appendChild(p3);
field_area.appendChild(li);
//removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
// serialize form
var data = {};
var inputs = [].slice.call(e.target.querySelector('form'));
inputs.forEach(input => {
data[input.name] = input.value;
});
The shortest possible solution (pure javascript):
var form = document.querySelector('form');
var data = new FormData(form);
docs: https://developer.mozilla.org/en-US/docs/Web/API/FormData
I know this form very well as I applied for same job position.It is an interesting task. Here is your answer with pure js!
var peopleList = [];
var addButton = document.querySelector('button.add');
var submitButton = document.querySelector('button[type=submit]');
var debug = document.querySelector('pre.debug');
var mainForm = document.forms[0];
var ageFormField = mainForm.age;
var relationshipFormField = mainForm.rel;
var smokerFormField = mainForm.smoker;
var positionFormField=mainForm.position;
//Taken from https://www.inventpartners.com/open-source/free-web-software/javascript_is_int
function is_int(value) {
if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
return true;
} else {
return false;
}
}
function formIsValid() {
return ageFormField.value != '' && is_int(ageFormField.value) && relationshipFormField.selectedIndex != 0 && positionFormField.value !='';
}
function updateDebug() {
if (peopleList.length != 0) {
debug.innerText = JSON.stringify(peopleList);
debug.setAttribute('style', 'display: block');
submitButton.disabled = false;
} else {
debug.innerText = '';
debug.removeAttribute('style');
submitButton.disabled = true;
}
}
function addEventClick(event) {
event.preventDefault();
if (formIsValid()) {
peopleList.push({
'age': ageFormField.value,
'position':positionFormField.value,
'relationship': relationshipFormField.options[relationshipFormField.selectedIndex].value,
'isSmoker': smokerFormField.checked,
});
updateDebug();
ageFormField.value = '';
positionFormField.value='';
relationshipFormField.selectedIndex = 0;
smokerFormField.checked = false;
} else {
var errors = '';
if (ageFormField.value == '') {
errors += 'Please enter your age!';
} else if (!is_int(ageFormField.value)) {
errors += 'Age must be a numeric value!';
}
if (relationshipFormField.selectedIndex == 0) {
if (errors != '') {
errors += '\n';
}
errors += 'Please select your relationship status!';
}
if (positionFormField.value == '') {
if (errors != '') {
errors += '\n';
}
errors += 'Please enter your position!';
}
if (errors != '') {
alert(errors);
errors = '';
}
else if (
errors != '') {
alert(errors);
errors = '';
}
}
}
function submitEventClick(event) {
event.preventDefault();
if (peopleList.length != 0) {
var http = new XMLHttpRequest();
var url = "savePeopleList.php";
http.open('POST', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
if (http.readyState == 4) {
if (http.status == 200) {
peopleList = [];
updateDebug();
alert('All of the changes were saved to the server!');
} else {
alert('An error occured while sending the data to the server!');
}
}
};
http.send(JSON.stringify(peopleList));
}
}
addButton.addEventListener('click', addEventClick, false);
submitButton.addEventListener('click', submitEventClick, false);
updateDebug();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Household builder</title>
<style>
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
</style>
</head>
<body>
<h1>Household builder</h1>
<div class="builder">
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Position
<input type="text" name="position">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
Iterate through the form, grabbing the various elements and creating new objects for each one, then setting the properties for each object and pushing to the final array would solve your problem fairly easily.
Then you can simply use querySelectorAll to match .debug and use JSON.stringify() to convert your array to a string and innerText to set the contents.
Example:
function go() {
var debug_class = document.querySelectorAll(".debug");
for (var i = 0; i < debug_class.length; i++) {
var element = debug_class[i];
element.innerText = JSON.stringify(serializeArray(document.querySelector("form")));
}
}
function serializeArray(form) {
var field, l, s = [];
if (typeof form == 'object' && form.nodeName == "FORM") {
var len = form.elements.length;
for (i = 0; i < len; i++) {
field = form.elements[i];
if (field.name && !field.disabled && field.type != 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') {
if (field.type == 'select-multiple') {
l = form.elements[i].options.length;
for (j = 0; j < l; j++) {
if (field.options[j].selected)
s[s.length] = {
name: field.name,
value: field.options[j].value
};
}
} else if ((field.type != 'checkbox' && field.type != 'radio') || field.checked) {
s[s.length] = {
name: field.name,
value: field.value
};
}
}
}
}
return s;
}
<form id="blah">
<input type="text" name="input1" value="a"></input>
<input type="text" name="input2" value="b"></input>
<input type="text" name="input3" value="c"></input>
<input type="text" name="input4" value="d"></input>
</form>
<button onclick="go()">Serialize!</button>
<div class="debug"></div>
EDIT
In your particular case, after including the above code, you would have to call go() at some point to generate the serialized data.
Here's how to do it after clicking on add
document.querySelector(".add").onclick = function(event) {
go(); // display in .debug
event.preventDefault();
createinput()
}
FULL SNIPPET
function go() {
var debug_class = document.querySelectorAll(".debug");
for (var i = 0; i < debug_class.length; i++) {
var element = debug_class[i];
element.innerText = JSON.stringify(serializeArray(document.querySelector("form")));
}
}
function serializeArray(form) {
var field, l, s = [];
if (typeof form == 'object' && form.nodeName == "FORM") {
var len = form.elements.length;
for (i = 0; i < len; i++) {
field = form.elements[i];
if (field.name && !field.disabled && field.type != 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') {
if (field.type == 'select-multiple') {
l = form.elements[i].options.length;
for (j = 0; j < l; j++) {
if (field.options[j].selected)
s[s.length] = {
name: field.name,
value: field.options[j].value
};
}
} else if ((field.type != 'checkbox' && field.type != 'radio') || field.checked) {
s[s.length] = {
name: field.name,
value: field.value
};
}
}
}
}
return s;
}
function validate(form) {
fail = validateAge(form.age.value)
fail += validateRel(form.rel.value)
if (fail == "") return true
else {
alert(fail);
return false
}
go();
}
function validateAge(field) {
if (isNaN(field)) return "No age was entered. \n"
else if (field < 1 || field > 200)
return "Age must be greater than 0. \n"
return ""
}
function validateRel(field) {
if (field == "") return "Please select a relationship \n"
return ""
}
document.querySelector("form").onsubmit = function() {
return validate(this)
}
document.querySelector(".add").onclick = function(event) {
go();
event.preventDefault();
createinput()
}
count = 0;
function createinput() {
field_area = document.querySelector('.household')
var li = document.createElement("li");
var p1 = document.createElement("p");
var p2 = document.createElement("p");
var p3 = document.createElement("p");
var x = document.getElementsByName("age")[0].value;
var y = document.getElementsByName("rel")[0].value;
var z = document.getElementsByName("smoker")[0].checked;
if (!z) {
z = "Non smoker \n";
} else {
z = "Smoker \n";
}
p1.innerHTML = x;
p2.innerHTML = y;
p3.innerHTML = z;
li.appendChild(p1);
li.appendChild(p2);
li.appendChild(p3);
field_area.appendChild(li);
//removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
// serialize form
var data = {};
var inputs = [].slice.call(e.target.querySelector('form'));
inputs.forEach(input => {
data[input.name] = input.value;
});
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>

HTML/Javascript Forms Checkbox Value Not Displaying

Pretty Straight forward problem.
When the user hits the "add" button and the checkmark is checked I would like the value to say "Smoker" in the class="household".
When the checkmark is not checked I would like the value to say "Non-smoker"
Currently, my "if else" statement isn't firing. Been looking everywhere to fix this. Can anyone help?
Side Note: No jQuery, Cannot edit the HTML. Only Pure Javascript.
HTML
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
JS
function validate(form) {
fail = validateAge(form.age.value)
fail += validateRel(form.rel.value)
if (fail == "") return true
else {
alert(fail);
return false
}
}
function validateAge(field) {
if (isNaN(field)) return "No age was entered. \n"
else if (field < 1 || field > 200)
return "Age must be greater than 0. \n"
return ""
}
function validateRel(field) {
if (field == "") return "Please select a relationship \n"
return ""
}
document.querySelector("form").onsubmit = function() {
return validate(this)
}
document.querySelector(".add").onclick = function(event) {
event.preventDefault();
createinput()
}
count = 0;
function createinput() {
field_area = document.querySelector('.household')
var li = document.createElement("li");
var p1 = document.createElement("p");
var p2 = document.createElement("p");
var p3 = document.createElement("p");
var x = document.getElementsByName("age")[0].value;
var y = document.getElementsByName("rel")[0].value;
var z = document.getElementsByName("smoker")[0].value.checked;
if( z === undefined) {
return ("Non smoker \n")
}
else {
return ("Smoker \n")
}
p1.innerHTML = x;
p2.innerHTML = y;
p3.innerHTML = z;
li.appendChild(p1);
li.appendChild(p2);
li.appendChild(p3);
field_area.appendChild(li);
//removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
The first problem is you are not getting the checkbox status right way. It should be document.getElementsByName("smoker")[0].checked instead of document.getElementsByName("smoker")[0].value.checked.
The second problem is you used return in if else. If you use return then the following codes of the function will not execute.
Change
var z = document.getElementsByName("smoker")[0].value.checked;
if( z === undefined) {
return ("Non smoker \n")
}
else {
return ("Smoker \n")
}
to
var z = document.getElementsByName("smoker")[0].checked;
if (!z) {
z = "Non smoker \n";
} else {
z = "Smoker \n";
}
Because you have only one "household" element you can add the following handler:
document.querySelectorAll('[name="smoker"]')[0].onclick = function() {
document.getElementsByClassName('household')[0].textContent =
this.checked ? 'Smoker' : 'Non-smoker';
}
The example:
function validate(form) {
fail = validateAge(form.age.value)
fail += validateRel(form.rel.value)
if (fail == "") return true
else {
alert(fail);
return false
}
}
function validateAge(field) {
if (isNaN(field)) return "No age was entered. \n"
else if (field < 1 || field > 200)
return "Age must be greater than 0. \n"
return ""
}
function validateRel(field) {
if (field == "") return "Please select a relationship \n"
return ""
}
count = 0;
function createinput() {
field_area = document.querySelector('.household')
var li = document.createElement("li");
var p1 = document.createElement("p");
var p2 = document.createElement("p");
var p3 = document.createElement("p");
var x = document.getElementsByName("age")[0].value;
var y = document.getElementsByName("rel")[0].value;
var z = document.getElementsByName("smoker")[0].checked;
if( !z ) {
z = "Non smoker";
}
else {
z = "Smoker";
}
p1.innerHTML = x;
p2.innerHTML = y;
p3.innerHTML = z;
li.appendChild(p1);
li.appendChild(p2);
li.appendChild(p3);
field_area.appendChild(li);
//removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
document.querySelector("form").onsubmit = function() {
return validate(this)
}
document.querySelector(".add").onclick = function(event) {
event.preventDefault();
createinput()
}
document.querySelectorAll('[name="smoker"]')[0].onclick = function() {
document.getElementsByClassName('household')[0].textContent = this.checked ? 'Smoker' : 'Non-smoker'
}
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>

Changing textfield currency type

<select data-placeholder="Please select a payment method.." style="width:50%;" class="chosen" onchange="currencyChange(this.value)">
<option value=""></option>
<optgroup label="Cash">
<option value="Paypal">Paypal</option>
<option value="Bitcoin">Bitcoin</option>
<option value="Western Union">Western Union</option>
<option value="Delivery">Delivery</option>
</optgroup>
<optgroup label="Ingame Currency">
<option value="RS3 GP">RS3 GP</option>
<option value="OSRS GP">OSRS GP</option>
</optgroup>
</select>
<script type="text/javascript">
var sign = "null";
var placement = "null";
float budget = "null";
function currencyChange(data){
if (data === 'Paypal') {
sign = "$";
placement = "before";
}
if (data === 'Bitcoin') {
sign = "$";
placement = "before";
}
if (data === 'Western Union') {
sign = "$";
placement = "before";
}
if (data === 'Delivery') {
sign = "$";
placement = "before";
}
if (data === 'RS3 GP') {
sign = "M/GP";
placement = "after";
}
if (data === 'OSRS GP') {
sign = "M/GP";
placement = "after";
}
if (placement === 'before') {
document.getElementById("budget").value = sign + document.getElementById("budget").value;
}
if (placement === 'after') {
document.getElementById("budget").value = document.getElementById("budget").value + sign;
}
}
</script>
I am trying to change the currency type of another textfield id="budget" to add a currency symbol dependent on the choice of payment method..?
But I get no such action when selecting the payment type.
remove this, Its works
float budget = "null";
And,
add below select
<input type="text" id="budget">
Edited
if (placement === 'before') {
toreplaceaft=document.getElementById("budget").value;
toreplacebef=toreplaceaft.replace("$","");
toreplace=toreplacebef.replace("M/GP","");
document.getElementById("budget").value = sign + toreplace.replace("$","");
}
if (placement === 'after') {
toreplaceaft=document.getElementById("budget").value;
toreplacebef=toreplaceaft.replace("$","");
toreplace=toreplacebef.replace("M/GP","");
document.getElementById("budget").value = toreplace+ sign;
}
Try this fiddle it will not accepting double sign.
http://jsfiddle.net/pee7d6qr/1/
if (placement === 'before') {
if(document.getElementById("budget").value.indexOf("$") == -1){
document.getElementById("budget").value = sign + document.getElementById("budget").value;
}
else {
document.getElementById("budget").value = document.getElementById("budget").value;
}
}
if (placement === 'after') {
if(document.getElementById("budget").value.indexOf("M/GP") == -1){
document.getElementById("budget").value = document.getElementById("budget").value + sign;
}
else {
document.getElementById("budget").value = document.getElementById("budget").value;
}
}
Remove the float variable in javascript
Budget Input element is missing
<input type="text" name="budget" id="budget" value=>
Use the below code
if (placement === 'before') {
document.getElementById("budget").value = sign + document.getElementById("budget").value.replace(/[^0-9.]/g,'');
}
if (placement === 'after') {
document.getElementById("budget").value = document.getElementById("budget").value.replace(/[^0-9.]/g,'') + sign;
}
Now you need to strip those "$,M/GP" stuff from the string
With little help from stackoverflow:
value = document.getElementById("budget").value;
value = value.replace(/\D/g,''); //strip non-numeric characters from string
Then
if (placement === 'before') {
document.getElementById("budget").value = sign +" "+ value;
}
if (placement === 'after') {
document.getElementById("budget").value = value +" "+ sign;
}
jsFiddle

How to show 0.00 when check box not checked?

How to display 0.00 in the totalcost field when check box not checked ?
<form id="form1">
<input type="checkbox" id='game0' value="9.99" onclick="UpdateCost()">Game 1 ( 9.99)<br>
<input type="checkbox" id='game1' value="19.99" onclick="UpdateCost()">Game 2 (19.99)<br>
<input type="checkbox" id='game2' value="27.50" onclick="UpdateCost()">Game 3 (27.50)<br>
<input type="checkbox" id='game3' value="45.65" onclick="UpdateCost()">Game 4 (45.65)<br>
<input type="checkbox" id='game4' value="87.20" onclick="UpdateCost()">Game 5 (87.20)<br>
<input type="checkbox" id='game5' value="87.20" onclick="UpdateCost()">Game 5 (87.20)<br>
<input type="text" id="totalcost" value="">
</form>
<script type="text/javascript">
var clickHandlers = (function () {
var form1 = document.getElementById("form1"),
totalcost = document.getElementById("totalcost"),
// if this is always the last input in the form, we could avoid hitting document again with
// totalcost = form1[form1.length - 1];
sum = 0;
form1.onclick = function (e) {
e = e || window.event;
var thisInput = e.target || e.srcElement;
if (thisInput.nodeName.toLowerCase() === 'input') {
if (thisInput.checked) {
sum += parseFloat(thisInput.value);
} else {
if (thisInput.type.toLowerCase() === 'checkbox') {
sum -= parseFloat(thisInput.value);
}
}
totalcost.value = (sum > 0) ? sum.toFixed(2) : "";
}
}
return null;
}());
</script>
Specify default value for the input:
<input type="text" id="totalcost" value="0.00">
Set the default value to 0.00:
totalcost.value = (sum > 0) ? sum.toFixed(2) : "0.00";
DEMO
var clickHandlers = (function () {
var form1 = document.getElementById("form1"),
totalcost = document.getElementById("totalcost"),
// if this is always the last input in the form, we could avoid hitting document again with
// totalcost = form1[form1.length - 1];
sum = 0;
form1.onclick = function (e) {
e = e || window.event;
var thisInput = e.target || e.srcElement;
if (thisInput.nodeName.toLowerCase() === 'input') {
if (thisInput.checked) {
sum += parseFloat(thisInput.value);
} else {
if (thisInput.type.toLowerCase() === 'checkbox') {
sum -= parseFloat(thisInput.value);
}
}
totalcost.value = (sum > 0) ? sum.toFixed(2) : "0.00";
}
}
return null;
}());

Categories

Resources