Running javascript code with html form submit - javascript

Hey, I'm using a html form that is used to log people into my website, I am building it so it uses AJAX (jQuery) but I'm having some problems.
Here is the JavaScript:
function validateLoginDetails() {
$('[name=loginUser]').click(function() {
$("#mainWrap").css({ width:"600px", height:"200px" });
$("#interfaceScreen").load("modules/web/loginForm.php?username=" + encodeURIComponent(username) + "&password=" + encodeURIComponent(password));
});
}
Here is the html form:
<form id="formLogin" name="loginUser" method="post">
Username<br /><input id="username" name="username" type="text" maxlength="30" style="width:160px; border:solid 1px #444444;" /><br /><br />
Password<br /><input id="password" name="password" type="password" maxlength="50" style="width:160px; border:solid 1px #444444;" /><br /><br />
<input id="submit" type="submit" value="Play" style="width:100px; background:#FFFFFF; border:solid 1px #444444;" />
</form>
The problem is, when I submit the form it runs the code but then goes back to how it was before, this may sound weird but I can tell because I can see it changing the div size and then right after reverting back to its original size.
Any ideas?
EDIT: If I run the code with the below link for example then it works fine.
Clicky

You need to return false from your handler so that it doesn't perform the actual form post after doing the AJAX call.
Here's what I would do.
$(function() {
$('#formLogin').submit( function() {
$('#mainWrap').css( { width: '600px', height: '200px' });
$.post( 'modules/web/loginForm.php',
$(this).serialize(),
function(data) {
$('#interfaceScreen').html(data);
}
);
return false;
});
});
Note that I'm using a post to make sure that the URL (including the username and password) doesn't end up exposed in the web logs. I'm also assuming that the page containing the form was loaded via https and, thus, the post will be secured as well.

I'm pretty sure tvanfosson is on the right path. Try moving up the return false into the click function or try canceling the event.
$('[name=loginUser]').click(function() {
//do stuff
return false;
});
or
$('[name=loginUser]').click(function(e) {
e.cancel();
});

