Duplicated form disapearing after a second - javascript

How do I keep my duplicated forms from disapearing whenever I press the "Duplicate Form" button? The duplicated form appears for about one second then instantly disapears, how do I prevent this?
Javascript
function myFunction() {
var elmnt = document.getElementById("formid");
var cln = elmnt.cloneNode(true);
document.body.appendChild(cln);
}
HTML
<form action="dilemman.php" method="post" class="copy" id="formid" enctype="multipart/form-data">
Video: <br>
<textarea type="text" rows="1" cols="40" name="videolank"></textarea>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Lägg till fler svar</button>
</div>
<button onclick="myFunction()">Duplicate form</button>
</form>

form will submit by default ,to disable the default action use preventDefault()
<button onclick="myFunction(e)">Duplicate form</button>
function myFunction(e) {
e.preventDefault();
... rest of code
}

Try moving the cloning button outside of your form, I'm suspecting that it triggers the submit action because the button is part of your form.
Also remember to change the ID of any new forms, as duplicate IDs will break code. I suggest adding a counter and adding this to the ID of the form every time.
<form action="dilemman.php" method="post" class="copy" id="formid" enctype="multipart/form-data">
Video: <br>
<textarea type="text" rows="1" cols="40" name="videolank"></textarea>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Lägg till fler svar</button>
</div>
</form>
<button onclick="myFunction()">Duplicate form</button>
and
var count = 0;
function myFunction() {
var elmnt = document.getElementById("formid");
var cln = elmnt.cloneNode(true);
cln.id = "formid"+(++count); //add 1 to count, then append
document.body.appendChild(cln);
}

Related

How do I get user input from text fields and display it on the webpage?

I'm learning how to code js and one of my goals is to have a pseudo commenting system on my webpage. I'm wondering how to make javascript that can make it so that the user can type a comment and it'll display on the webpage. I've tried using getelementbyclassname but because I'm a beginner I don't really know what I'm doing.
HTML:
<div class="commentform">
<h1>Leave your comment!</h1>
<br>
<br>
<form class="commentform" method="post">
<p>Nickname or Name</p> <input id="name" required="required" type="text">
<br>
<p>Comments: </p><textarea id="comment" name="comments" rows="8" cols="20"></textarea>
<button type="button" name="commentsubmit">Comment!</button>
</form>
</div>
So you want the comment to pop up when the user submits the form. A problem I noticed about your code is that <button type="button" name="commentsubmit">Comment!</button> doesn't actually submit the form - it should have type="submit".
Also, you don't specify where on the webpage you want the comment to be placed, so I'll assume it's some div, I'll use <div id="target"></div> but it could be anything.
First: triggering JS when the form is submitted
You can use the .addEventListener function to call a function when the form is submitted. It seems like you are having some trouble selecting the form though. One way is to use document.querySelector, which is more versatile than getElementsByClassName, since you have more than one element with the same class name. We want to select a form with class commentform, which can be represented as form.commentform (look familiar? this is also a CSS selector!).
document.querySelector("form.commentform").addEventListener("submit", function(event) {
});
This selects the form, and adds a listener that triggers a function when the form is submitted. We can place code inside of this function body.
Second: putting the comment on the page
We'll need to retrieve the comment first. The comment is in a textarea with id="comment" - perfect, we can use document.getElementById("comment") to select it. Then, we can call .value on the textarea to retrieve its contents.
document.getElementById("comment").value
Then, we can set the contents of the <div id="target"></div> to the comment. This can be done the same way as we retrieved the textarea, except we use .innerText instead of .value.
document.getElementById("target").innerText = document.getElementById("comment").value;
This now sets the text of the target div to equal the comment that was entered. If you also want the page to not refresh when the user submits the form, you'll want to put event.preventDefault(); in the function as well, to tell the browser to prevent the default behavior of submitting a form (refreshing the page).
document.querySelector("form.commentform").addEventListener("submit", function(event) {
event.preventDefault();
document.getElementById("target").innerText = document.getElementById("comment").value;
});
<div class="commentform">
<h1>Leave your comment!</h1>
<br>
<br>
<form class="commentform" method="post">
<p>Nickname or Name</p> <input id="name" required="required" type="text">
<br>
<p>Comments: </p><textarea id="comment" name="comments" rows="8" cols="20"></textarea>
<button type="submit" name="commentsubmit">Comment!</button>
</form>
</div>
<div id="target"></div>
If you also want to display the nickname, the steps are similar. I'll leave that as an exercise for you.
All what you need to do is to add a script tag and within it make a function where you can get the value of what your're typing within the text field, add the onclick to the button so that you invoke the function.
<div class="commentform">
<h1>Leave your comment!</h1>
<br>
<br>
<form class="commentform" method="post">
<p>Nickname or Name</p> <input id="name" required="required" type="text">
<br>
<p>Comments: </p><textarea id="comment" name="comments" rows="8" cols="20"></textarea>
<button onclick='getText()' type="button" value="hello" name="commentsubmit">Comment!</button>
</form>
<p id = 'demo'> </p>
</div>
<script>
function getText (){
var x = document.getElementById("comment").value
document.getElementById("demo").innerHTML = "You commment is : " + x;
console.log(x)
}
</script>
You can do something like this....
const handleComment = (e)=>{
e.preventDefault();
const newDiv = document.createElement("div");
newDiv.innerText = e.target.comments.value;
const comments = document.getElementById("comments")
comments.append(newDiv)
}
const form = document.getElementById("commentForm")
form.addEventListener("submit", handleComment, true);
<div id="comments"></div>
<div class="commentform">
<h1>Leave your comment!</h1>
<br>
<br>
<form id="commentForm" class="commentform" >
<p>Nickname or Name</p> <input id="name" required="required" type="text">
<br>
<p>Comments: </p><textarea id="comment" name="comments" rows="8" cols="20"></textarea>
<button type="submit" name="commentsubmit">Comment!</button>
</form>
</div>
What I did was added an event listener to the form that captures the submit event.
I then took the comment text and used innerText to add it to a dynamically created div (using document.createElement).
Finally I appended the div to another div I created and gave an Id of comments.
(inside the HTML)

