How to separate HTML from Javascript in this form? - javascript

NO, this topic doesn't answer my question at all. Please read the question before doing anything.
I have a form with Javascript, which works as expected:
<script>
function checkForm(form)
{
if(form.cb1.checked) {
window.open('http://google.com/','_blank');
}
if(form.cb2.checked) {
window.open('http://yahoo.com/','_blank');
}
return true;
}
</script>
<form onsubmit="return checkForm(this);">
<label for="cb1">G</label>
<input name="cb1" type="checkbox">
<label for="cb2">Y</label>
<input name="cb2" type="checkbox">
<input type="submit" value="Submit">
</form>
But if i try to separate HTML from JS it stops working.
After clicking on Submit an url changes to checkbox.html?cb1=on, if the first checkbox is checked, or to checkbox.html?cb2=on, if the second checkbox is checked, or to checkbox.html?cb1=on&cb2=on, if checked both. But tabs with urls don't open.
My separation try looks like:
document.getElementById('cbx').addEventListener(
'submit', function checkForm(event) {
if (form.cb1.checked) {
window.open('http://google.com/', '_blank');
}
if (form.cb2.checked) {
window.open('http://yahoo.com/', '_blank');
}
return true;
});
<form id="cbx">
<label for="cb1">G</label>
<input name="cb1" type="checkbox">
<label for="cb2">Y</label>
<input name="cb2" type="checkbox">
<input type="submit" value="Submit">
</form>
<script type="text/javascript" src="form.js"></script>

Use event.preventDefault() to solve the problem. It is essentially the same as doing return true inside an HTML element attribute like onsubmit, it prevents the default behavior that would normally occur. If you want your custom behavior, which is opening some URLs in a new tab, to occur, you must override the default behavior first.
Also, make sure your form variable is defined somewhere, not sure if it is in your code because it isn't in your second example.
document.getElementById('cbx').addEventListener(
'submit', function checkForm(event) {
//Prevents default action that would normally happen onsubmit
event.preventDefault();
//Define the form element
var form = document.getElementById("cbx");
if (form.cb1.checked) {
window.open('http://google.com/', '_blank');
}
if (form.cb2.checked) {
window.open('http://yahoo.com/', '_blank');
}
return true;
});
<form id="cbx">
<label for="cb1">G</label>
<input name="cb1" type="checkbox">
<label for="cb2">Y</label>
<input name="cb2" type="checkbox">
<input type="submit" value="Submit">
</form>
The code is tested and works. (It doesn't work in the snippet due to how snippets react to opening URLs in new tabs, but here's a working JSFiddle.)

Related

Javascript - Adding value to array with onclick and function doesn't work [duplicate]

