Dom Modification to clear Radio Button Info with Reset Button - javascript

So I have made a form that I can clear with a reset button. On this form, I have four radio buttons (that code is towards the top). When a button is selected, info comes up using "displayText".
<script type="text/javascript">
function textToDisplay (radioValue) {
console.log("textToDisplay + " + radioValue);
var displayText = "";
if (radioValue == "S") {
displayText = "Shortboards are under 7 ft in length.";
}
else if (radioValue == "L") {
displayText = "Longboards are usually between 8 and 10 ft.";
}
if (radioValue == "A") {
displayText = "Alternative boards defy easy aesthetic description.";
}
if (radioValue == "M") {
displayText = "Mid-Length surfboards are between 7 and 8 ft.";
}
return (displayText)
}
//DOM modification
function modifyDom(radioInput) {
console.log(radioInput.name + " + " + radioInput.value);
var displayText = textToDisplay(radioInput.value);
console.log(node);
var insertnode = document.getElementById("radioButtons");
var infonode = document.getElementById("info")
if (infonode === null) {
console.log("infonode does not yet exist");
var node = document.createElement("DIV");
node.setAttribute("id", "info");
node.className = "form-text infoText";
var textnode = document.createTextNode(displayText);
node.appendChild(textnode);
console.log(node);
insertnode.appendChild(node);
}
else {
console.log("infonode already exists");
infonode.innerHTML = displayText;
}
}
function checkboxesSelected (checkboxes, errorString) {
console.log("checkboxesSelected function");
var cbSelected = 0;
for (i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
cbSelected += 1;
}
}
if (cbSelected < 2) {
return (errorString);
} else {
return "";
}
}
function validate (form) {
console.log("validate form");
var fail = "";
fail += checkboxesSelected(form.extras, "At least TWO fin setup needs
to be selected.\n")
if (fail == "") return true
else { alert(fail); return false }
}
</script>
When I reset my page using the button,
<input type="reset" name="reset" value="Reset">
the buttons themselves are cleared but the information that appeared from selecting the button is still visible. How can I reset the page so the displayText information is not visible? Thanks!

You can use an event listener for the reset event generated by clicking the reset button to execute cleanup code.
Here's a cut down example of the technique:
"use strict";
let myForm = document.getElementById("myForm");
let infoNode = document.getElementById("infonode");
let infoText = {
"S": "small board's are good",
"L": "large board's are good too"
};
myForm.addEventListener("change", function (event) {
if(event.target.name == "size") {
infoNode.innerHTML = infoText[ event.target.value];
}
}, false);
myForm.addEventListener("reset", function (event) {
infoNode.innerHTML = "";
}, false);
<form id="myForm">
<label> <input name="size" type="radio" value = "S"> Short</label><br>
<label> <input name="size" type="radio" value = "L"> Long</label><br>
<input type="reset" value="reset">
</form>
<div id="infonode"></div>

would suggest to remove the dynamically attached div#info:
document.getElementById("info").remove();
or blank it:
document.getElementById("info").innerHTML = "";

Related

Calculator doesn't display result [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
*This calculator is only for one digit calculations
In my code there are 3 textboxes Two for values and one for Operators.
I want that if first textbox isn't empty and user clicks on any number than that value should be added in another textbox.
When I click Enter it doesn't display result and I didn't show any kind of error in console
// Textboxes, Enter and Reset
var txt1 = document.querySelector("#txt1");
var txt2 = document.querySelector("#txt2");
var txt3 = document.querySelector("#txt3");
var ent = document.querySelector("#ent");
var res = document.querySelector("#res");
// Number-Buttons
var b1 = document.querySelector("#b1");
var b2 = document.querySelector("#b2");
var b3 = document.querySelector("#b3");
var b4 = document.querySelector("#b4");
var b5 = document.querySelector("#b");
var b6 = document.querySelector("#b6");
var b7 = document.querySelector("#b7");
var b8 = document.querySelector("#b8");
var b9 = document.querySelector("#b9");
// Operators
var add = document.querySelector("#add");
var sub = document.querySelector("#sub");
var mul = document.querySelector("#mul");
var div = document.querySelector("#div");
if (txt1.value == "") {
function B1() { txt1.value = "1" }
function B2() { txt1.value = "2" }
function B3() { txt1.value = "3" }
function B4() { txt1.value = "4" }
function B5() { txt1.value = "5" }
function B6() { txt1.value = "6" }
function B7() { txt1.value = "7" }
function B8() { txt1.value = "8" }
function B9() { txt1.value = "9" }
if (txt2.value == "") {
function Add() { txt2.value = "+" }
function Sub() { txt2.value = "-" }
function Mul() { txt2.value = "*" }
function Div() { txt2.value = "/" }
}
// if (txt1.value != "" && txt3.value == "") {
// function B1() { txt3.value = "1" }
// function B2() { txt3.value = "2" }
// function B3() { txt3.value = "3" }
// function B4() { txt3.value = "4" }
// function B5() { txt3.value = "5" }
// function B6() { txt3.value = "6" }
// function B7() { txt3.value = "7" }
// function B8() { txt3.value = "8" }
// function B9() { txt3.value = "9" }
// }
}
function Ent() {
if (txt1.value == "" || txt2.value == "" || txt3.value == "") {
alert("Pls Enter values and select the operator");
}
function sum() {
if (txt2.value == "+") {
var Sum = Number(txt1.value) + Number(txt3.value);
alert(Sum);
console.log(Sum);
}
}
function sub() {
if (txt2.value == "-") {
var Sub = Number(txt1.value) - Number(txt3.value);
alert(Sub);
console.log(Sub);
}
}
function mul() {
if (txt2.value == "*") {
var Mul = Number(txt1.value) * Number(txt3.value);
alert(Mul);
console.log(Mul);
}
}
function div() {
if (txt2.value == "/") {
var Div = Number(txt1.value) / Number(txt3.value);
alert(Div);
console.log(Div);
}
}
}
I tried to understand what you want to do from the code you shared. In the solution you developed, I made subtractions as the numbers are defined as separate buttons. In this direction, I developed a lean solution. This program is used as follows:
Use the numeric keypad to enter the first number.
Click the action you want to perform (+, -, *, /)
Use the numeric keypad to enter the second number.
Click the CALCULATE button to see the result.
Click the CLEAR button to clear the screen.
var firstNumberText = document.getElementById("txt1");
var secondNumberText = document.getElementById("txt2");
var operatorText = document.getElementById("txt3");
var operationText = document.getElementById("txt4");
var resultText = document.getElementById("txt5");
var addButton = document.getElementById("add");
var subButton = document.getElementById("sub");
var mulButton = document.getElementById("mul");
var divButton = document.getElementById("div");
var enterButton = document.getElementById("enter");
var clearButton = document.getElementById("clear");
let status = true;
let currentFirstNumber = "";
let currentSecondNumber = "";
function updateText(){
firstNumberText.innerText = currentFirstNumber;
secondNumberText.innerText = currentSecondNumber;
}
function changeState(operator) {
operatorText.innerText = operator;
status = !status;
}
addButton.addEventListener("click", function() {
changeState("+");
});
subButton.addEventListener("click", function() {
changeState("-");
});
mulButton.addEventListener("click", function() {
changeState("*");
});
divButton.addEventListener("click", function() {
changeState("/");
});
function numberPressed(pressedButton) {
if(status)
currentFirstNumber += pressedButton.value;
else
currentSecondNumber += pressedButton.value;
}
function updateResult(result, operator) {
operationText.innerText = firstNumberText.textContent + operator + secondNumberText.textContent + "=" + `${result}`;
resultText.innerText = result;
}
function calculate() {
if (firstNumberText.value == "" || secondNumberText.value == "" || operatorText.value == "") {
alert("Warning");
return;
}
var result = 0;
if(operatorText.textContent == "+") {
result = parseInt(firstNumberText.textContent) + parseInt(secondNumberText.textContent);
updateResult(result, "+");
}
else if(operatorText.textContent == "-") {
result = parseInt(firstNumberText.textContent) - parseInt(secondNumberText.textContent);
updateResult(result, "-");
}
else if(operatorText.textContent == "*") {
result = parseInt(firstNumberText.textContent) * parseInt(secondNumberText.textContent);
updateResult(result, "*");
}
else if(operatorText.textContent == "/") {
result = parseInt(firstNumberText.textContent) / parseInt(secondNumberText.textContent);
updateResult(result, "/");
}
}
enterButton.addEventListener("click", function() {
calculate();
});
clearButton.addEventListener("click", function() {
status = true;
currentFirstNumber = "";
currentSecondNumber = "";
firstNumberText.innerText = "";
secondNumberText.innerText = "";
operatorText.innerText = "";
operationText.innerText = "";
resultText.innerText = "";
});
<!-- First Number -->
<label id="txt1">-</label><br>
<!-- Operator -->
<label id="txt3">-</label><br>
<!-- Second Number -->
<label id="txt2">-</label><br>
<!-- Operation -->
<label id="txt4">-</label><br>
<!-- Result -->
<label id="txt5">-</label><br>
<button type="button" value="0" onclick='numberPressed(this);updateText()'>0</button>
<button type="button" value="1" onclick='numberPressed(this);updateText()'>1</button>
<button type="button" value="2" onclick='numberPressed(this);updateText()'>2</button>
<button type="button" value="3" onclick='numberPressed(this);updateText()'>3</button>
<button type="button" value="4" onclick='numberPressed(this);updateText()'>4</button>
<button type="button" value="5" onclick='numberPressed(this);updateText()'>5</button>
<button type="button" value="6" onclick='numberPressed(this);updateText()'>6</button>
<button type="button" value="7" onclick='numberPressed(this);updateText()'>7</button>
<button type="button" value="8" onclick='numberPressed(this);updateText()'>8</button>
<button type="button" value="9" onclick='numberPressed(this);updateText()'>9</button>
<br><br>
<button type="button" id="add">+</button>
<button type="button" id="sub">-</button>
<button type="button" id="mul">*</button>
<button type="button" id="div">/</button><br><br>
<button type="button" id="enter">CALCULATE</button>
<button type="button" id="clear">CLEAR</button>

HTML Checkbox "onclick" Create Button issue

So i have following objectives from the checkbox click event
1] Create A Button having id = 'id-of-checkbox'+'some-character-here' in specified div
2] Clicking On That Particular Button Will Remove The Button As Well As Checkbox tick related to it
3] If User wants to remove button in specified div through unchecking the checkbox it should be done
4] And If User again checks the checkbox button should be created in specified div
Now i have achieved first 3 objectives and im having issue with 4th one , i.e
if i click on checkbox again after unticking it button is not getting created and console doesnt return any error associated with it.. please help
Here Is My HTML Code
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" class="btn" onclick="updateValue(this.id,this.name)">
Price Filter
</div>
<div id="DropArea">
</div>
Here is My Javascript Code
var objTo = document.getElementById('DropArea');
var checked = ""
function updateValue(id,name)
{
if(document.getElementById(id).checked)
{
checked='yes'
}
else if(!document.getElementById(id).checked)
{
checked='no'
}
if(checked=='yes')
{
addButton(id,name);
}
else if(checked=='no')
{
removeButton(id,name);
}
}
function addButton(id,name)
{
var nameOfButton = name+'X';
var idofButton = id+'11';
var btn = document.createElement("BUTTON");
btn.innerHTML=nameOfButton;
btn.setAttribute("class","btnCancel");
btn.setAttribute("id",idofButton);
btn.setAttribute("onclick","someMsg(this.id)")
objTo.appendChild(btn);
}
function removeButton(id,name)
{
var idofButton = id+'11'
if(document.getElementById('DropArea').contains(document.getElementById(idofButton)))
{
document.getElementById('DropArea').remove(document.getElementById(idofButton));
console.log('Button Removed');
}
}
function someMsg(id)
{
var name = id.substring(0,id.length-2);
document.getElementById(id).remove();
document.getElementById(name).checked=false;
console.log('Deleted');
}
Another approach to achieving the same result:
const dropArea = document.querySelector("#dropArea");
const checkbox = document.querySelector("#priceFilter");
checkbox.addEventListener("change", function(e) {
if (this.checked) {
const btn = createSpecificButton();
dropArea.appendChild(btn);
} else {
const btn = dropArea.querySelector("button");
dropArea.removeChild(btn);
}
});
const createSpecificButton = () => {
const btn = document.createElement("button");
btn.innerText = "Click Here";
btn.addEventListener("click", function(e) {
checkbox.checked = false;
this.remove();
});
return btn;
};
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" /> Price Filter
</div>
<div id="dropArea"></div>
Element.remove() don't have any parameters, so when you call by your way, it will remove DropArea element (includes children, like idofButton).
Solution: Change the below line
document.getElementById('DropArea').remove(document.getElementById(idofButton));
To
document.getElementById(idofButton).remove();
var objTo = document.getElementById('DropArea');
var checked = ""
function updateValue(id, name) {
if (document.getElementById(id).checked) {
checked = 'yes'
} else if (!document.getElementById(id).checked) {
checked = 'no'
}
if (checked == 'yes') {
addButton(id, name);
} else if (checked == 'no') {
removeButton(id, name);
}
}
function addButton(id, name) {
var nameOfButton = name + 'X';
var idofButton = id + '11';
var btn = document.createElement("BUTTON");
btn.innerHTML = nameOfButton;
btn.setAttribute("class", "btnCancel");
btn.setAttribute("id", idofButton);
btn.setAttribute("onclick", "someMsg(this.id)")
objTo.appendChild(btn);
}
function removeButton(id, name) {
var idofButton = id + '11'
if (document.getElementById('DropArea').contains(document.getElementById(idofButton))) {
document.getElementById(idofButton).remove();
console.log('Button Removed');
}
}
function someMsg(id) {
var name = id.substring(0, id.length - 2);
document.getElementById(id).remove();
document.getElementById(name).checked = false;
console.log('Deleted');
}
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" class="btn" onclick="updateValue(this.id,this.name)"> Price Filter
</div>
<div id="DropArea">
</div>