fill and submit form using javascript from console

Here is my form:
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
<input type="Submit" value="Submit" >
</form>
And need to fill it from console.
just to use it in my app,
Will inject javascript with data to local html file.
I tried to make the form without a submit button like so:
<body>
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
</form>
<script>
htmlString.oninput = function(){
///do some stuff
}
</script>
</body>
Expecting that :
document.getElementById('htmlString').value="moo" ;
It automatically submit the form, because here oninput used.
But it just stayed filled with inputs and not proceed further.
Tried with other solution:
form = document.getElementById("myForm")
form.submit()
But it just refreshed the page and not submitted the form.
The need is just one filed without else, and inject my string to it with javascript to run functions embedded in the html.
Try making the input button hidden.
<body>
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
<input type="Submit" value="Submit" style="display: none" >
</form>
<button onclick="simulateConsole()">Try it</button>
<script>
htmlString.oninput = function(){
if(this.value === "moo") {
myForm.submit();
}
}
// This event will be triggered even if you use console
htmlString.onsubmit = function(){
if(this.value === "moo") {
// do something onSubmit
}
}
function simulateConsole() {
// you can simulate this in console
htmlString.value = "moo";
myForm.submit();
}
</script>
</body>
I hope it helps.
You need to supply an action to the form, otherwise it will just reload the page.
See more here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form

Form with two buttons