If you're dealing with a form submission, you should really opt for the .form() event handler, rather than a .click() event handler. With the former, if the form is submitted via any other methods, your checks will still run, whereas click depends on that one single element firing an action. You'll also need to return false or preventDefault() on this event, so your function actually fires correctly.
The other thing (and this may be minuscule/unimportant based on the code sampling you've provided) is that you're binding that event handler in a function that has to be called - why not load it on document ready, like so (see below)?
I'd rework your code like this, personally:
$(document).ready(function() {
$('#formLogin').submit(function() {
$("#mainWrap").css({ width:"600px", height:"200px" });
$("#interfaceScreen").load("modules/web/loginForm.php?username=" + encodeURIComponent(username) + "&password=" + encodeURIComponent(password));
return false;
});
});

First, did you confirm that your .php file is returning content and not an error? If you are inserting content (with $load), you should not trigger the CSS commands on the div until your expected content (from load) has returned successfully e.g. use callback. Also, I would suggest using .submit(), a form specific function, with a direct reference to the form tag and/or id to speed things up (not making jquery search as many things in the DOM).
< style >
.loadReg{ width:[yourBeginWidth]; height:[yourBeginHeight];}
.loadSuccess{ width:600px; height:200px;}
< / style >
function validateLoginDetails() {
$('#formLogin').submit(function() {
// using load(url,{data:toPOST},callback(if successful));
$("#interfaceScreen").load("modules/web/loginForm.php?",
{"username": encodeURIComponent(username), "password": encodeURIComponent(password)},
function(){$("#mainWrap").toggleClass('loadSuccess');}
);// end load
});// end submit
return false;
}
This could be even more efficient and less obtrusive, but wanted to leave it recognizable. The other guys are right...if your Div is returning to its original size...it is because the page is being allowed to reload...in which case your initial DIV width/height are applied by the browser...as your alternate width/height are only applied by jquery onsubmit.
To recap:
assign submit event to form directly
use $load built-in ability to pass the value pairs is object {name:val}
move CSS to unobtrusive state vs buried in code
trigger CSS if successful
stop page from reloading and resetting display

Related

jQuery validation (through '.attr('required', true)') - how to display alert popup if the field is empty?

I simply validate inputs by running the following code
$(".new_address").attr('required', true);
This is the general use case when someone wants to validate an input.
Here's my case - I am adding inputs (with class="new_address") to the form. This works well. But now, I need to ensure that user added at least one input with that specific class (class="new_address"). How to do that?
If I use only this validation $(".new_address").attr('required', true); and trying to send out the form without any inputs with class new_address, the form is not sent out, but at the same time - I don't see any error message (because those inputs were not added to the page, so the tiny popups have no space to be displayed.
How to solve this issue? I was thinking of adding the validation rule above merging with alert popup (if this validation doesn't go through, then would be display the alert popup saying that is missing at least on input). But how to combine them?
Thank you.
please try using $.each as below for checking at least one is required
$(".new_address").each(function (){
//your code to check least one is required using below attribute
$(this).attr('required', 'required');
});
For alert popup please try using alert in above code. Not able to understand from above mentioned description.
You're using the Html 5 validation, and this is implemented differently for each browser. You can't, to my knowledge, change where and how the notification is displayed for validation errors. And it's not a good choice if your requirement is "[...] at least one input". Adding required would make them all required.
What you could do is add your own validation. For example you could attach an event to the click of the submit button that will check if an input exist and/or if it has any value. To check if the element exists you could use $('.new_address').length.
A basic example below:
$('#myAdder').click(function() {
$('#myForm').prepend('<input type="text" class="new_address" value=""/><br/>');
});
$('#mySubmit').click(function() {
$('#myValidationSummary').text('').hide();
var oneFilledIn = false;
$('.new_address').each(function(i, o) {
if (o.value.length > 0) {
oneFilledIn = true; //at least one element is filled in
return false; //exit the each
}
});
if ($('.new_address').length == 0 || !oneFilledIn) {
$('#myValidationSummary').text('New address must be added and filled in').show();
return false; //this makes sure the form doesn't post
}
});
$('#myForm').submit(function() {
alert('form submitted ok'); //dummy code just to show the form submission
});
#myValidationSummary {
color: red;
border: 1px solid #000;
padding: 4px;
display: none;
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myValidationSummary"></div>
<form id="myForm">
<input type="button" id="myAdder" value="Add input" />
<input type="submit" id="mySubmit" value="Submit it" />
</form>

simple jQuery function working in codepen but not on server:

So I have this little function that takes the value or text input and gives it to an iframe's src attribute. It seems to work great on my codepen, but when I export it (with all of the files etc(codepen style) (jquery and everything is loaded properly) and put it on a server, it doesn't work. Does anyone have any ideas why this might be? or how I could be going about this in a better way? --
this is what shows in the url bar on submit with the live version in chrome if that means anything to you.
http://site.com/?url-input=http%3A%2F%2Fmy-site.com
A working codepen
HTML
<form class="visitor-input-form">
<label for="url-input" >
Type in your current URL and see what your website looks like to almost everyone else.
</label>
<input type="text" name="url-input"
class="currentUrl"
placeholder="http://nouveau.io" id="txtSRC" />
<input type="submit" class="submit-button" value="View site" />
</form>
jQuery
$(".submit-button").click( function() {
$(".i-frame").attr("src", $("#txtSRC").val());
});
Thanks for your time.
Update:
So to further test I'm using this. Page loads, tells me the dom is ready. So everything is loading in order. Then I input the url, it tells me the button was pushed, THEN - it tells me the dom is ready AGAIN. So, when I'm pressing enter, it is reloading the page. I do not want the page to reload. I just want the iframe to get switched out. So that is at least a little window to what might be the problem.
jQuery( document ).ready(function($) {
alert("dom is ready");
$(".submit-button").click( function() {
alert("button was pushed");
$(".i-frame").attr("src", $("#txtSRC").val());
});
}); // end dom ready
Make sure you either execute your jQuery at the end of the document, after the elements already exist in the page, or in the head within a document ready call:
$(document).ready(function () {
$(".submit-button").click(function () {
$(".i-frame").attr("src", $("#txtSRC").val());
});
});
Codepen does the former.
We found this:
Prevent reloading page after submiting form. ( no ajax )
<form onsubmit="return false">
Does the trick, but I have the feeling there is a better answer. I feel like on submit, it should run the scrip maybe instead of on click. I'm going to look into that. <form onsubmit="script"> etc... I'll wait a while before I mark this as answered in the hopes I get something more appropriate, but it is currently working as intended.
The page is reloading, try updating your jQuery to this:
jQuery( document ).ready(function($) {
$(".submit-button").click( function(e) {
e.preventDefault();
$(".i-frame").attr("src", $("#txtSRC").val());
});
});

Replacing asp:imagebutton with processing image using jquery

So I have an asp:imagebutton for lets say loginning into a web site.
OnClick the page does xyz and then redirects you, there is a pause time between the redirect from when the button was clicked. To make the wait a bit more user friendly I am replacing the button with a processing image and text the javascript that does this is:
$(document).ready(function () {
$(".ShowProcessing").click(function () {
$(this).replaceWith("<img src='/content/images/processing.gif' /> Processing");
});
});
This is the button:
<asp:ImageButton ID="Login" runat="server" OnClick="Login_Click" CssClass="ShowProcessing" />
The problem is the change to processing image happens but the asp OnClick event however does not fire.
Instead of replacing the entire element with something else entirely, just alter the src of the current element:
$(".ShowProcessing").click(function () {
$(this).attr("src", "/content/images/processing.gif");
});
This is if ImageButton is rendered as an img proper, somewhere, and not just some funky input with scripting (I don't recall off the top of my head, and webforms does some things in strange ways). Then proceed to insert text after the existing element as desired.
Instead of using .replace() tried and succeeded with:
$(".ShowProcessing").click(function () {
$(this).hide();
$(this).after("<img src='/content/images/processing.gif' /> Please wait..." )
});
I guess you may try to remove the first image and then add the new processing image.
instead of replace use (Remove then add) functions.

jQuery Modal Confirmation Dialog Not Submitting Form

I am trying to pop up a confirmation modal when the user presses the delete button on the edit form. The modal pops up fine, but when jQuery should be submitting the form, it's not doing anything. I have delete as a type="button", because when it is of type submit the modal function does not hold up the process and it just deletes the user right away.
The HTML ...
-- EDIT --
(I added the <form> tags)
<form action="/admin/edit-user" enctype="application/x-www-form-urlencoded" method="post" name="edit_user_form" id="edit_user_form">
...
<p><input type="submit" value="Save" name="submit" id="submit"/></p>
<p><input type="submit" value="Cancel" name="cancel" id="cancel"/></p>
<p><input type="button" value="Delete User" name="delete_btn" id="delete_btn" onclick="confirmDeleteUser();"/></p>
...
</form>
...
<div id="dialog-modal" title="Confirm Delete User">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 0 0;"></span> Are you sure you wish to delete this user?</p>
<p>To continue editing, click cancel.</p>
</div>
The Javascript:
function confirmDeleteUser()
{
$('#dialog-modal').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Cancel": function() {
$(this).dialog("close");
return false;
},
"Delete User": function() {
var self = $(this);
var form = $('#edit_user_form');
tmpElm = $('<input type="hidden" />');
tmpElm.attr('name', 'delete');
tmpElm.attr('id', 'delete');
tmpElm.val(true);
tmpElm.appendTo(form);
form.submit();
return true;
}
}
});
$('#dialog-modal').dialog('open');
}
When I inspect the source, I'm seeing that the code is properly appending the new hidden element, but the submit just doesn't seem to want to fire. What step am I missing?
Try it a different way.
HTML
Your html has the following: onclick="confirmDeleteUser();"
Why? jQuery is supposed to make this easier for you, not harder.
Your HTML should be pure and not calling functions (with the exception of ultra-extreme circumstances you are very unlikely to encounter). Why not use the jQuery library to bind the event to the element, rather than mix javascript function calls into your HTML? You should be doing something like this in the <script> tags, after a document ready statement.
$("#delete_btn").click(function(e){
/*Code that runs on click of the "delete_btn" ID tag*/
});
If you're unfamiliar with jQuery selectors and events then start reading here.
You can find all the events here.
You can find all the selectors here
The other reason you should do this is in the event the document isn't correctly/fully loaded in order to prevent it from breaking on your users.
CSS
You've also done this: style="float:left; margin:0 7px 0 0;" in an HTML tag? That's evil, dude. Just evil. How am I going to maintain this code in five months?
Instead, use CSS.
In your tags, or CSS file, you need an entry such as:
.dialogAdjust {
float: left;
margin: 0 7px 0 0;
}
Then in your HTML you would say:
<span class="ui-icon ui-icon-alert dialogAdjust"></span>
And now you can tweak the thing to your heart's content. It's better if you can make the class on the dialog div, rather than individual HTML elements, and in this case you absolutely can.
JavaScript
Hokay, so, here's your function:
function confirmDeleteUser()
{
$('#dialog-modal').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Cancel": function() {
$(this).dialog("close");
return false;
},
"Delete User": function() {
var self = $(this);
var form = $('#edit_user_form');
tmpElm = $('<input type="hidden" />');
tmpElm.prop('name', 'delete');
tmpElm.prop('id', 'delete');
tmpElm.val(true);
tmpElm.appendTo(form);
form.submit();
return true;
}
}
});
$('#dialog-modal').dialog('open');
}
What's going on here? First step, you should try and use a tool to measure code quality. Two popular ones are JSHint and JSLint. You don't need to follow things they say like it's the only way to write your code, but it's immensely helpful in finding bugs due to small mistakes. I like JSHint, so we're going to run it through that.
And here's the output:
Errors:
Line 17 tmpElm = $('<input type="hidden" />');
'tmpElm' is not defined.
Line 18 tmpElm.attr('name', 'delete');
'tmpElm' is not defined.
Line 19 tmpElm.attr('id', 'delete');
'tmpElm' is not defined.
Line 20 tmpElm.val(true);
'tmpElm' is not defined.
Line 21 tmpElm.appendTo(form);
'tmpElm' is not defined.
Oops. Looks like you've got an undefined variable in there, meaning it's now global. Global variables are bad, they break scope and can make your code function in strange ways.
We need to fix that. You should always declare local variables in local scope. That means putting a var tempElm; at the top of the "Delete User" function.
Do away with that function wrapper, you won't need it. Your code should create the dialog object and code when the document is done loading, and open the dialog when it's clicked. What is happening in your original code both creating the dialog and opening it every time you click that button. What's the problem with that? You keep creating the object, even though it's created. You're creating the same object again and again and again. In this implementation, you won't notice it, but your design will carry over to places it will unless you take notice of this now.
So, what does that look like? In your <head> tag you should see something like this:
<script>
/*
This makes all the code inside
run when the window is done loading,
not before, which may cause issues.
*/
$(window).load(function(){
/*
This sets up the dialog
as you've described before
*/
$('#dialog-modal').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Cancel": function() {
$(this).dialog("close");
return false;
},
"Delete User": function() {
var self = $(this);
var form = $('#edit_user_form');
//We've added the var infront of tepElem
var tmpElm = $('<input type="hidden" />');
tmpElm.prop('name', 'delete');
tmpElm.prop('id', 'delete');
tmpElm.val(true);
tmpElm.appendTo(form);
form.submit();
return true;
}
}
});
/*
This is the part where I talked
about selectors and events in the HTML
*/
$("#delete_btn").click(function(e){
$('#dialog-modal').dialog('open');
});
});
</script>
When asking for help, use a tool like jsFiddle to post JavaScript in to make it easier for other people to help you.
Here's a jsFiddle of the revisions we've made so far. Spend a bit of time learning how to use it if you're doing a lot of work in JavaScript and want to test something really quickly.
Here's why I wanted you to learn jsFiddle:
You didn't give us enough code to work with successfully, thus leading to me writing this huge post about code quality and how to ask questions, doubly so when you post a bounty.
If you want help, don't make people work really hard for it. You won't get good help unless someone is totally insane.
jsFiddle requires you post actual working code (or non-working code) that lets us see if there's a problem with form.submit(), such as any strange attributes or properties on the form element, or any number of other issues that could be kicking around that you excluded.
So let's look at what's breaking your "Delete User" function.
function() {
var self = $(this);
var form = $('#edit_user_form');
tmpElm = $('<input type="hidden" />');
tmpElm.prop('name', 'delete');
tmpElm.prop('id', 'delete');
tmpElm.val(true);
tmpElm.appendTo(form);
form.submit();
return true;
}
Why have you declared self? You never use it once. Lets get rid of that.
You could use something called chaining, it's really up to you. Some people hate it.
You append a whole new input to the form for something that looks like a choice, I'm not sure this is wise. I'd suggest changing the value of a normal input, or using another pattern, this could lead to a lot of issues, but for the sake of the question I'll imagine it's done for all the right reasons. Be careful however, if someone double clicks submit, that input's in there two times.
form is a word reserved by used in the DOM, you should avoid using that one to avoid confusion between your variable and the DOM API.
Which form submission button are we clicking here? You have a lot, and jQuery isn't going to guess and hope for the best.
How forms should look:
The w3 explains what forms are and the purpose of things.
Key points:
Names are paired with values
The submit button clicked is sent, the submit buttons not clicked are not.
The DOM is can be navigated based on NAME and ID attributes
Something weird is going on in your form.
Here's a form that javascript understands how to submit:
http://jsfiddle.net/YS8uW/2/
Here's javascript attempting to submit your form (stripped down to bare-bones):
http://jsfiddle.net/LfDXh/
What's different here?
You have IDs all over the place.
You use keywords for names
Lets look at something you've done, given an ID of submit to something:
http://jsfiddle.net/fdLfC/
And what happens when we don't use that as an ID?
http://jsfiddle.net/fdLfC/1/
Ahh. So that's weird.
It's like giving it an id of submit won't let you call submit. A proper explanation is, you've re-written it because the dom did it when you assigned that ID and Name, it's trying to call the element.
You can see this if you open up a debugger or something, it gives you an alert to the effect of:
TypeError: Property 'submit' of object # is not a function
Keep away from using keywords to mean something else and you won't fall into these weird traps.
A big thank you to #MattMcDonald for linking me to this resource, which explains how to deal with, and why, NAME and ID attributes over-write the built-in HTML DOM methods.
Do the other stuff I said too. Disclaimer: Everyone's going to wage war on me saying it's not absolute that you should be doing all those things, I agree, but I think this post is long enough, and we'll all agree that doing these things is a step forward in code quality, not backwards. It's up to you at the end, but try avoiding mixing things together into a huge messy pot. Think about the execution of your code and how it's happening also.
If you are sure it appends the hidden input, then the problem must be in using duplicate ID.
The button and the hidden input have the same ID. Make them different and try again.
Dont ask me the reason why it worked, all i can tell you is after doing this and that and tearing each part of your code, finally i made it work. click below link to see the demo
http://jsfiddle.net/praveen_prasad/KaK5A/4/
The changes i made are: removed id and name attributes from submit buttons from form
Example:
<input type="submit" value="Save" name="submit" id="submit"/>
changed above to below
<input type="submit" value="Save" />
Note For JsFiddle Demo: when you will click delete user on modal, form will submit. jsfiddle will say "Error 404", as it wont find the link you are posting your form. Open firebug and see that its actually posting to correct url.
"Delete User": function() {
var self = $(this);
var form = $('#edit_user_form');
tmpElm = $('<input type="hidden" />');
tmpElm.attr('name', 'delete');
tmpElm.attr('id', 'delete');
tmpElm.val(true); // HERE ----------------
tmpElm.appendTo(form);
form.submit();
return true;
}
At the designated location, shouldn't it be :
tmpElm.value(true);
or
tmpElm.attr('value', 'true');
I find it less confusing to handle my form submits upon confirms via jQuery ajax with serialized form values. It has the added benefit of avoiding unwanted form submits from buttons inside the <form> tags. So, it would look something like this:
<form id="edit_user_form">
...
<button id="submit_btn">Submit</button><br />
<button id="cancel_btn">Cancel</button><br />
<button id="delete_btn">Delete</button>
...
</form>
And then the javascript:
$('#delete_btn').click(function() {
$('#dialog-modal').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Cancel": function() {
$(this).dialog("close");
return false;
},
"Delete User": function() {
$.ajax({
url: "/admin/edit-user",
type: "POST",
data: $('#edit_user_form).serialize(),
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred: " + errorThrown);
},
success: function(){
//Notify of success, redirect, etc.
}
});
}
}
});
});
So, it still submits via a POST. It now can happen asynchronously (or not) You can "do things" on success without changing the page, or alternatively redirect as you might need. I use a "dispatcher" page to submit to my object oriented framework, which then returns the output back to the PHP dispatcher to be json_encoded and echoed as a string for the AJAX call to use on success. Using this pattern, I only have to have one page that spits out plain text and the rest can reside in my OO Classes, which can't be called directly by ajax without doing some serious clooging (by using xajax)

