Javascript - strange behaviour naming a function 'submit()' - javascript

Is submit a reserved word in Javascript?
Take a look at this code:
<html>
<head>
<script>
function sayHello(){
console.log('Hello!');
}
function submit(){
console.log('Submit!')
}
</script>
</head>
<body>
<form>
<button onclick="sayHello()">Say hello</button>
<button onclick="submit()">Submit</button>
</form>
<button onclick="sayHello()">Say hello - outside</button>
<button onclick="submit()">Submit - outside</button>
</body>
</html>
I'm trying to understand why I can't call the submit() function inside the <form> tag but it works outside the tag. I think it is a reserved word even because changing the function name the script works well but I can't find any information about that on mdn
I'm not a JS guru, so can someone help me understand this strange behaviour?

The problem is that submit() is a built-in function that gets called whenever a <form> gets submitted. To have custom functionality kick in which a form is submitted, you'll not only need to use a different function name, but also prevent the default form submission with event.preventDefault(), passing the event into the function.
This can be seen in the following -- note that the sayHello() will clear the screen (with an attempted form submission), whereas customSubmit() will not:
<html>
<head>
<script>
function sayHello(){
console.log('Hello!');
}
function customSubmit(e){
e.preventDefault();
console.log('Submit!')
}
</script>
</head>
<body>
<form>
<button onclick="sayHello()">Say hello</button>
<button onclick="customSubmit(event)">Submit</button>
</form>
<button onclick="sayHello()">Say hello - outside</button>
<button onclick="customSubmit(event)">Submit - outside</button>
</body>
</html>

Buttons inside forms automatically submit the form, as long as the button doesn't have an event handler, or has an event handler that doesn't preventDefault():
<form>
<button>Say hello</button>
<button>Submit</button>
</form>
(see how the form gets submitted - the page in the snippet disappears)
It has nothing to do with the submit function name.
But still, using inline event handlers is bad practice and results in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener.
Inline handlers should be avoided just as much as eval should be avoided.
If you want to prevent a button inside a form from submitting the form, call e.preventDefault() like this:
function sayHello(){
console.log('Hello!');
}
function submit(){
console.log('Submit!')
}
const [b1, b2] = Array.from(document.querySelectorAll('button'));
b1.addEventListener('click', (e) => {
e.preventDefault();
sayHello();
});
b2.addEventListener('click', (e) => {
e.preventDefault();
submit();
});
<form>
<button>Say hello</button>
<button>Submit</button>
</form>

Pressing a button in a form reloads the page.
<html>
<head>
</head>
<body>
<!--Any button in the form will submit the form and reload the page-->
<form>
<button id="btn1">Say hello</button>
<button id="btn2">Submit</button>
<button>Anything</button>
</form>
<!--these ones don't-->
<button onclick="sayHello()">Say hello - outside</button>
<button onclick="submit()">Submit - outside</button>
<script>
// notice the page loads when we click the 'anything' button, even without an event handler
//the delay allows you to see it happening
console.log("loading page...");
setTimeout(welcome, 500);
function welcome() {
console.log("page has been loaded");
}
// adding preventDefault to these, stops the form from submitting
function sayHello(e) {
console.log('Hello!');
e.preventDefault();
}
function submit(e) {
console.log('Submit!')
e.preventDefault();
}
//This is how you add event handlers
let btn1 = document.getElementById('btn1');
let btn2 = document.getElementById('btn2');
btn1.addEventListener('click', sayHello);
btn2.addEventListener('click', submit);
</script>
</body>
</html>

Related

Onclick function error, function isn't defined

Over the recent days 've been trying to make buttons that changes a text's color by using
document.querySelector.('class name').style.color
in a function while using onclick to put that function in the button, but it always says my function *chanageColor isn't defined. Could some of you help me please? It also says theres an unexpected token, please help me with that as well!
<body>
<div class="box">
<h1> Hello</h1>
</div>
<script>
function changeColor(){
document.querySelector.('.box').style.color = 'pink';
}
</script>
<button class="pink">Pink</button>
</body>
</html>
Well, there's nothing in your code here that would even try to call your function so I can't say for sure what your issue is, but to hook up the click event of the button to your function, you use: .addEventListener().
Now, you do have a typo:
document.querySelector.('.box') // <-- The dot before ( is wrong
And your script element should be the last thing before you close the body tag so that by the time the script runs, all the HTML will have been parsed into memory.
<div class="box">
<h1> Hello</h1>
</div>
<button class="pink">Pink</button>
<script>
document.querySelector("button.pink").addEventListener("click", changeColor);
function changeColor(){
document.querySelector('.box').style.color = 'pink';
}
</script>
And while this works, inline styles should be avoided whenever possible because they are the hardest type of CSS styling to override and lead to duplication of code. Instead, use CSS classes whenever you can (almost always) as shown here:
.pinkText { color:pink; }
<div class="box">
<h1> Hello</h1>
</div>
<button class="pink">Pink</button>
<script>
// Get your DOM element references just once, not every time the function runs:
const box = document.querySelector('.box');
document.querySelector("button.pink").addEventListener("click", changeColor);
function changeColor(){
box.classList.add('pinkText');
}
</script>
<!DOCTYPE html>
<html>
<body>
<div class="box">
<h1> Hello</h1>
</div>
<button class="pink" onclick="changeColor()">Pink</button>
</body>
<script>
function changeColor(){
document.querySelector('.box h1').style.color = 'pink';
}
</script>
</html>

How do I use dynamically created html/javascript with ASP.NET? [duplicate]

