Javascript Issue - HTML division Calculator - javascript

I'm in the learning phase the code works fine no issues, however I need to add the below features.
When clicking the mouse on the calculate button it does the calculation and spits the results out correct, however my question is I'd want to use the physical keyboard "enter key" to execute/press the calculate button.
Also I need the form to reset after 5 seconds automatically, how can I do that ?
.
<script Language="Javascript">function Calc(myform){var enternumber1=document.myform.number1.value;var enternumber1=parseFloat(enternumber1,10);if(isNaN(enternumber1)||(enternumber1<0)){alert(" Enter a valid number! ");document.myform.number1.value="";document.myform.number1.focus();}else{var enternumber2=document.myform.number2.value;var enternumber2=parseFloat(enternumber2,10);if(isNaN(enternumber2)||(enternumber2<0)){alert(" Enter a valid number! ");document.myform.number2.value="";document.myform.number2.focus();}else
document.myform.number3.value=enternumber1/enternumber2;}}</script>
<form name="myform">
<br />
<b>Enter your first number:</b> <input maxlength="" name="number1" size=" " type="text" /><br />
<br />
<b>Enter your second number:</b> <input maxlength="" name="number2" size="" type="text" /><br />
<br />
<input name="button" onclick="Calc(myform)" type="button" value="Calculate" /> <input name="Reset" type="Reset" /><br />
<br />
<b>The result is :</b> <input maxlength="" name="number3" size="" type="text" value="" /> </form>

Please try to be clear in whatever you are asking. Lets move to your query now:
From your query I can understand that you are facing issues in doing 2 things:
Calling your Calc('myform') function when Enter key is pressed in second input field. - I am not covering validation of form(should have validation function,to be called before calling Calc() function). Just add an id to both the form tag as well as the second input field.Let say you add myForm and num2 ids in form and second input field respectively.
Once added you can use following function:
<script type="text/javascript">
document.getElementById('num2').onkeypress = function (event) {
if (event.keyCode == 13) {
Calc(myform);
}
};
</script>
**Note:**In this function we are checking every key which is getting pressed when our cursor is in num2 field, if the key pressed is having code 13,which is the keycode of enter key, I am just calling the same function Calc() which you are already using.So it will do the same what its doing on click of Calculate button.
For resetting your form in every 5 seconds.Please add this function:
function resetForm() {
document.getElementById("myForm").reset()
}
setInterval(resetForm, 5000);
Note: We are calling setInterval function here to reset your form in every 5seconds.Please dont forget to add myForm id in your form.

Related

Retain value in a disabled input when reset button is pressed