Validating Input with Javascript

I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">

jQuery multiple validation

I have here a form validation. I used this validation in multiple editing records in php. I have two textbox that comparing it's value. I tried to mix my validation script and comparing value script but isn't working properly.
This what I have now but I'm having problem with this when I tried to input lower value in n_quanity field the validation error message is not working and it allowed the form to submit. I want to display error in span not alert the message. Help please?
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
for (var i = 0,len=textBox1.length; i < len;i++) {
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
return false;
} else {
$(this).next("span.val_qty").html("");
}
}
});
And this is my full code
<script>
jQuery(function($) {
var validation_holder;
$("form#register_form input[name='submit']").click(function() {
var validation_holder = 0;
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else {
$(this).next("span.val_qty").html("");
}
});
if(validation_holder == 1) { // if have a field is blank, return false
$("p.validate_msg").slideDown("fast");
return false;
} validation_holder = 0; // else return true
/* validation end */
}); // click end
}); // jQuery End
</script>
<script>
$('#sbtBtn').on('click', function () {
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
for (var i = 0,len=textBox1.length; i < len;i++) {
if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
alert('value is greater than quantity');
return false;
} else {}
}
});
</script>
<p> <label for="">PR Quantity</label> <input name="n_quantity[]" id="n_quantity" class="qty n_quantity" type="text"/><span class="val_qty"></span> </p>
<p style="display:none;"><input id="pr_total" class="pr_total" type="text"></p>

I want to Empty the Value of 2 Input-Type-Text, On Checked (Box)

Guys I Need Help I have the Code what can Empty the Value of Single Input by ID i have 2 Input lets say Start time and End time When i Click on All Day it should be Empty Start Time and End Time When i Check this Button...
Here is my Code....
<Input type="text" id="startime" />
<input type="text" id="endtime" />
<input type="check" id="remove" />
<script type="text/javascript">
var imgInput = document.getElementById('startime'),
remove = document.getElementById('remove'),
val = imgInput.value;
remove.onchange = function() {
if (this.checked) {
imgInput.value = "";
} else {
imgInput.value = val;
}
}
</script>
Help Appreciated...
For a checkbox, you should not use the onchange event handler, onclick will do what you need:
remove.onclick = function() {
if (this.checked) {
imgInput.value = "";
} else {
imgInput.value = val;
}
}
However it looks like you might be trying to save the value if it gets cleared so it can be repopulated, if this is the case then you also need to update val before you clear the text box:
remove.onclick = function() {
if (this.checked) {
val = imgInput.value;
imgInput.value = "";
} else {
imgInput.value = val;
}
}

Categories