how to reset form in firefox browser by javascript - javascript

I want to reset form in firefox browser. When I use previous function in back button, the page is not reset for hidden field. It has previous stage. So, How do I?
<Html>
<Head>
<Title>My Testing for javascript</Title>
<Script type="text/javascript">
function hidetext(){
window.alert('Start save to hidden');
document.getElementById('hid').value = document.getElementById('puttextbox').value;
window.alert('Complete save to hidden');
document.getElementById('puttextbox').value='';
}
function displaytext(){
window.alert('Start display from hidden');
document.getElementById('displaytextbox').value = document.getElementById('hid').value;
window.alert('Complete display from hidden');
}
function resetform(){
document.getElementById('form1').reset();
window.alert('reset is completing.....');
}
</Script>
</Head>
<Body>
<form id="form1">
<div>
Type your hidden text <input type="text" id="puttextbox"/>
<br/>
Display your hidden text <input type="text" id="displaytextbox"/>
<br/>
<input type="hidden" id="hid"/>
<button type="button" id="putbutton" onclick="hidetext();">Put the textbox</button>
<button type="button" id="displaybutton" onclick="displaytext();">Display hidden text</button>
<button type="button" id="resetbutton" onclick="resetform();">Reset</button>
</div>
</form>
</Body>
</Html>

Why not this:
<input type="reset" value="Reset">
? It's HTML-native. Or try this instead:
window.onload = function() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = '';
}
};
It clears each input element in the page.

function clearForm(oForm) {
var elements = oForm.elements;
oForm.reset();
for(i=0; i<elements.length; i++) {
field_type = elements[i].type.toLowerCase();
switch(field_type) {
case "text":
case "password":
case "textarea":
case "hidden":
elements[i].value = "";
break;
case "radio":
case "checkbox":
if (elements[i].checked) {
elements[i].checked = false;
}
break;
case "select-one":
case "select-multi":
elements[i].selectedIndex = -1;
break;
default:
break;
}
}
}
That should do the job.

The most simple version is:
document.form1.reset();
However, this resets all input fields to their default value, i.e. the one sent along with the HTML. If you want all fields cleared, you'd need to loop through them all.

Related

JavaScript: radio buttons not redirecting on submit