Please see the following code:
<body>
<form id="form1" runat="server">
<div>
<button id="helloButton">
Search</button>
<div id="hello">
</div>
<script type="text/javascript">
$(document).ready(
function () {
$('#helloButton').click(function () {
$('#hello').html('<div>hello world</div>');
});
});
</script>
</div>
</form>
When I use this script, all it does is flash "hello world", it doesn't keep it on the page. Does this has something to do with the click event? I'm trying to click the button and then leave the object on the page.
Otherwise you can simply do a return false which will do both
preventDefault and stop propagation
$('#helloButton').click(function (e) {
$('#hello').html('<div>hello world</div>');
return false;
});
in order to prevent the form from posting, so that you can see your changes, you need to call preventDefault()
$('#helloButton').click(function (e) {
e.preventDefault();
$('#hello').html('<div>hello world</div>');
});

Can't change a paragraph text in javascript through DOM

it changes for about a second and returns to the previous text.The "Loading..." line has to change into "hi, Please click the next text box to see more instructions!".
I have tried it latest chrome and Edge browsers.
function greetMe() {
var yourName = document.getElementById("textbox").value;
info1 = "hi, Please click the next text box to see more instructions!"
document.getElementById("textToChange").innerHTML = info1
}
#myForm {
float: left;
width: 30%
}
#myformInfo {
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>HEllO ThERE!</h1>
<div id="myForm"><form >
<input id="textbox" placeholder="Your name">
<button onclick="greetMe()">click!</button>
<br><br>
<input id="">
</div></form>
<div id="myFormSteps">
<p id="textToChange">
<script>var info1 = "Loading..."
document.write(info1)
</script>
</p>
</div>
</body>
</html>
It's probably because you haven't set the type attribute for your button. A button's default type is submit. Try adding the attribute type="button" to your <button>.
When you click the button your form is submitting and the page is reloading - that's why it returning to its initial state. To stop this happening pass in event as a parameter to the function and then use that argument in the function with preventDefault():
HTML
<button onclick="greetMe(event);">click!</button>
JS
function greetMe(e) {
e.preventDefault();
// ...
}
As an aside it's better is to remove your inline JS and use an event listener instead.
var button = document.querySelector('button');
button.addEventListener('click', greetMe, false);

Check what exatly button clicked, when multiple buttons with the same selector on page

I have a two buttons with the same selector class. When I do this:
$('.my_button').click(function() {
console.log(1);
});
, and then click on the button it log 1 two times, like I clicked both buttons instead single. So my question is: There exists some way in JS to get only that button what I clicked, without assign unique selector like id. I am newbien in JS, so can somebody explain me? I found related issue here. Thanks!
Edit:
I make buttons a little bit different. And yes, it returns only single button, but why click trigger works two times. Console log log two times.
Every event listener receives the event, which carries the event target. Try the below example.
$('.my_button').click(function(e) {
console.log(e);
console.log(e.currentTarget);
console.log($(e.currentTarget));
});
use this inside your function code
$('.my_button').on('click',function() {
var tempContainer=$(this).parent();
alert($(tempContainer).html()); // you ll see that you are showing the code where exists your clicked button
});
Assign different id to your buttons
$(".my_button").on("click",function(){
console.log($(this).attr("id"))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="my_button" id="test" value="Test"/>
<input type="button" class="my_button" id="test2" value="Test-2"/>
Try this:
<button class="my_button">Content1</button>
<button class="my_button">Content2</button>
<script>
$( ".my_button" ).click(function( event ) {
console.log(1);
});
</script>
https://jsfiddle.net/nt9ryeyr/5/
Try this:-
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".p").click(function(e){
alert($(e.currentTarget).attr("value"));//button text on which you clicked
});
});
</script>
</head>
<body>
<input type='button' class="p" value='test'/>
</body>
</html>
if your html is like this
<button class="my_button">Test</button>
<button class="my_button">Test1</button>
then use this script
$('.my_button').click(function() {
if(this.innerHTML ==="Test")
console.log(1);
else
console.log(2);
});
or if your html is like this
<input type="button" class="my_button" value="Test"/>
<input type="button" class="my_button" value="Test1"/>
then use this script
$('.my_button').click(function() {
if($(this).val() ==="Test")
console.log(1);
else
console.log(2);
});

localStorage clears screen

I'm testing out localStorage to see if it can be used in my app, but when I try to store data from a text input box to it, the screen goes blank. How can I fix this? Here is the code:
<html>
<head>
<script type="text/javascript">
function write() {
localStorage.setItem('item', document.getElementById('input').value);
}
function read() {
var data = localStorage.getItem('item');
document.getElementById('display').innerHTML = data;
}
</script>
</head>
<body>
<input id="input" type="text" />
<button type="button" onclick="write()">
Write
</button>
<p id="display">
Display
</p>
<button type="button" onclick="read()">
Read
</button>
</body>
</html>
change your function name from write to something else. it sounds like you are accidentally invoking document.write, which would blank out your entire page.
You cannot use a function called write on the global (document) namespace ... call it something else and it works fine
<input id="input" type="text" />
<button type="button" onclick="somethingelse();">
Write
</button>
<p id="display1">
Display
</p>
<button type="button" onclick="read()">
Read
</button>​
function somethingelse() {
localStorage.setItem('item', document.getElementById('input').value);
}
function read() {
var data = localStorage.getItem('item');
document.getElementById('display1').innerHTML = data;
}​
Working example here
The code inside html event handlers is ran effectively like:
with(document) {
with(this) {
write();
}
}
so your write is shadowed (it calls document.write). You can simply refer to the correct write with window.write():
<button type="button" onclick="window.write()">
Ultimately it's better not to use inline html events at all. A simple button.onclick = write would have worked, where button is reference to the element.

Categories