If I run dispatchEvent, on an element that has no handlers attached, nothing happens.
<!DOCTYPE html>
<html>
<head>
<title>Title is required</title>
<script>
function submitHandlers() {
var target = document.getElementById('myForm');
var event = new Event('submit');
var result = target.dispatchEvent(event);
// nothing happens because no handler is attached to target submit event
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" name="test" value="this is a test">
<input type="button" value="JS Submit Handlers" onclick="submitHandlers()" >
</form>
</body>
</html>
How can I determine that no handler is attached an then decide to manually run the document.getElementById('myForm').submit(); ?
I need a Vanilla Js answer...
In pseudo Javascript it would be something like:
<!DOCTYPE html>
<html>
<head>
<title>Title is required</title>
<script>
function submitHandlers() {
var target = document.getElementById('myForm');
if(target.hasEventListener('submit')) {
var event = new Event('submit');
var result = target.dispatchEvent(event);
}
else {
target.submit();
}
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" name="test" value="this is a test">
<input type="button" value="JS Submit Handlers" onclick="submitHandlers()" >
</form>
</body>
</html>
Update
I think that this is a Chrome issue, Firefox behavior is different: when you call dispatchEvent if no custom handler is defined, it fires the native "html" submit event (the same as document.getElementById('myForm').submit())
Related
I am trying to create a calculator that solves the Pythagoras theorem. I have created a function inside a tag in my code which takes two arguments (one for each leg length of the right-angled triangle) The function works if I just do a console.log with two numbers as arguments and the function executes properly if it is inside the script tag. But I just want to know how to take the two arguments in the text boxes and then when I press the button make the result appear on the screen.
<html>
<main>
<head>
<!--Textboxes to input lengths of legs-->
<input type = "text" required placeholder= "1st legnth">
<br> <br>
<input type = "text" required placeholder= "2nd legnth">
<br> <br>
<button type = "submit">Give me the answer.
</head>
</main>
</html>
<script>
function solveforHyp (a, b)
{
var c = a*a + b*b;
return Math.sqrt(c);
}
var final = (solveforHyp(3, 4));
console.log(final);
</script>
add a span after the button to contain the final result:
<span id="final-result"></span>
add an onclick event to your button, it might look like this:
<button type="button" onclick="onButtonSubmit()"></button>
you might also give some relevant ID's to the input like this:
<input type = "text" id="first-length" required placeholder= "1st legnth">
<input type = "text" id="second-length" required placeholder= "2nd legnth">
and finally, write the onButtonSubmit function to access the inputs and call the solveforHyp function :
function onButtonSubmit(){
const firstValue = document.getElementById('first-length').value;
const secondValue = document.getElementById('second-length').value;
document.getElementById('final-result').innerText = solveforHyp(firstValue,secondValue); // finally, put the returned value in the created span.
}
First of all your document structure is entirely wrong, a lot of tags are not closed script is after the HTML tag, and content is written inside head tag and head is inside main, NO doctype declaration is done, and most importantly if you wanna submit something you should have a form at least with preventing its default behavior. Learn HTML before JavaScript Brother, and also its a good practice to use input type Number when you already know the input will be always a Number.
and here is the code what you are trying to make
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<form id="formOne">
<input type="number" required placeholder="1st legnth" id="first">
<br> <br>
<input type="number" required placeholder="2nd legnth" id="second">
<br> <br>
<button type="submit">Give me the answer</button>
</form>
</body>
<script>
let form = document.querySelector("#formOne");
let inputOne = document.querySelector("#first");
let inputTwo = document.querySelector("#second");
form.addEventListener("submit", function(e){
e.preventDefault();
console.log(Math.sqrt(Math.pow(inputOne.value,2) + Math.pow(inputTwo.value,2)));
})
</script>
</html>
Js file function to be called
function tryMe(arg) {
document.write(arg);
}
HTML FILE
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src='object.js'> </script>
<title>abc</title><meta charset="utf-8"/>
</head>
<body>
<script>
tryMe('This is me vishal bhasin signing in');
</script>
</body>
</html>
You can try like this:
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<form id="form">
<input type="text" id="first_length" name="first_length" />
<input type="text" id="second_length" name="second_length" />
<input type="submit" value="Submit" />
</form>
<script>
function logSubmit(event) {
event.preventDefault();
var first_length = document.getElementById("first_length").value;
var second_length = document.getElementById("second_length").value;
var final = solveforHyp(first_length, second_length);
console.log(final);
}
const form = document.getElementById("form");
form.addEventListener("submit", logSubmit);
function solveforHyp(a, b) {
var c = a * a + b * b;
return Math.sqrt(c);
}
</script>
</body>
</html>
I am quite new to HTML and JavaScript. Below is the sample code. The below code block works fine with onsubmit as form tag attribute
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Tags</title>
</head>
<body>
<form id="form1" action="#" onsubmit="functSubmit()">
<label for="input1">This text will be passed in CustomeEvent</label>
<input id="input1" type="text" value="default">
<input type="submit" id="bt1">
</form>
<script>
function functSubmit(event) {
var msg = document.getElementById("input1").value;
alert(msg);
}
</script>
</body>
</html>
But when I write below code with addEventListener() it does not work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Tags</title>
</head>
<body>
<form id="form1" action="#">
<label for="input1">This text will be passed in CustomeEvent</label>
<input id="input1" type="text" value="default">
<input type="submit" id="bt1">
</form>
<script>
document.getElementById("form1").addEventListener('submit', functSubmit(event));
function functSubmit(event) {
var msg = document.getElementById("input1").value;
alert(msg);
}
</script>
</body>
</html>
Why might addEventListener not be working?
That's because you're immediately invoking the event listener's callback. Just pass the function as an argument, without invoking it. Anytime the form is submitted, that function will have the event object passed into it.
document.getElementById("form1").addEventListener('submit', functSubmit);
function functSubmit(event) {
var msg = document.getElementById("input1").value;
alert(msg);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Tags</title>
</head>
<body>
<form id="form1" action="#">
<label for="input1">This text will be passed in CustomeEvent</label>
<input id="input1" type="text" value="default">
<input type="submit" id="bt1">
</form>
</body>
</html>
On a side note: it's generally better practice to separate the concern of your HTML from your JavaScript. While inlining your event handlers in attributes works, it couples two separate concerns. For maintainability's sake, manage your handlers separately. You also get the benefit of leveraging event delegation.
You are invoking functSubmit and passing the result to the addEventListner function.
Instead you want something like this
<form id="form1" action="#" onsubmit="functSubmit()">
or
document.getElementById("form1").addEventListener('submit',functSubmit);
function functSubmit(event) {
var msg = document.getElementById("input1").value;
alert(msg);
}
event is already passed in by the caller of the functSubmit function.
I think you can only pass a string as function name. You can try
document.getElementById("form1").addEventListener('submit', function(event){
functSubmit(event);
});
I need to the add a JavaScript variable to a link in action form. Is that possible?
JavaScript function:
<script>
function parameter()
{
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value;
});
return vars;
}
var vpid = getUrlVars()["pid"];
}
//var link = "second_02.html" + pid.toString();
</script>
And in my form I need to add the variable 'link' to a form action, as follows:
<form action='second_02.html + ?pid=vpid&' id="sky-form" class="sky-form">
You'll need to do that programmatically via JavaScript.
After this line...
var vpid = getUrlVars()["pid"];
Add this one...
document.getElementById('sky-form').action = 'second_02.html?pid=' + vpid;
Given the nature of the content of vpid, then you could implements this in the load event of your window.
ALTERNATE METHOD 1
Here's an alternate method of doing what you appear to require, but it requires you to set the new location with the calculated parameter. You can amend the lines that try to get the text from the textbox, with whatever you need to append to your URL.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function validateForm() {
//alert('Validating form...');
var text = document.getElementById('txtValue').value;
text = escape(text);
location.href = 'test.html?param=' + text;
return false;
}
</script>
</head>
<body>
<form id="frmTest" method="get" action="" onsubmit="return validateForm();">
<input id="txtValue" type="text" value="foobar">
<input id="btnSubmit" type="submit" value="Submit">
</form>
</body>
</html>
ALTERNATE METHOD 2
This method allows you to continue to use your form, even with its GET method, but you set the value of a hidden field, that will then be appended to the URL in the querystring during submission.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function validateForm() {
//alert('Validating form...');
document.getElementById('hidTest').value = 'some calculated value';
return true;
}
</script>
</head>
<body>
<form id="frmTest" method="get" action="" onsubmit="return validateForm();">
<input id="txtValue" type="text" value="foobar">
<input id="btnSubmit" type="submit" value="Submit">
<input name="hidTest" id="hidTest" type="hidden" value="testIt">
</form>
</body>
</html>
The browser URL is not supposed to be altered but it is anyway. That is supposed to be prevented by event.preventDefault() in the event listener for the cityNameSubmit button.
<!DOCTYPE html>
<html>
<head>
<script>
function bindButton() {
document.getElementById('cityNameSubmit').addEventListener('click', function (event) {
event.preventDefault();
})
}
</script>
</head>
<body>
<form>
<fieldset>
<legend>Choose a City</legend>
<input type="text" name="cityName" id="cityName">
<input type="submit" id="cityNameSubmit">
</fieldset>
</form>
</body>
</html>
You created a function but you forget to call this function. try this:
<script>
function bindButton() {
document.getElementById('cityNameSubmit').addEventListener('click', function (event) {
event.preventDefault();
})
}
window.onload = function() {
bindButton();
}
</script>
In fact in your actual code you are just declaring the function bindButton(), you have to call it in order to attach the event, for example in the body onload event, using <body onload="bindButton()"> like this:
<!DOCTYPE html>
<html>
<head>
<script>
function bindButton() {
document.getElementById('cityNameSubmit').addEventListener('click', function(event) {
event.preventDefault();
console.log("form submission prevented !");
})
}
</script>
</head>
<body onload="bindButton()">
<form>
<fieldset>
<legend>Choose a City</legend>
<input type="text" name="cityName" id="cityName">
<input type="submit" id="cityNameSubmit">
</fieldset>
</form>
</body>
</html>
Or even better using an Immediately-invoked function expression (IIFE), like this:
(function() {
document.getElementById('cityNameSubmit').addEventListener('click', function(event) {
event.preventDefault();
console.log("form submission prevented !");
})
})();
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<fieldset>
<legend>Choose a City</legend>
<input type="text" name="cityName" id="cityName">
<input type="submit" id="cityNameSubmit">
</fieldset>
</form>
<script>
(function() {
document.getElementById('cityNameSubmit').addEventListener('click', function(event) {
event.preventDefault();
console.log("form submission prevented !");
})
})();
</script>
</body>
</html>
Note:
Make sure to put the script at the end of the body tag, to ensure that the HTML was parsed.
You need to call the function bindButton() somewhere or simply remove this function definition and leave just
document.getElementById('cityNameSubmit').addEventListener('click',function(event){
event.preventDefault();
})
I have a simple form with two inputs and a submit button. I need to display the message depending on the lang attribute. When I click on submit button it displays the message even though the field is filled with valid data.
<!DOCTYPE html5>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="" method="get">
<input type="text" value="" oninvalid="check(event)" required/>
<input type="text" value="" oninvalid="check(event)" required/>
<input type="submit" value="Save">
</form>
<script type="text/javascript">
function check(e) {
var a=document.documentElement.lang;
var validateMsg=(a=="ar"?"In arabic":"Plz enter on Alphabets");
var input = e.target;
if(input.validity.valid){
return true;
}else{
input.setCustomValidity(validateMsg);
return false;
}
}
</script>
</body>
</html>
check(event) is meaningless. The event parameter is passed internally
checking validity inside the oninvalid handler is useless
If you use only oninvalid, you won't be able to change back the validation message once the user starts filling the field. You should use the change, keyup or keydown event for that, depending on the reactivity you want.
This could work:
<input type="text" value="" onchange="check" required />
// ...
function check(e) {
var input = e.target;
var msg = "";
if(!input.validity.valid) {
var a=document.documentElement.lang;
msg=(a=="ar"?"In arabic":"Plz enter on Alphabets");
}
input.setCustomValidity(msg);
}