I have four main HTML files:
introPage.html, formOne.html, and radio buttons on submit should go to pageThree.html or pageFour.html. I have two switch statements for pages 3 and 4 that direct to their segmented
pages.
On submit, I would get stuck on page 2, and im not sure what is causing this issue.
Previously I was using innerHTML instead of different HTML files, and it worked. But when I swapped all the lines of innerHTML for window.location.href, this issue started happening.
introPage.html:
<html>
<head></head>
<body>
<button type="button" id="subButton">Next...</button>
</body>
<script type="text/javascript" src="jsFile.js"></script>
</html>
formOne:
<html>
<head></head>
<body>
<input id="rb1" type="radio" name="option1" value="pageOne" /> 1
<input id="rb2" type="radio" name="option1" value="pageTwo" /> 2
<button type="button" id="subButton">Next...</button>
</body>
<script type="text/javascript" src="jsFile.js"></script>
</html>
jsFile.js:
var cPage = 1;
var testType;
var sb = document.getElementById("subButton");
sp.addEventListener("click", function () {
optionRes()
nextPage()
}
function optionRes() {
let option1 = document.getElementsByName("option1");
for (let i = 0; i < option1.length; i++) {
if (option1[i].checked) {
testNumber = option1[i].value;
}
}
}
function nextPage() {
switch (testNumber) {
case pageOne:
pageThreeSwitch()
break;
case pageTwo:
pageFourSwitch()
break;
default:
pageThreeSwitch()
}
}
function pageThreeSwitch() {
switch(cPage) {
case 1:
cPage++;
pageFive();
break;
case 2:
cPage++
pageSevin();
}
}
function pageFourSwitch() {
switch(cPage) {
case 1:
cPage++;
pageSix();
break;
case 2:
cPage++
pageEight();
}
}

How can I merge javascript code with html form that triggers when we perform some action like "submit" and gives output?

I created a function using switch case in javascript.
function convert(x){
switch(x) {case "c": return "d"; case "a": return "o"; case "t": return "g";}
}
var str = "cat";
var result = "";
for(var i = 0; i < str.length; i++)
{
result += convert(str[i]) ;
}
console.log(result);
In this program,I gave default value of str = "cat" which gives output
dog. But instead of passing default value, I want to pass value via html form and print output. So I created a simple html form.
<html>
<head>
<script language="JavaScript">
function showOutput() {
document.getElementById('display').innerHTML = document.getElementById("user_input").value;
}
</script>
</head>
<body>
<form>
<label><b>Please give your input: </b></label>
<input type="text" name="message" id="user_input">
</form>
<input type="submit" onclick="showOutput();"><br/>
<label>Your output is : </label>
<p><span id='display'></span></p>
</body>
</html>
The layout of this HTML form is shown.
Now I want to input value as "cat " and when I click submit, I want output as "dog" using javascript code which I created earlier that has the "convert" function.
You need to put the loop inside the showOutput function so it will convert the user inputs and display the result in display span when the button is clicked.
NOTE 1: I suggest the use of addEventListener() instead of inline-event onClick when you attach events like :
document.querySelector('[type="submit"]').addEventListener('click', showOutput, false);
NOTE 2: You may need to put the submit input inside the form to validate the structure of your HTML code, you could also use .textContent attribute instead of .innerHTML since you're just assigning text and no HTML code.
document.querySelector('[type="submit"]').addEventListener('click', showOutput, false);
function showOutput() {
event.preventDefault();
var str = document.getElementById("user_input").value;
var result = "";
for (var i = 0; i < str.length; i++) {
result += convert(str[i]);
}
document.getElementById('display').textContent = result;
}
function convert(x) {
switch (x) {
case "c":
return "d";
case "a":
return "o";
case "t":
return "g";
}
}
<form>
<label><b>Please give your input: </b></label>
<input type="text" name="message" id="user_input">
<input type="submit">
</form>
<br/>
<label>Your output is : </label>
<p><span id='display'></span></p>
You can place the code inside showOutput(). Then assign the returned result from the function to the element.
I will also suggest you to use textContent() instead of innerHTML() when dealing with text only content as it is faster, safer, and more predictable.
function showOutput() {
var str = document.getElementById("user_input").value;
var result = "";
for(var i = 0; i < str.length; i++){
result += convert(str[i]) ;
}
document.getElementById('display').textContent = result;
}
function convert(x){
switch(x) {
case "c": return "d";
case "a": return "o";
case "t": return "g";
}
}
<form>
<label><b>Please give your input: </b></label>
<input type="text" name="message" id="user_input">
</form>
<input type="submit" onclick="showOutput();"><br/>
<label>Your output is : </label>
<p><span id='display'></span></p>

How can I pass the zip to the button function?

I did wrap this in a form with a submit button, but realized that this attempted to go to a new page without performing the logic. How can I pass the zip code to the onclick button event? If this is completely wrong, can you provide guidance onto how to perform this correctly.
<input type="text" placeholder="Zip Code" pattern="[0-9]{5}" name="zip" required />
<button id="checker">Go!</button>
<script>
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip) {
var zipCodes = [26505, 26501, 26507, 26506];
for (i = 0; i <= zipCodes.length - 1; i++) {
if (zip == zipCodes[i]) {
alert("YES");
break;
}
}
}
</script>
You need to get the value of your input and you can do this with document.querySelector('[name="zip"]').value
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip) {
var zip = document.querySelector('[name="zip"]').value;
var zipCodes = [26505, 26501, 26507, 26506];
for (i = 0; i <= zipCodes.length - 1; i++) {
if (zip == zipCodes[i]) {
alert("YES");
break;
}
}
})
<input type="text" placeholder="Zip Code" pattern="[0-9]{5}" name="zip" required />
<button id="checker">Go!</button>
Just use getElementById('ELEMENT_NAME_HERE').value like so:
Go!
<script>
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip){
console.log('Clicked');
var enteredZip = document.getElementById("zip").value;
console.log(enteredZip);
var zipCodes=[26505, 26501, 26507, 26506];
for(i=0; i<=zipCodes.length-1; i++){
if(zip == zipCodes[i]){
alert("YES");
break;
}}});
</script>
https://plnkr.co/edit/ptyUAItwyaSmZXsD81xK?p=preview
You can't pass it in.
basically if this myfunction() will return a false then the form would not be submitted;
Also this would only be performed at the time of submittion of the form
https://www.w3schools.com/jsref/event_onsubmit.asp
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input id='input-id' type="submit">
</form>
<script>
myfunction(){
if(/*some condition*/)
{
return false;
}
</script>
Also few things to consider since you seem new and people here are giving you very correct but specific solutions.
if you add a button to inside tag, that would submit the form on clicking it.
That is why many use a div which looks like a button by css. Mainly a clean solution to override the Button submit and also you can simply submit the form by Javascript.

Buttons loads index file on click

I have this code:
$(function() {
/*declare a function call hAddCoin with parameter hValue for value and option for option +,x2,clear or max*/
function hAddCoin(hValue, option) {
var bet = document.getElementById('coincredits'); /*get the element*/
var coins = document.getElementById('coins').innerHTML; /*get the inner of id coins*/
var cur = parseInt(bet.value); /*get the coincredit and convert to integer*/
var res = 0; /*declare res variable for result*/
/*we need to check bet is empty or not*/
if (typeof bet.value === "undefined" || bet.value == "") {
cur = 0;
}
/*cek the option, it's will be +, X2 or max and default to 0*/
switch (option) {
case 1:
{
res = cur + hValue;
}
break;
case 2:
{
res = cur * option;
}
break;
case 3:
{
res = parseInt(coins);
}
break;
default:
{
res = 0;
}
break;
}
bet.value = res; /*set value coin creadit to result*/
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="coincredits" id="coincredits" class="form-control" required="" parsley-type="text" placeholder="Minimum 10 coins" data-parsley-id="40" style="text-align:center; color: ;">
<div class="content" style="text-align:center;">
<button id="clear" class="box-btn" onclick="hAddCoin(0,0)">Clear</button>
<button id="add10" class="box-btn" onclick="hAddCoin(10,1,)">+10</button>
<button id="add100" class="box-btn" onclick="hAddCoin(100,1)">+100</button>
<button id="add1000" class="box-btn" onclick="hAddCoin(1000,1)">+1000</button>
<button id="double" class="box-btn" onclick="hAddCoin(0,2)">x2</button>
<button id="max" class="box-btn" onclick="hAddCoin(0,3)">Max</button>
</div>
It adds (or should add) value to the input field, but it just sends me to mywebsite.com/index.php
I have tried defrient scripts but this is happening every time. It gives me no errors and logs nothing in the console.
I know it might be a piece of cake but i just can't figure it out.
<button> elements are implicitly type="submit" which means they submit the form they reside in. If your <form> doesn't have an action attribute it will use the current page as target URL, which reloads the page.
You need to either explicitly set type="button" on each button or add an onsubmit event handler on the form that invokes event.preventDefault()

getting validation to check boxes

Hello all: I recently stumbled upon a question about form validation, which I'm currently trying to get working. I got the code from an answer and then customized it to more what I'm needing.:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function Validate(){
if(!validateForm()){
alert("Something happened");
return false;
}
return true
}
function validateForm()
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked){return true}
}
}
return false;
}
</script>
</head>
<body>
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate()" method="get">
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
NOTE: The image is just from a Google Image Search, and is on Wikipedia (I do not own it).
Now, when I originally entered the HTML from the answer into the Tryit Editor at W3 Schools, it would give me a "Something Happened" alert, or do nothing. (I think that's what is was supposed to do).
Still, (now that I have my own questions) it will say "something happened" if nothing is selected, but no matter how many check (over 1 checked) it will just give me the image. Basically, what I want is it to check if ALL or ONLY SOME are checked. If all are checked i want one image, and if only some, I want a different one.
I hope this isn't too confusing, and I appreciate any help :)
P.S.:Here is the question where I got the code: Original Question
Try this for the script section, it will change the form's "action" attribute (which points the form to a the desired URL upon submitting) after validating how many checkboxes are checked:
<script type="text/javascript">
function Validate(formRef){
var checkboxes = getCheckboxes(formRef);
var checkedCount = validateForm(checkboxes);
if(checkedCount == checkboxes.length){
// All are checked!
return true;
} else if(checkedCount > 0) {
// A few are checked!
formRef.setAttribute('action', 'http://upload.wikimedia.org/wikipedia/commons/thumb/2/24/Yahoo!_logo.svg/200px-Yahoo!_logo.svg.png');
return true;
} else {
alert("Something happened");
}
return true;
}
function getCheckboxes(formRef) {
var c = formRef.getElementsByTagName('input');
var checkboxes = [];
for (var i = 0; i<c.length; i++){
if (c[i].type == 'checkbox')
{
checkboxes.push(c[i]);
}
}
return checkboxes;
}
function validateForm(checkboxes) {
var checkedCount = 0;
for (var i = 0; i < checkboxes.length; i++){
if (checkboxes[i].checked){
checkedCount++;
}
}
return checkedCount;
}
</script>
The form HTML should be updated to pass "this", the reference to the form object being validated, into the Validate() function, to avoid the need to query for it again:
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate(this)" method="get">
Try this (will alert first option if one or more but less than 3 checked, will alert second option if exactly 3 checked):
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input value="Submit" type="submit" onclick="
var count = 0;
for(var i = 0; i < document.getElementsByTagName('input').length - 1; i++)
{
if(document.getElementsByTagName('input')[i].checked)
{
count += 1;
}
}
if(count >= 1 && count < 3)
{
alert('First Option');
}else
{
if(count == 3)
{
alert('Second Option');
}
}" />
</body>
</html>
The following should get you on the right path:
function Validate() {
var checkboxes = processCheckboxes();
if (checkboxes.all.length == checkboxes.checked.length) {
alert("All are checked");
} else if (checkboxes.checked.length > 0) {
alert("Some checked");
} else {
alert("None checked");
}
return false;
}
function processCheckboxes() {
var checkboxes = document.querySelectorAll('input[type=checkbox]');
var checked = [].filter.call( checkboxes, function( el ) {
return el.checked
});
return { all: checkboxes, checked: checked };
}
You can then process the checked boxes in whatever manner you like before submitting.
See a working example here: http://jsfiddle.net/jkeyes/Zcu7d/

Categories