I am using a project code input in my form as
<input type="text" id="txtProjectCode" name="Project Code" class="form-control" maxlength="15" disabled="disabled" />
When I reset my form using my reset function
function resetRequestForm() {
$("#txtProjectCode").val(userProject);
}
I am trying to add value again through global variable, but still it is not reflecting in the form.
Please help on this
Please see this example. It is not exactly what you are doing.
But I am only showing the way how to do it.
Here It is working with disabled also, but please note that disabled fields value will not post on the server end.
var userProject = 'My Project';
function resetRequestForm() {
$("#txtProjectCode").val(userProject);
}
function getValueAgain(){
console.log($("#txtProjectCode").val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txtProjectCode" name="Project Code" class="form-control" maxlength="15" readonly />
<button onClick="resetRequestForm()"; >resetRequestForm</button>
<button onClick="getValueAgain()"; >getValueAgain</button>
Disabled input text
<input type="text" id="txtProjectCode" name="Project Code" class="form-control" maxlength="15" disabled="disabled" />
Clear Button
<button class="clear_button" onclick ="return resetForm();" id="clearRequest">Clear</button>
This will retain the data in the disabled input, when
the form is cleared using a button with custom resetForm() function
the button type is set as `reset'
Note:
Data will not be retained if readonly="readonly" is used instead of disabled="disabled" (in both the cases)
no need to feed the data again as $("#txtProjectCode").val(userProject); - userProject is a global variable.

how to give an alert if specific number is not written in input field on clicking submit button

I have an input field and I want the user to put in a number that is predetermined, like 500, if the user clicks the submit button and value they typed in is NOT 500, there should be a javascript alert. If the user does type in 500 and then clicks the submit button then alert should not happen.
<input name="number" type="text" size="36" maxlength="60" />
<input name="Submit" type="submit" value="submit" />
I would recommend to use ids instead of a form with submit because you will have to reload the page everytime and read the GET parameters out of the URL.
Use onclick instead, like this example:
<html>
<head>
<script>
function myFunction() {
if (document.getElementById("number").value != "500")
alert("Your alertmessage");
}
</script>
</head><body>
<input id="number" type="text" size="36" maxlength="60" />
<input type="button" value="Submit" onclick="myFunction()" />
</body>
</html>
I would recommend using onclick handler rather than a submit handler for your submit button and assign an id to your input. The onclick function will evaluate your input's value. You can parse the input value to make it an integer and check it against 500.
Or, you can ignore the parseInt part and compare the value to "500". Whichever you prefer.
If the value passes the conditional, then pass that value to your submit functionality.
const checkNum = () => {
if (parseInt(document.getElementById('thisNum').value) !== 500) {
alert("NOT NUMBER")
} else {
submitFunction(document.getElementById('thisNum').value)
}
}
const submitFunction = (x) => {
console.log(x)
//your submit functionaliy
}
<input id="thisNum" name="number" type="text" size="36" maxlength="60" />
<input name="Submit" type="submit" value="Submit" onclick="checkNum()" />

JS - Focus/Select Cursor Again after Toggling Div

I have a landing page with two forms, only one form visible at a tme. The first form is an age-verification form and if the conditions are met I use jQuery .toggle() to switch to the next form. On page load, for good UX I am using .focus() to put the cursor in the first form field with this line of code: $("input[name='month']").focus();
// Focus cursor on first input field
$("input[name='month']").focus();
var age = 19;
// After calculating age based on user input, toggle the elements
if (age >= 18) {
$('#age-verification').toggle();
$('#subscribe').toggle();
} else {
$('#age-verification').html('<h2>Sorry, you must be at least 18 years old.</h2>');
}
<div id="age-verification">
<h2>Must be 18, please verify age</h2>
<input type="number" name="month" />
<input type="number" name="day" />
<input type="number" name="year" />
<button id="age-gate-submit">Submit</button>
</div>
<form id="subscribe" action="#" method="post">
<input type="text" name="email" />
<input type="text" name="zip" />
<button id ="subscribe" type="submit">Submit</button>
</form>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
How can I use either .select(), focus() or other method to place the cursor in the first field of the second form <input type="text" name="email" /> after the .toggle() event? I've tried placing a .focus() event direct after the .toggle() which seemed logical but not successful.
You need to first hide the subscribe form:
$('#subscribe').hide();
Working demo: http://jsbin.com/kihepujewi/edit?html,js,output

onblur to onsubmit not working as expected

I have this code which works as expected (executes when the user clicks out of the entry field)
<input id="sampleID" name="sampleID" type="text" onblur="myfunction(sampleID.value); "/>
However I'm having trouble figuring out how to have this work when the user hits the 'enter' button. Ive tried:
<input id="sampleID" name="sampleID" type="text" onkeyup="if (event.keyCode==13) myfunction(sampleID.value); "/>
but this clears the form input field
key13 is the return/enter key. You probably wanted onblurs sister event change. In order to stop the page from clearing the page, use preventDefault(). That will stop the ENTER/RETURN key from triggering a submit event on the <form>. The following Snippet demonstrates both.
SNIPPET
function test(val) {
console.log('You have entered: ' + val);
}
<form id="f1">
<label for="testKeyup">Type in box and press the <kbd>ENTER/RETURN</kbd> key</label>
<input id="testKeyup" name="testKeyup" type="text" onkeyup="if (event.keyCode==13) test(this.value); event.preventDefault()" />
<br/>
<br/>
<label for="testChange">Type in box and then click anywhere <b>but</b> this box</label>
<input id="testChange" name="testChange" type="text" onchange="test(this.value);event.preventDefault();" />
</form>

Javascript validation function not being executed

I'm having to dip my toe back in the EE and javascript world after many years. What am I doing wrong here... a simple form being submitted, with a JS block to validate during the onsubmit event of the submit button. The alert("Here") message box does not appear when I submit the form, and the form gets submitted successfully, i.e. HelloForm gets displayed, with blank values, so I'm led to believe that validate() is not being called. I've tried this in both the Eclipse internal web browser as well as Chrome and see the same thing both times. I'm assuming that I don't need to explicitly activate javascript in either browser, as it would be on by default.
<html>
<head>
<script>
function validate()
{
alert("Here");
var x = document.forms["inputForm"].["first_name"].value;
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="inputForm" action="HelloForm" method="GET" onsubmit="return validate()">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit The Form" />
</form>
</body>
</html>
In this line will throw a syntax error:
document.forms["inputForm"].["first_name"].value
^^^
The statement is wrong, should be without dot between braces:
document.forms["inputForm"]["first_name"].value
//or
document.forms.inputForm.first_name.value
Working with Objects
You can use Html5 Validations.
<form name="inputForm" action="HelloForm" method="GET" >
First Name: <input type="text" name="first_name" required />
<br />
Last Name: <input type="text" name="last_name" required />
<input type="submit" value="Submit The Form" />
</form>
Working Demo

Categories

Resources