I have a form that has a submit button in it somewhere.
However, I would like to somehow 'catch' the submit event and prevent it from occurring.
Is there some way I can do this?
I can't modify the submit button, because it's part of a custom control.
Unlike the other answers, return false is only part of the answer. Consider the scenario in which a JS error occurs prior to the return statement...
html
<form onsubmit="return mySubmitFunction(event)">
...
</form>
script
function mySubmitFunction()
{
someBug()
return false;
}
returning false here won't be executed and the form will be submitted either way. You should also call preventDefault to prevent the default form action for Ajax form submissions.
function mySubmitFunction(e) {
e.preventDefault();
someBug();
return false;
}
In this case, even with the bug the form won't submit!
Alternatively, a try...catch block could be used.
function mySubmit(e) {
e.preventDefault();
try {
someBug();
} catch (e) {
throw new Error(e.message);
}
return false;
}
You can use inline event onsubmit like this
<form onsubmit="alert('stop submit'); return false;" >
Or
<script>
function toSubmit(){
alert('I will not submit');
return false;
}
</script>
<form onsubmit="return toSubmit();" >
Demo
Now, this may be not a good idea when making big projects. You may need to use Event Listeners.
Please read more about Inline Events vs Event Listeners (addEventListener and IE's attachEvent) here. For I can not explain it more than Chris Baker did.
Both are correct, but none of them are "best" per se, and there may be
a reason the developer chose to use both approaches.
Attach an event listener to the form using .addEventListener() and then call the .preventDefault() method on event:
const element = document.querySelector('form');
element.addEventListener('submit', event => {
event.preventDefault();
// actual logic, e.g. validate the form
console.log('Form submission cancelled.');
});
<form>
<button type="submit">Submit</button>
</form>
I think it's a better solution than defining a submit event handler inline with the onsubmit attribute because it separates webpage logic and structure. It's much easier to maintain a project where logic is separated from HTML. See: Unobtrusive JavaScript.
Using the .onsubmit property of the form DOM object is not a good idea because it prevents you from attaching multiple submit callbacks to one element. See addEventListener vs onclick
.
The following works as of now (tested in chrome and firefox):
<form onsubmit="event.preventDefault(); return validateMyForm();">
where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()
Try this one...
HTML Code
<form class="submit">
<input type="text" name="text1"/>
<input type="text" name="text2"/>
<input type="submit" name="Submit" value="submit"/>
</form>
jQuery Code
$(function(){
$('.submit').on('submit', function(event){
event.preventDefault();
alert("Form Submission stopped.");
});
});
or
$(function(){
$('.submit').on('submit', function(event){
event.preventDefault();
event.stopPropagation();
alert("Form Submission prevented / stopped.");
});
});
For prevent form from submittion you only need to do this.
<form onsubmit="event.preventDefault()">
.....
</form>
By using above code this will prevent your form submittion.
var form = document.getElementById("idOfForm");
form.onsubmit = function() {
return false;
}
To follow unobtrusive JavaScript programming conventions, and depending on how quickly the DOM will load, it may be a good idea to use the following:
<form onsubmit="return false;"></form>
Then wire up events using the onload or DOM ready if you're using a library.
$(function() {
var $form = $('#my-form');
$form.removeAttr('onsubmit');
$form.submit(function(ev) {
// quick validation example...
$form.children('input[type="text"]').each(function(){
if($(this).val().length == 0) {
alert('You are missing a field');
ev.preventDefault();
}
});
});
});
label {
display: block;
}
#my-form > input[type="text"] {
background: cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my-form" action="http://google.com" method="GET" onsubmit="return false;">
<label>Your first name</label>
<input type="text" name="first-name"/>
<label>Your last name</label>
<input type="text" name="last-name" /> <br />
<input type="submit" />
</form>
Also, I would always use the action attribute as some people may have some plugin like NoScript running which would then break the validation. If you're using the action attribute, at the very least your user will get redirected by the server based on the backend validation. If you're using something like window.location, on the other hand, things will be bad.
You can add eventListner to the form, that preventDefault() and convert form data to JSON as below:
const formToJSON = elements => [].reduce.call(elements, (data, element) => {
data[element.name] = element.value;
return data;
}, {});
const handleFormSubmit = event => {
event.preventDefault();
const data = formToJSON(form.elements);
console.log(data);
// const odata = JSON.stringify(data, null, " ");
const jdata = JSON.stringify(data);
console.log(jdata);
(async () => {
const rawResponse = await fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: jdata
});
const content = await rawResponse.json();
console.log(content);
})();
};
const form = document.forms['myForm'];
form.addEventListener('submit', handleFormSubmit);
<form id="myForm" action="/" method="post" accept-charset="utf-8">
<label>Checkbox:
<input type="checkbox" name="checkbox" value="on">
</label><br /><br />
<label>Number:
<input name="number" type="number" value="123" />
</label><br /><br />
<label>Password:
<input name="password" type="password" />
</label>
<br /><br />
<label for="radio">Type:
<label for="a">A
<input type="radio" name="radio" id="a" value="a" />
</label>
<label for="b">B
<input type="radio" name="radio" id="b" value="b" checked />
</label>
<label for="c">C
<input type="radio" name="radio" id="c" value="c" />
</label>
</label>
<br /><br />
<label>Textarea:
<textarea name="text_area" rows="10" cols="50">Write something here.</textarea>
</label>
<br /><br />
<label>Select:
<select name="select">
<option value="a">Value A</option>
<option value="b" selected>Value B</option>
<option value="c">Value C</option>
</select>
</label>
<br /><br />
<label>Submit:
<input type="submit" value="Login">
</label>
<br /><br />
</form>
<form v-on:submit.prevent="yourMethodHere">
The submit event will no longer reload the page. It runs your method.
From vue documentation: https://vuejs.org/guide/essentials/event-handling.html#event-modifiers
Here my answer :
<form onsubmit="event.preventDefault();searchOrder(event);">
...
</form>
<script>
const searchOrder = e => {
e.preventDefault();
const name = e.target.name.value;
renderSearching();
return false;
}
</script>
I add event.preventDefault(); on onsubmit and it works.

Creating objects and adding to array on button [duplicate]