How to remove an HTML element using Javascript?

I am a total newbie. Can somebody tell me how to remove an HTML element using the original Javascript not jQuery.
index.html
<html>
<head>
<script type="text/javascript" src="myscripts.js" > </script>
<style>
#dummy {
min-width: 200px;
min-height: 200px;
max-width: 200px;
max-height: 200px;
background-color: #fff000;
}
</style>
</head>
<body>
<div id="dummy"></div>
<form>
<input type="submit" value="Remove DUMMY" onclick="removeDummy(); "/>
</form>
</body>
myscripts.js
function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
}
What happens when I click the submit button, is that it will disappear for a very very short time and then appear back immediately. I want to completely remove the element when I click the button.
What's happening is that the form is getting submitted, and so the page is being refreshed (with its original content). You're handling the click event on a submit button.
If you want to remove the element and not submit the form, handle the submit event on the form instead, and return false from your handler:
HTML:
<form onsubmit="return removeDummy(); ">
<input type="submit" value="Remove DUMMY"/>
</form>
JavaScript:
function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
return false;
}
But you don't need (or want) a form for that at all, not if its sole purpose is to remove the dummy div. Instead:
HTML:
<input type="button" value="Remove DUMMY" onclick="removeDummy()" />
JavaScript:
function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
return false;
}
However, that style of setting up event handlers is old-fashioned. You seem to have good instincts in that your JavaScript code is in its own file and such. The next step is to take it further and avoid using onXYZ attributes for hooking up event handlers. Instead, in your JavaScript, you can hook them up with the newer (circa year 2000) way instead:
HTML:
<input id='btnRemoveDummy' type="button" value="Remove DUMMY"/>
JavaScript:
function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
return false;
}
function pageInit() {
// Hook up the "remove dummy" button
var btn = document.getElementById('btnRemoveDummy');
if (btn.addEventListener) {
// DOM2 standard
btn.addEventListener('click', removeDummy, false);
}
else if (btn.attachEvent) {
// IE (IE9 finally supports the above, though)
btn.attachEvent('onclick', removeDummy);
}
else {
// Really old or non-standard browser, try DOM0
btn.onclick = removeDummy;
}
}
...then call pageInit(); from a script tag at the very end of your page body (just before the closing </body> tag), or from within the window load event, though that happens very late in the page load cycle and so usually isn't good for hooking up event handlers (it happens after all images have finally loaded, for instance).
Note that I've had to put in some handling to deal with browser differences. You'll probably want a function for hooking up events so you don't have to repeat that logic every time. Or consider using a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over those browser differences for you. It's very important to understand the underlying stuff going on, both in terms of JavaScript fundamentals and DOM fundamentals, but libraries deal with a lot of inconsistencies, and also provide a lot of handy utilities — like a means of hooking up event handlers that deals with browser differences. Most of them also provide a way to set up a function (like pageInit) to run as soon as the DOM is ready to be manipulated, long before window load fires.
Just do this
element.remove();
Try it here LOOK
http://jsfiddle.net/4WGRP/
You should use input type="button" instead of input type="submit".
<form>
<input type="button" value="Remove DUMMY" onclick="removeDummy(); "/>
</form>
Checkout Mozilla Developer Center for basic html and javascript resources
Your JavaScript is correct. Your button has type="submit" which is causing the page to refresh.
It reappears because your submit button reloads the page. The simplest way to prevent this behavior is to add a return false to the onclick like so:
<input type="submit" value="Remove DUMMY" onclick="removeDummy(); return false;" />
index.html
<input id="suby" type="submit" value="Remove DUMMY"/>
myscripts.js
document.addEventListener("DOMContentLoaded", {
//Do this AFTER elements are loaded
document.getElementById("suby").addEventListener("click", e => {
document.getElementById("dummy").remove()
})
})
Change the input type to "button". As T.J. and Pav said, the form is getting submitted. Your Javascript looks correct, and I commend you for trying it out the non-JQuery way :)
Try running this code in your script.
document.getElementById("dummy").remove();
And it will hopefully remove the element/button.
That is the right code. What is probably happening is your form is submitting, and you see the new page (where the element will exist again).
This works. Just remove the button from the "dummy" div if you want to keep the button.
function removeDummy() {
var elem = document.getElementById('dummy');
elem.parentNode.removeChild(elem);
return false;
}
#dummy {
min-width: 200px;
min-height: 200px;
max-width: 200px;
max-height: 200px;
background-color: #fff000;
}
<div id="dummy">
<button onclick="removeDummy()">Remove</button>
</div>
I'm still a newbie too, but here is one simple and easy way: You can use outerHTML, which is the whole tag, not just a portion:
EX: <tag id='me'>blahblahblah</tag>'s innerHTML would be blahblahblah, and outerHTML would be the whole thing, <tag id='me'>blahblahblah</tag>.
So, for the example, if you want to delete the tag, it's basically deleting its data, so if you change the outerHTML to an empty string, it's like deleting it.
<body>
<p id="myTag">This is going to get removed...</p>
<input type="button" onclick="javascript:
document.getElementById('myTag').outerHTML = '';//this makes the outerHTML (the whole tag, not what is inside it)
" value="Remove Praragraph">
</body>
Instead, if you want to just not display it, you can style it in JS using the visibility, opacity, and display properties.
document.getElementById('foo').style.visibility = hidden;
//or
document.getElementById('foo').style.opacity = 0;
//or
document.getElementById('foo').style.display = none;
Note that opacity makes the element still display, just you can't see it as much. Also, you can select text, copy, paste, and do everything you could normally do, even though it's invisible.Visibility fits your situation more, but it will leave a blank transparent space as big as the element it was applied to.I would recommend you do display, depending on how you make your webpage. Display basically deleting the element from your view, but you can still see it in DevTools.
Hope this helps!

Categories

Resources