JQuery clone products field - javascript

I have a products page set up where a user can fill out fields to customise products (size, quantity, colour, etc). I also have a button where they can add another product and the same fields as before will appear below. However, I'd like to have a button where they can duplicate what they have just entered into the fields, so instead of adding a new set of fields, it copies what they have just entered.
https://jsfiddle.net/y0y7r3za/12/ this is the very basics of the code (cant post the real code for certain reasons).
$(document).ready(function() {
$('#duplicate').click(function(e) {
e.preventDefault();
$("#product").clone().appendTo("#newArea");
});
});
(example of code to allow the jsfiddle link).
The clone works and duplicates, however once I press the update button to 'save' the changes, and go back into the order to edit it, the cloned form is not longer there.
Any ideas as to why the clone disappears would be a great help!

$(document).ready(function() {
function cloningElement(el){
var source = el.closest(".clone-source").clone();
source.removeClass('clone-source hide').addClass('cloned');
source.appendTo("#newArea");
}
$(document).on('click', 'button[id="duplicate"]', function(e) {
e.preventDefault();
cloningElement($(this));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clone-source" id="product">
<form action="/action_page.php">
<fieldset>
<legend>Product information:</legend>
Name:<br>
<input type="text" name="name">
<br>
Size :<br>
<input type="text" name="size">
<br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<button type="button" id="duplicate">Duplicate</button>
</div>
<div id="newArea">
</div>

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)

generate alert on button click based on input type hidden

I have html that has tile view and each tile has some info with button. I want to check the value of an input hidden field and if the value is not in array defined raise an alert.
html
<div class="box" style="width:30%%">
<div class="boxInner">
<form id="form_myws" method="POST">
<input type="hidden" name="state" value="%s">
<div class="titleBox">
<input type="submit" value="submit" name="ws_butt" id="submit" />
</div>
</form>
</div>
</div>
javascript
<script type="text/javascript">
$('#submit').click(function(){
var state_list=["AVAILABLE","IMPAIRED","INOPERABLE",];
var curr_state=$(this).find("input[type='hidden'][name='state']");
console.log(curr_state.val());
if (jQuery.inArray(curr_state.val(),state_list)<0){
alert("submission is allowed only with AVAILABLE,IMPAIRED,INOPERABLE states.");
}
});
It is not generating any alert. How to achieve that?
var curr_state=$(this).find("input[type='hidden'][name='state']");
change it to
var curr_state=$(this).closest('form').find("input[type='hidden'][name='state']");
also add
return false;
inside if statement so it won't submit form.
If you want to subvert submit you need to do:
$('#submit').click(function(e){
// this:
e.preventDefault();
// more code
// .. or better
return false;
});
You can contain these responses in if --> then constructs but you need to do one or the other to prevent a form from submitting. If you're not using a form, don't use submit!
You can also access the hidden input value like this:
$('#form_myws > input[name="state"]').val();
Working snippet:
var val = $('#form_myws > input[name="state"]').val();
$('body').append(val);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form_myws">
<input type="hidden" name="state" value="%s">
<div class="titleBox">
<input type="submit" value="submit" name="ws_butt" id="submit" />
</div>
</form>
in your case:
var curr_state=$(this).find("input[type='hidden'][name='state']");
$(this) get the button element you selected , you can't find any childen nodes via find() So you should select the hidden input correctly like:
var curr_state=$($(this).parent()[0]).prev()[0];
or like this:
var curr_state=$($(this).parent()[0]).siblings('[name="state"]')[0];

Input Tags and Submit form outside the <form>

I know how to submit a form from outside the form, for example:
<form action="Get?id_sec=120" method="post" id="form15" name="form15" style="display:none"></form>
<input type="submit" class="finish-button primary-button button" border="0" value="Limpar pedido" form="form15" onclick="javascript:document.form15.submit();" />
But I want to put a tag with a reference to the form with javascript too, because command form="example" doesn't work in Internet Explorer.
example:
<input class="input-cep" name="pr001" id="cepfrete" type="text" form="form15"/>
or
<input type="radio" name="tipofrete" value="4" form="form15">`
How can I do that?
Hey Vince, thanks, this works. Very useful help! I need just one other thing. How can I put an input and select in the same form in jQuery?
example:
<input type="text" data-form="dataForm" name="external-input-2">
<Select id="selectField_1" name="selectField_1" data-form="dataForm" >
<option value="52" data-form="dataForm">A</option>
</Select>
To submit a form from outside the form:
HTML
<form id="theForm">...</form>
<button id="submitTheForm">Click to Submit</button>
jQuery
$('#submitTheForm').on('click', function() {
$('#theForm').submit();
});
To include external inputs in the form submission:
HTML
<form id="theForm">...</form>
<button id="submitTheForm">Click to Submit</button>
<input type="text" data-form="theForm" name="external-input-1">
<input type="text" data-form="theForm" name="external-input-2">
jQuery
You can append the external inputs as hidden inputs to the form:
$('#submitTheForm').on('click', function() {
var form = $('#theForm');
$('input[data-form="theForm"]').each(function() {
var input = $(this);
var hidden = $('<input type="hidden"></input>');
hidden.attr('name', input.attr('name'));
hidden.val(input.val());
form.append(hidden);
});
form.submit();
});
I'm not sure that I can completely understand your question but if you are asking how to submit a form externally in different situations, her is my answer.
For the future, just put an id on the form like this.
<form id="form15"></form>
Then to submit this form from anywhere, all you have to do is call the following javascript line in an onclick, a function, etc.
document.getElementById("form15").submit();

html form submiting more fields than expected

I'm dealing with a awful issue, I developed a form with multi fields set (using normal div)
and when I test the submit action I got in the URL the one input not filled, also hidden in
the markup as showed bellow.
http://127.0.0.1:8000/exform.html?user=test&pwd=QWERT1234&user_reg=
And here is the code for the form:
<form id="exform">
<div class="fields" id="login">
<div class="txt">
<label for="user"></label>
<input id="user" type="text" name="user"/>
</div>
<div class="txt">
<label for="pwd"</label>
<input id="pwd" type="password" name="pwd" />
</div>
<input type="submit" value="test" id="test"/>
</div>
<div class="fields" id="register">
<div class="txt">
<label for="user_reg"></label>
<input id="user_reg" name="user_reg" type="text"/>
</div>
<div class="txt">
<label for="pwd2"></label>
<input id="pwd2" type="password" />
</div>
<div class="txt">
<label for="pwdc"></label>
<input id="pwdc" type="password"/>
</div>
<div class="buttons">
<input type="submit" value="OK" id="ok"/>
</div>
</div>
</form>
The strange is that the second field set isn't available in the screen, because in the css
there is a rule to only show the first group with the class "fields"
/*Hide all except first div with class div*/
#exform .fields:not(:first-of-type) {
display: none;
}
So I really want to know why the form is submitting fields out of the scope.
For example, if the second group fieldset is used, when the button submit with value OK is clicked the result produced is similar. In the URL, only the user_reg field parameter is showed filled with the two another fields for the first group without values:
http://127.0.0.1:8000/exform.html?user=&pwd=&user_reg=test
The following code is for submit test:
$(function() {
$('#test').click(function() {
$('#exform').submit(function(event) {
console.log("form Submited:" + document.forms['exform'] + "test");
});
});
$('#ok').click(function() {
$('#exform').submit(function(event) {
console.log("form Submited:" + document.forms['exform'] + "ok");
});
});
});
Doesn't matter I'm got the same URL results
This
http://127.0.0.1:8000/exform.html?user=test&pwd=QWERT1234&user_reg=
or
http://127.0.0.1:8000/exform.html?user=&pwd=&user_reg=test
Instead I'm receiving:
// on #test click
http://127.0.0.1:8000/exform.html?user=test&pwd=QWERT1234
// on #ok click
http://127.0.0.1:8000/exform.html?user_reg=test&pwd2=QWERT1234&pwdc=QWERT123
I can't retrieve the values for pwd2 and pwdc fields in the URL as parameters obtained after submitting.
This got me crazy.
If you do not specify the method method of the form, the default is GET while submitting it. This is the reason to see all form elements in your URL.
Try this:
<form id="exform" method="post">
<!-- form contents -->
See here for details.
When you submit form you submit all it's input fields at ones.
Even if you hide something with css it still exists in html.
When you processed the form you can add a hidden field "input type="hidden"" and give that field a value that tells your script witch fields you want processed in witch case.
And i also fink that post method is better (more secure) especially if you send password.

Jquery multiple forms in same page

I have the following dynamically generated HTML
<div id="1">
<form name = "inpForm">
<input name="FirstName" type="text"/>
<input type="submit" value="Submit"/>
</form>
</div>
<div id="2">
<form name = "inpForm">
<input name="FirstName" type="text"/>
<input type="submit" value="Submit"/>
</form>
</div>
The outer divs have different IDs but the form names are the same. I am using Jquery to perform some validation when the form is submitted. However, when the second form is submitted, I always get the values of the first form.
$(document).ready(function () {
$('form[name="inpForm"]').live('submit', function () {
alert($('input[name="FirstName"]').val());
return false;
});
});
How can I modify myJquery to find the "FirstName" element that matches the current form where the submit was triggered?
Thanks
Add some context:
alert($(this).find('input[name="FirstName"]').val());
Use this (the form-element) as context-argument:
alert($('input[name="FirstName"]',this).val());

Categories