I have a form that has a submit button in it somewhere.
However, I would like to somehow 'catch' the submit event and prevent it from occurring.
Is there some way I can do this?
I can't modify the submit button, because it's part of a custom control.
Unlike the other answers, return false is only part of the answer. Consider the scenario in which a JS error occurs prior to the return statement...
html
<form onsubmit="return mySubmitFunction(event)">
...
</form>
script
function mySubmitFunction()
{
someBug()
return false;
}
returning false here won't be executed and the form will be submitted either way. You should also call preventDefault to prevent the default form action for Ajax form submissions.
function mySubmitFunction(e) {
e.preventDefault();
someBug();
return false;
}
In this case, even with the bug the form won't submit!
Alternatively, a try...catch block could be used.
function mySubmit(e) {
e.preventDefault();
try {
someBug();
} catch (e) {
throw new Error(e.message);
}
return false;
}
You can use inline event onsubmit like this
<form onsubmit="alert('stop submit'); return false;" >
Or
<script>
function toSubmit(){
alert('I will not submit');
return false;
}
</script>
<form onsubmit="return toSubmit();" >
Demo
Now, this may be not a good idea when making big projects. You may need to use Event Listeners.
Please read more about Inline Events vs Event Listeners (addEventListener and IE's attachEvent) here. For I can not explain it more than Chris Baker did.
Both are correct, but none of them are "best" per se, and there may be
a reason the developer chose to use both approaches.
Attach an event listener to the form using .addEventListener() and then call the .preventDefault() method on event:
const element = document.querySelector('form');
element.addEventListener('submit', event => {
event.preventDefault();
// actual logic, e.g. validate the form
console.log('Form submission cancelled.');
});
<form>
<button type="submit">Submit</button>
</form>
I think it's a better solution than defining a submit event handler inline with the onsubmit attribute because it separates webpage logic and structure. It's much easier to maintain a project where logic is separated from HTML. See: Unobtrusive JavaScript.
Using the .onsubmit property of the form DOM object is not a good idea because it prevents you from attaching multiple submit callbacks to one element. See addEventListener vs onclick
.
The following works as of now (tested in chrome and firefox):
<form onsubmit="event.preventDefault(); return validateMyForm();">
where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()
Try this one...
HTML Code
<form class="submit">
<input type="text" name="text1"/>
<input type="text" name="text2"/>
<input type="submit" name="Submit" value="submit"/>
</form>
jQuery Code
$(function(){
$('.submit').on('submit', function(event){
event.preventDefault();
alert("Form Submission stopped.");
});
});
or
$(function(){
$('.submit').on('submit', function(event){
event.preventDefault();
event.stopPropagation();
alert("Form Submission prevented / stopped.");
});
});
For prevent form from submittion you only need to do this.
<form onsubmit="event.preventDefault()">
.....
</form>
By using above code this will prevent your form submittion.
var form = document.getElementById("idOfForm");
form.onsubmit = function() {
return false;
}
To follow unobtrusive JavaScript programming conventions, and depending on how quickly the DOM will load, it may be a good idea to use the following:
<form onsubmit="return false;"></form>
Then wire up events using the onload or DOM ready if you're using a library.
$(function() {
var $form = $('#my-form');
$form.removeAttr('onsubmit');
$form.submit(function(ev) {
// quick validation example...
$form.children('input[type="text"]').each(function(){
if($(this).val().length == 0) {
alert('You are missing a field');
ev.preventDefault();
}
});
});
});
label {
display: block;
}
#my-form > input[type="text"] {
background: cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my-form" action="http://google.com" method="GET" onsubmit="return false;">
<label>Your first name</label>
<input type="text" name="first-name"/>
<label>Your last name</label>
<input type="text" name="last-name" /> <br />
<input type="submit" />
</form>
Also, I would always use the action attribute as some people may have some plugin like NoScript running which would then break the validation. If you're using the action attribute, at the very least your user will get redirected by the server based on the backend validation. If you're using something like window.location, on the other hand, things will be bad.
You can add eventListner to the form, that preventDefault() and convert form data to JSON as below:
const formToJSON = elements => [].reduce.call(elements, (data, element) => {
data[element.name] = element.value;
return data;
}, {});
const handleFormSubmit = event => {
event.preventDefault();
const data = formToJSON(form.elements);
console.log(data);
// const odata = JSON.stringify(data, null, " ");
const jdata = JSON.stringify(data);
console.log(jdata);
(async () => {
const rawResponse = await fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: jdata
});
const content = await rawResponse.json();
console.log(content);
})();
};
const form = document.forms['myForm'];
form.addEventListener('submit', handleFormSubmit);
<form id="myForm" action="/" method="post" accept-charset="utf-8">
<label>Checkbox:
<input type="checkbox" name="checkbox" value="on">
</label><br /><br />
<label>Number:
<input name="number" type="number" value="123" />
</label><br /><br />
<label>Password:
<input name="password" type="password" />
</label>
<br /><br />
<label for="radio">Type:
<label for="a">A
<input type="radio" name="radio" id="a" value="a" />
</label>
<label for="b">B
<input type="radio" name="radio" id="b" value="b" checked />
</label>
<label for="c">C
<input type="radio" name="radio" id="c" value="c" />
</label>
</label>
<br /><br />
<label>Textarea:
<textarea name="text_area" rows="10" cols="50">Write something here.</textarea>
</label>
<br /><br />
<label>Select:
<select name="select">
<option value="a">Value A</option>
<option value="b" selected>Value B</option>
<option value="c">Value C</option>
</select>
</label>
<br /><br />
<label>Submit:
<input type="submit" value="Login">
</label>
<br /><br />
</form>
<form v-on:submit.prevent="yourMethodHere">
The submit event will no longer reload the page. It runs your method.
From vue documentation: https://vuejs.org/guide/essentials/event-handling.html#event-modifiers
Here my answer :
<form onsubmit="event.preventDefault();searchOrder(event);">
...
</form>
<script>
const searchOrder = e => {
e.preventDefault();
const name = e.target.name.value;
renderSearching();
return false;
}
</script>
I add event.preventDefault(); on onsubmit and it works.

