JavaScript onclick event handlers not functioning properly - javascript

For some reason, my onclick JavaScript event handlers are not functioning properly.
Here is my markup, script and style:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
document.ready = function() {
document.getElementById('calculate').onClick.calculateQuad()
{
var inputa = document.getElementById('variablea').value;
var inputb = document.getElementById('variableb').value;
var inputc = document.getElementById('variablec').value;
root = Math.pow(inputb,2) - 4 * inputa * inputc;
root1 = (-inputb + Math.sqrt(root))/2*inputa
root2 = (-inputb + Math.sqrt(root))/2*inputa
document.getElementById('root1').value = root1;
document.getElementById('root2').value = root2;
if(root<'0')
{
alert('This equation has no real solution.')
}
else {
if(root=='0')
{
document.getElementById('root1').value = root1
document.getElementById('root2').value = 'No Second Answer'
}
else {
document.getElementById('root1').value = root1
document.getElementById('root2').value = root1
}
}
};
document.getElementById('erase').onClick.document.getElementById('form1').reset();
}
</script>
<style>
#container
{
text-align: center;
}
</style>
</head>
<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
a:<input id="variablea" value="" type="text">
<br/>
b:<input id="variableb" value="" type="text">
<br />
c:<input id="variablec" value="" type="text">
<br />
<input id="calculate" value="Calculate!" type="button">
<input id="erase" value="Clear" type="button">
<br />
<br />
Roots:
<br />
<input id="root1" type="text" readonly>
<br />
<input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>
Is there an explainable reason?

This is wrong
document.getElementById('calculate').onClick.calculateQuad()
It must be
document.getElementById('calculate').onClick = function ()
And this is wrong too
document.getElementById('erase').onClick.document.getElementById('form1').reset();
Fixing:
document.getElementById('erase').onClick = function(){document.getElementById('form1').reset();}