I am trying to create multiple forms which have two buttons, each will submit the form to different script, one via ajax and second one will just submit the form.
<?php foreach($objects as $object) : ?>
<div class="card-body">
<form id="edit-form" action="#" method="POST">
<input name="subject" value="<?=$object['subject']?>" type="text" id="title" class="input-xxlarge">
<textarea id="content" name="content" rows="25"><?=$object['content']?></textarea>
<button type="button" id="send-button" class="btn btn-primary">Send</button>
<input type="submit" id="submit-button" value="Submit"/>
</form>
</div>
<?php endforeach; ?>
First I am trying to get the current form, but I have problem with that. console.log shows something only on the first form, if I click on the buttons from other forms then It will do nothing.
$('#send-button').on('click', function(e) {
e.defaultPrevented;
$form = $(this);
$url = $form.attr('action');
$data = $form.serialize(); console.log($form);
console.log($url);
});
Is it because my button has same ID for every form ?
You shouln't use ID's multiple times on the same page. Try to use a class for that case. Also as stated in the comments use e.preventDefault(); to stop the event.
$(this) will result in the #send-button beeing targeted. To access the form you need to find the closest form element like this:
$form = $(this).closest('form');
html:
<form method="POST" action="#">
<input type="text">
<button type="button">send</button>
<input type="submit" value="submit" />
</form>
<form method="POST" action="#">
<input type="text">
<button type="button">send</button>
<input type="submit" value="submit" />
</form>
js:
$("form").each(function() {
var form = this;
$(form).find('button').on('click', function(e) {
e.preventDefault();
console.log(form);
console.log(this);
})
});
this will add events on every form you have on your page, button will submit form via script and submit will just submit it. also here's a fiddle to play with

Testing a simple javascript button

Hello gentlemen and ladies. I'm trying to test the button to see if it binds to event but it's not working. I have been at this for hours and couldn't find the answer.I'm looking for code that separates the HTML and javsScript. I'm new and I really appreciate your time. I can't get the alert to work when I click button.
var formId;
formId = document.GetElementById("button");
function run(){
alert("Stack overflow");
}
formId.addEventListener("submit", run, false);
<div id ="content">
<div id ="title">Special Offers</div>
<div id="colors">Sign-up to receive personalized offers!
</div>
<fieldset>
<legend> Please enter your information</legend>
<form action="#" method="post" />
<input type="text" />
<label for ="button">add</label>
</form>
</fieldset>
<!--**************Button******-->
<button type="submit" id="button">submit</button>
</div>
Try ...
var formId = document.getElementById("button");
function run(){
alert("Stack overflow");
}
formId.addEventListener("click", run, false);
Where I am using .getElementById (spelling) and the click event on the Listener.
Fiddle: http://jsfiddle.net/rfornal/9duqfgL6/
You could use the following code:
<div id ="content">
<div id ="title">Special Offers
</div>
<div id="colors">Sign-up to receive personalize offers!
</div>
<button type="submit" id="button" onclick="run()">submit</button>
</div>
and your JS should be as follows:
function run(){
alert("stack overflow");
}
Your form tag was self closing. It should be getElementById. Try the click event instead of the submit event.
Your button is outside the form. When you have your button inside it, you can add the submit event listener to your form.
var formId = document.getElementById("button");
function run(){
alert("Stack Overflow");
}
formId.addEventListener("click", run, false);
<div id ="content">
<div id ="title">Special Offers</div>
<div id="colors">Sign-up to receive personalized offers!</div>
<fieldset>
<legend> Please enter your information</legend>
<form action="#" method="post">
<input type="text"/>
<label for="button">add</label>
<button type="submit" id="button">submit</button>
</form>
</fieldset>
</div>

Javascript Html button

I currently have a button in HTML with the following code:
<form id="tfnewsearch" method="get" >
<input type="text" id="search_query" name="q" size="21" maxlength="120"><input type="button" id="search_button" name="search" value = "Search"onclick="doSearch(this.form.q)">
</form>
The function 'doSearch()' works only if I click the submit button. What changes do I have to do if it has to work even if I just press the Enter key?
<form id="tfnewsearch" method="get" onsubmit="doSearch()" >
Simply change the onclick to an onsubmit and attach it to your form!
The proper way it to move it to simple JS script
<script type="text/javascript">
var form = document.querySelector('#tfnewsearch'),
query = form.querySelector('[name="q"]');
form.addEventListener('submit', function(){
doSearch(query.value);
});
</script>

Categories