Why the onsubmit doesnt work and if I call the function in the console it runs?

I have this html:
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<script src="js/filename.js"></script>
</head>
<body>
<form id = "dp5" action="" method="POST" onsubmit="Write_Text()">
<h3>5- Do you know any browsers?</h3>
<input id = "No" type="radio" name="dp5N" value="false">
<label for = "No">No </label>
<input id = "yes" type="radio" name="dp5S" value="true">
<label for = "yes">Yes</label>
<label for = "text">6 - Which?</label>
<input id = "text" type="text" name="dp5text" value="">
</form>
<div id="next">
<input id="sub" type="submit" name="submit" value="Next">
</div>
</body>
</html>
And this javascript "filename":
function Write_Text() {
let x = document.forms["dp5"]["No"].value;
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
}
The text box should start disabled and only be able when the user choose "yes" option. The function isn't working at all.
Your submit button is outside the form. Put it inside the form and it will work.
<form id = "dp5" action="" method="POST" onsubmit="Write_Text(); return false">
<h3>5- Do you know any browsers?</h3>
<input id = "No" type="radio" name="dp5N" value="false">
<label for = "No">No </label>
<input id = "yes" type="radio" name="dp5S" value="true">
<label for = "yes">Yes</label>
<label for = "text">6 - Which?</label>
<input id = "text" type="text" name="dp5text" value="">
<div id="next">
<input id="sub" type="submit" name="submit" value="Next">
</div>
</form>
Once you fix the problem Sreekanth MK pointed out, you'll have a new problem:
Nothing is preventing the default action of the form submission, which is to send the form data to the action URL (in your case it will be the page's own URL) and replace the current page with whatever that URL returns.
You need to prevent the default action. The minimal way is:
<form id = "dp5" action="" method="POST" onsubmit="Write_Text(); return false">
or
<form id = "dp5" action="" method="POST" onsubmit="event.preventDefault(); Write_Text();">
...but I recommend using modern event handling instead by removing the onsubmit attribute and changing the JavaScript like this:
function Write_Text(event) {
event.preventDefault();
let x = document.forms["dp5"]["No"].value;
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
}
document.getElementById("dp5").addEventListener("submit", Write_Text);
Note that you need to move your script tag. Putting script in head is an anti-pattern. Scripts go at the end of the page, right before the closing </body> tag.
Side note: You're free to do anything you like in your own code, but FWIW, the overwhelming convention in JavaScript is that function names start with a lower case letter and use camelCase, other than constructors which used initially-capped CamelCase instead. So writeText rather than Write_Text.
First of all, the submit problem can be easily solved by moving the button in the form and preventing the default behavior.
Among the submit problem, I think your code could be significantly improved by also solving the following problem: you can select both of the radio inputs: wrap them into a field-set and use the same name for them; why? it's easier to get the selected answer and can be extended to multiple inputs.
Below you have a working example with what I said.
Cheers!
function Write_Text(event) {
event.preventDefault();
let x = document.querySelector('input[name="ans"]:checked').value
console.log(x);
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
}
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
</head>
<body>
<h3>5- Do you know any browsers?</h3>
<form id="dp5" action="" method="POST" onsubmit="return Write_Text(event)">
<fieldset>
<input id="No" type="radio" name="ans" value="false">
<label for="No">No </label>
<input id="yes" type="radio" name="ans" value="true">
<label for="yes">Yes</label>
</fieldset>
<label for="text">6 - Which?</label>
<input id="text" type="text" name="dp5text" disabled value="">
<div id="next">
<input id="sub" type="submit" name="submit" value="Next">
</div>
</form>
</body>
</html>
you need to use event object here to prevent Default because page get refreshed onSubmit and then submit form in your function Write_Text()
function Write_Text(event) {
//This will prevent Default Behaviour
event.preventDefault();
let x = document.forms["dp5"]["No"].value;
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
// then submit using JS
}

Validate HTML using Javascript

I have the following code; I want to make sure that submit does not actually post to the page specified by action unless one of the two radio inputs has been selected. I have tried multiple variations of this and other code, and cannot seem to figure out whats wrong. Whether the radio buttons are selected or not it still posts to somepage.py.
<html>
<head>
<title>
Test Page
</title>
<script language="JavaScript">
function validate(formEntry) {
if (formEntry.Q1.q11.checked != true && formEntry.Q1.q12.checked != true)
return false;
return true;
}
</script>
</head>
<body>
<form action="somepage.py" method="POST" onsubmit="return validate(this);">
<input type="radio" name="Q1" id="q11" value="1" />
<input type="radio" name="Q1" id="q12" value="2" />
<input type="submit" name="Submit" />
</form>
</body>
</html>
If you make one button checked by defualt, then one will always be checked:
<input type="radio" name="Q1" id="q11" value="1" checked>
<input type="radio" name="Q1" id="q12" value="2" >
Or the function can be simply:
function validate(formEntry) {
return formEntry.Q1[0].checked || formEntry.Q1[1].checked ;
}
if either is checked it will return true, otherwise false.
if (!formEntry.Q1[0].checked && !formEntry.Q1[1].checked)
Trying to access input by form_name.input_name.input_id is really strange.
Use jquery validation. Checkout this link for details
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Demo page here:
http://jquery.bassistance.de/validate/demo/
It seems to work, look at:
http://jsfiddle.net/EEgea/
Maybe you'd better use a framework like JQuery to prevent javascript flaws between different browsers
Or use a validation framework like JQuery validation, I highly recommend that.
try your function like :-
function validate(formEntry) {
var radiobtn=document.getElementsByName('Q1');
if(!(radiobtn[0].checked || radiobtn[1].checked))
return false;
return true;
}

HTML form with dynamic action (using JavaScript?)

I want to create a form like this:
Type in your ID number into the form's input and submit.
The form's action becomes something like /account/{id}/.
I was told JavaScript was the only way to achieve this (see here), but how?
Using jQuery it might look something like this:
$('#inputAccount').change(function () {
$('#myForm').attr('action', 'http://www.example.com/account/' + $('#inputAccount').val());
});
This should change the action of the form any time the text in the input element changes. You could also use .blur() instead of .change() to perform the action whenever focus leaves the input element, so it doesn't keep changing all the time, etc. Then, when the form is submitted, it should submit to whatever was last placed in its action attribute.
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(frm.txt).keyup(function(){
$(frm).get(0).setAttribute('action', '/account/'+$(frm.txt).val());
});
});
</script>
</head>
<body>
<form id="frm" action="foo">
<input type="text" id="txt" />
<input type="submit" id="sub" value="do eet" />
</form>
You can do something like this in JavaScript. Depending on the checked radio button (in this case,but it could be another form element) it will be chosen an action or the other:
<script type="text/javascript">
function OnSubmitForm()
{
if(document.myform.operation[0].checked == true)
{
document.myform.action ="insert.html";
}
else
if(document.myform.operation[1].checked == true)
{
document.myform.action ="update.html";
}
return true;
}
</script>
<form name="myform" onsubmit="return OnSubmitForm();">
name: <input type="text" name="name"><br>
email: <input type="text" name="email"><br>
<input type="radio" name="operation" value="1" checked>insert
<input type="radio" name="operation" value="2">update
<p>
<input type="submit" name="submit" value="save">
</p>
</form>

Categories

Resources