There's not really a "ready" event like that. If you want to do things at what's commonly thought of as the "ready" point, you'll need to use a framework. Otherwise, you can use "onload" instead of "ready".
If, for example, you were using jQuery, you'd do this:
$(function() {
var inputa = document.getElementById('variablea').value;
var inputb = document.getElementById('variableb').value;
var inputc = document.getElementById('variablec').value;
// etc ...
});
Without that, you'd do:
window.onload = function() {
// all your stuff
};
Also:
... .onclick.calculateQuad() {
makes no sense at all.

.onClick.document.getElementById('form1').reset()
I think you want to turn this into:
.onclick = function () { document.getElementById('form1').reset(); }

if you can use Jquery
$(document).ready(function()
{
$("#variablea").click(function(element)
{
///....operation
});
});
you can use $(" input").click(function(element){}) operate all of input elements

Related

How to call function when input value changes?

I have tried to find a way to call a function when the value of the input changes, but so far I haven't found anything. All of the things I have tried seemed to work but didn't.
Html:
var funds = 500;
document.getElementById("submit").onclick = function() {
}
function AP() {
if (document.getElementById("p").checked) {
document.getElementById("AP").innerHTML = "%";
} else {
document.getElementById("AP").innerHTML = "";
}
}
//right here I'd like the function to call.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rng Crypto</title>
</head>
<body>
<header>
<h1>Crypto ran from randomness!</h1>
</header>
<div>
<input type="radio" name="AP" id="a" onchange="AP()" checked>Absolute<input type="radio" name="AP" id="p" onchange="AP()">Percent<br>
<input type="number" id="input" HERE TO ADD THINGY>
<p id="AP" style="display:inline;"></p><br>
<button id="submit">Submit</button>
</div>
<script src="RngCrypto.js"></script>
</body>
</html>
The things that I have tried are:
<input type="number" id="input" onchange="input()">
<input type="number" id="input" oninput="input()">
<input type="number" id="input" onkeyup="input()">
document.getElementById("input").onchange=input();
document.getElementById("input").oninput=input();
const inputEle = document.querySelector("#input");
inputEle.addEventListener('input', function(e) {
console.log(e.target.value);
})
<input type="text" id="input">
Have you tried adding the 'change' event on the input element.
Edit: adding 'input' eventListener, is one more way to achieve this result.
(refer following code)
var funds = 500;
document.getElementById("submit").onclick = function() {
}
function AP() {
if (document.getElementById("p").checked) {
document.getElementById("AP").innerHTML = "%";
} else {
document.getElementById("AP").innerHTML = "";
}
}
//right here I'd like the function to call.
document.queryselector("#input").addEventlistener('change', function(e) {
console.log(e.target.value;)
})
When I got you right this is basically what you are looking for:
<input class="js-radio-button" type="radio" name="ab" value="absolute"> Absolute<br>
<input class="js-radio-button" type="radio" name="ab" value="percent"> Percent<br>
<button class="js-check-selection">CHECK</button>
<div>
<span>Result is:</span> <span id="result"></span>
</div>
in your javascript you have:
function checkSelectedRadio() {
// get your radios having the name 'ab'
const radios = document.querySelectorAll('input[type=radio][name=ab]');
// reset result container
document.getElementById('result').innerHTML = '';
// loop through the radios
for (let i = 0; i < radios.length; i += 1) {
// check for each radio if it was selected
if (radios[i].checked) {
// set the value of the selected radio to your result container
document.getElementById('result').innerHTML = `Value: ${radios[i].value}`;
// if you need more logic:
if (radios[i].value === 'absolute') {
// do something here if 'absolute' was checked
} else if (radios[i].value === 'percent') {
// do something here if 'percent' was checked
}
}
}
}
// get your button to check radio status like this or fire the function above by your onchange handler
const checkButton = document.querySelector('.js-check-selection');
checkButton.addEventListener('click', checkSelectedRadio);
EDIT after reading your comment:
To detect change of your input field it works like this:
<input type="number" id="input" value="1">
In your JS:
const field = document.querySelector('#input');
function inputCheck() {
console.log('input changed');
// or do something else
}
field.addEventListener('change', inputCheck);

HTML onsubmit event is not calling the JavaScript function

I have two buttons in my form for calling two JavaScript functions. The first button works good in its onclick event calling the payroll() function successfully but the second button is of type submit and it never calls the send() function on form submission. I don't know why this issue occurs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html >
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{{ g.sijax.get_js()|safe }}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript" >
function payroll() {
var basic=document.forms["salary"]["bsalary"].value;
var empid=document.forms["salary"]["empid"].value;
var ta,hra,da,pf,netsalary,grosssalary;
if (empid == ""||basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if(isNaN(basic))
{alert("Salary must be in Numbers");
return false;
}
hra=basic*40/100;
da=basic*15/100;
pf=basic*12/100;
basic=parseInt(basic);
hra=parseInt(hra);
da=parseInt(da);
grosssalary=basic + hra + da;
ta=basic*6.2/100;
netsalary=grosssalary-ta;
document.getElementById("hra").innerHTML=hra;
document.getElementById("ta").innerHTML=ta;
document.getElementById("da").innerHTML=da;
document.getElementById("netsalary").innerHTML=netsalary;
document.getElementById("pf").innerHTML=pf;
document.getElementById("grosssalary").innerHTML=grosssalary;
window.alert("HI"+grosssalary);
return true;
}
function send()
{
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.forms['salary']['hra'].value;
var da = document.forms['salary']['da'].value;
var ta = document.forms['salary']['ta'].value;
var pf = document.forms['salary']['pf'].value;
var gross_sal = document.forms['salary']['grosssalary'].value;
window.alert("HI"+gross_sal);
var net_sal = document.forms['salary']['netsalary'].value;
Sijax.request('send',[id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%" >
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return send()" >
<label id = "empid">Employee ID</label><br>
<input type = "text" name = "empid" placeholder = "Employee ID" /><br><br>
<label id = "bsalary">Basic Salary</label><br>
<input type = "text" name = "bsalary" placeholder = "Basic salary" /><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for ="hra">House Rent Allowance(HRA)</label>
<p id="hra" name="hra"></p><br>
<label for ="ta">Travel Allowance(TA)</label>
<p id="ta" name="ta"></p><br>
<label for ="da"> Dearness Allowance(DA)</label>
<p id="da" name="da"></p><br>
<label for ="netsalary">Net Salary</label>
<p id="netsalary" name="netsalary"></p><br>
<label for ="pf">Provident Fund(PF)</label>
<p id="pf" name ="pf"></p><br>
<label for ="grosssalary">Gross Salary</label>
<p id="grosssalary" name="grosssalary"></p><br><br>
<input type="submit" value="Upload Salary">
</form>
</div>
</body>
</html>
You can't act with <p> elements like as a form-elements. You may create a respective <input type="hidden"> elements and fill them in payroll(), or get values by .innerHtml on paragraphs.
P.S. You have actually a TypeError exception, calling undeclared form elements like document.forms['salary']['grosssalary'] and so on.
okay, quick fix, since you are using python flask library Sijax for ajax and therefore jQuery, you can alter your javascript send function like this:
function send(e){
e.preventDefault(); //it is as good as returning
//false from the function in all cases
var id = document.forms['salary']['empid'].value;
...
}
and change your onsubmit handler declaration like this:
<form id="salary" name="salary" style="margin-top: 2%" method="post"
onsubmit="return send(event)" >
please note that when you stop the event chain propagation, you will have to do a manual submission of the form.
So, you can modify your send function to do .preventDefault based on your custom criterias, otherwise, let the form submit
Your code actually works, if you're running this code as a snippet here in stack overflow, Form submission is actually blocked by default. Try running your code in codepen. I tried it and it's actually working.
http://codepen.io/jhonix22/pen/VPZagb
Check this out. It is nowhere close to a perfect solution but I think it helps. You can not access the paragraphs as if you would the form input elements. Im not entirely sure what Sijax thing is. I believe it is just a normal AJAX HTTP thing with some sort of CSRF security filters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{
{
g.sijax.get_js() | safe
}
}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript">
function payroll() {
var basic = document.forms["salary"]["bsalary"].value;
var empid = document.forms["salary"]["empid"].value;
var ta, hra, da, pf, netsalary, grosssalary;
if (empid == "" || basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if (isNaN(basic)) {
alert("Salary must be in Numbers");
return false;
}
hra = basic * 40 / 100;
da = basic * 15 / 100;
pf = basic * 12 / 100;
basic = parseInt(basic);
hra = parseInt(hra);
da = parseInt(da);
grosssalary = basic + hra + da;
ta = basic * 6.2 / 100;
netsalary = grosssalary - ta;
document.getElementById("hra").innerHTML = hra;
document.getElementById("ta").innerHTML = ta;
document.getElementById("da").innerHTML = da;
document.getElementById("netsalary").innerHTML = netsalary;
document.getElementById("pf").innerHTML = pf;
document.getElementById("grosssalary").innerHTML = grosssalary;
window.alert("HI" + grosssalary);
return true;
}
function send() {
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.getElementById('hra').innerHTML;
var da = document.getElementById('da').innerHTML;
var ta = document.getElementById('ta').innerHTML;
var pf = document.getElementById('pf').innerHTML;
var gross_sal = document.getElementById('grosssalary').innerHTML;
window.alert("HI" + gross_sal);
var net_sal = document.getElementById('netsalary').innerHTML;
// I think you are missing something here.
Sijax.request('send', [id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%">
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return false">
<label id="empid">Employee ID</label><br>
<input type="text" name="empid" placeholder="Employee ID"/><br><br>
<label id="bsalary">Basic Salary</label><br>
<input type="text" name="bsalary" placeholder="Basic salary"/><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for="hra">House Rent Allowance(HRA)</label><br>
<p id="hra" readonly name="hra"></p>
<label for="ta">Travel Allowance(TA)</label><br>
<p id="ta" readonly name="ta"></p>
<label for="da"> Dearness Allowance(DA)</label><br>
<p id="da" readonly name="da"></p>
<label for="netsalary">Net Salary</label><br>
<p id="netsalary" readonly name="netsalary"></p>
<label for="pf">Provident Fund(PF)</label><br>
<p id="pf" readonly name="pf"></p>
<label for="grosssalary">Gross Salary</label><br>
<p id="grosssalary" readonly name="grosssalary"></p><br>
<input type="button" onclick="send()" value="Upload Salary">
</form>
</div>
</body>
</html>

live update value if checkbox is checked or not

I am trying to update a textbox based on whether or not a checkbox is checked or not. Thanks to this post I got a text box working fine, but I can't get a checkbox to update the value. What am I missing?
<html>
<head>
<title>sum totals</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
if ( rege.test(t.tons.value) ) {
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
else
alert("Error in input");
}
$('input[name="selectedItems1"]').click(function(){
var j = document.getElementById("output");
if (this.checked) {
j.value=j.value+300
}else{
j.value=j.value-300
}
});
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
<br />
<input type="checkbox" name="selectedItems1" value="val1" />I have a car
<br/>
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
Place the <script> tag after <form>
Reason:
When the html page loads, it'll be interpreted line by line. When it come to click(), jQuery will try to find the element input[name="selectedItems1"] which won't be loaded into the DOM at that time. So, jQuery won't attach the click() event handle to that checkbox. That's the reason why your code didn't work.
Try this :
<html>
<head>
<title>sum totals</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
<script type="text/javascript">
function calculate(){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
var tons = $('#tons').val();
if ( rege.test(tons) ) {
val = parseInt(tons);
var treesSaved = val * 17;
if($('input[name="selectedItems1"]').is(":checked"))
{
treesSaved = treesSaved +300;
}
else
{
treesSaved = treesSaved -300;
}
if(isNaN(treesSaved))
j.value=0
else
j.value=treesSaved;
}
else
alert("Error in input");
}
$(function(){
$('input[name="selectedItems1"]').change(function(){
calculate();
});
});
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate()"/>
<br />
<input type="checkbox" name="selectedItems1" value="val1" />I have a car
<br/>
<input type="text" id="output" value="Output" />
</form>
</body>
</html>

Calling string from one function into another doesent seem to work., why?

So I have this code and it does not seem to work. The thing I want it to do is to call the "together" from the function "go" in the function "second". What am i doing wrong?
The program was initially supposed to take what is in the input-text and add it with the ".com" or the ".no"(depending on what u checked) and redirect to that page. But I only want to call the "together" in the "second" function. Is there any better way to do it?
<!doctype html>
<html>
<head>
<title>A Basic Form</title>
<link rel="stylesheet" type="text/css">
<style type="text/css">
</style>
</head>
<body>
<fieldset>
<legend>Redirection: </legend>
<div>
<label>Where do you want to go?</label>
<input type="text" id="input" name="input" size="7">
<input type="button" id="submit" name="submit" value="Submit" onclick="go()">
</div>
<div>
<input type="radio" id="no" name="end" value=".no">
<label for="no">.no</label><br />
<input type="radio" id="com" name="end" value=".com">
<label for="com">.com</label>
</div>
</fieldset>
<script type="text/javascript">
var end = "";
var input = document.getElementById("input").value;
function go(end, input){
if (document.getElementById("no").checked){
end = document.getElementById("no").value;
}else if (document.getElementById("com").checked){
end = document.getElementById("com").value;
}else{
alert("Please Choose a category!");
}
var together = input + end;
// window.location.replace("http://www." + together);
}
second(together);
function second(together){
alert(together);
}
</script>
</body>
</html>
function go(end, input){
if (document.getElementById("no").checked){
end = document.getElementById("no").value;
}else if (document.getElementById("com").checked){
end = document.getElementById("com").value;
}else{
alert("Please Choose a category!");
}
var together = input + end;
// window.location.replace("http://www." + together);
} // remove this
second(together);
} // add this

Change HTML form 'input' type by JavaScript

How can I do this through the tag itself?
Change type from text to password
<input type='text' name='pass' />
Is it possible to insert JavaScript code inside the input tag itself to change type='text' to type='password'?
Try:
<input id="hybrid" type="text" name="password" />
<script type="text/javascript">
document.getElementById('hybrid').type = 'password';
</script>
Changing the type of an <input type=password> throws a security error in some browsers (old IE and Firefox versions).
You’ll need to create a new input element, set its type to the one you want, and clone all other properties from the existing one.
I do this in my jQuery placeholder plugin: https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js#L80-84
To work in Internet Explorer:
dynamically create a new element
copy the properties of the old element into the new element
set the type of the new element to the new type
replace the old element with the new element
The function below accomplishes the above tasks for you:
<script>
function changeInputType(oldObject, oType) {
var newObject = document.createElement('input');
newObject.type = oType;
if(oldObject.size) newObject.size = oldObject.size;
if(oldObject.value) newObject.value = oldObject.value;
if(oldObject.name) newObject.name = oldObject.name;
if(oldObject.id) newObject.id = oldObject.id;
if(oldObject.className) newObject.className = oldObject.className;
oldObject.parentNode.replaceChild(newObject,oldObject);
return newObject;
}
</script>
Yes, you can even change it by triggering an event
<input type='text' name='pass' onclick="(this.type='password')" />
<input type="text" placeholder="date" onfocusin="(this.type='date')" onfocusout="(this.type='text')">
Here is what I have for mine.
Essentially you are utilizing the onfocus and onblur commands in the <input> tag to trigger the appropriate JavaScript code. It could be as simple as:
<span><input name="login_text_password" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="this.select(); this.setAttribute('type','text');" /></span>
An evolved version of this basic functionality checks for and empty string and returns the password input back to the original "Password" in the event of a null textbox:
<script type="text/javascript">
function password_set_attribute() {
if (document.getElementsByName("login_text_password")[0].value.replace(/\s+/g, ' ') == "" ||
document.getElementsByName[0].value == null) {
document.getElementsByName("login_text_password")[0].setAttribute('type','text')
document.getElementsByName("login_text_password")[0].value = 'Password';
}
else {
document.getElementsByName("login_text_password")[0].setAttribute('type','password')
}
}
</script>
Where HTML looks like:
<span><input name="login_text_password" class="roundCorners" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="password_set_attribute();" /></span>
let btn = document.querySelector('#btn');
let input = document.querySelector('#username');
btn.addEventListener('click',()=> {
if ( input.type === "password") {
input.type = "text"
} else {
input.type = "password"
}
})
<input type="password" id="username" >
<button id="btn">change Attr</button>
I had to add a '.value' to the end of Evert's code to get it working.
Also I combined it with a browser check so that the input type="number" field is changed to type="text" in Chrome since 'formnovalidate' doesn't seem to work right now.
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
document.getElementById("input_id").attributes["type"].value = "text";
This is a simple toggle with jQuery. It works also with the the ASP.NET MVC EditorFor() when you have a DataType.Password on the model property.
function showPassword() {
let password = $(".password");
if (password[0].type == "password") {
password[0].type = "";
}
else {
password[0].type = "password";
}
}
$(".show-pass").click(function (e) {
e.preventDefault();
var type = $("#signupform-password").attr('type');
switch (type) {
case 'password':
{
$("#signupform-password").attr('type', 'text');
return;
}
case 'text':
{
$("#signupform-password").attr('type', 'password');
return;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="password" class="show-pass">
This is not supported by some browsers (Internet Explorer if I recall), but it works in the rest:
document.getElementById("password-field").attributes["type"] = "password";
or
document.getElementById("password-field").attributes["type"] = "text";
You can try this:
const myTimeout = setTimeout(show, 5000);
function show() {
document.getElementById('pass').type = "text";
}
clearTimeout(myTimeout);
//html
<input type="password" id="password_input">
<i onclick="passwordDisplay()" class="ti-eye"></i>
//js
const input = document.getElementById("password_input")
function passwordDisplay() {
if (input.attributes["type"].value == "text")
input.attributes["type"].value = "password"
else
input.attributes["type"].value = "text"
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript" language="javascript">
function changefield(){
document.getElementById("passwordbox").innerHTML = "<input id=\"passwordfield\" type=\"password\" name=\"password-field\" title=\"Password\" tabindex=\"2\" />";
document.getElementById("password-field".focus();
}
</script>
</head>
<body>
<div id="passwordbox">
<input id="password-field" type="text" name="password-field" title="Password"onfocus="changefield();" value="Password" tabindex="2" />
</div>
<input type="submit" name="submit" value="sign in" tabindex="3" />
</body>
</html>

Categories

Resources