Clone form fields with value - javascript

I am trying to clone a form, along with its respective fields values. However, I am getting one field value in all cloned fields.
var $couriers = $('#do-list');
$('.add-do-list').click(function( e ) {
var $cloneElem = $couriers.children('.myform').last().clone();
$cloneElem.find('select').attr('value', $('select').val()).end()
$cloneElem.find('input[type=text]').attr('value', $('input[type=text]').val()).end()
$cloneElem.find('textarea').attr('value', $('textarea').val()).end()
$cloneElem.insertAfter( $couriers.children('.myform').last() );
e.preventDefault();
});
HTML:
<ul id="do-list">
<li class="myform">
<form>
<input type="text" name="fname" value="to be clone" />
<input type="text" name="lname" value="to be clone" />
<textarea name="detail">to be clone</textarea>
</form>
<div class="add-do-list">Duplicate form</div>
</li>
</ul>

First line, you have , after $('#do-list'). There needs to be a semi-colon or ;.
Before the first .find you need $cloneElem for it find inside.
Try this:
var $couriers = $('#do-list');
$('.add-do-list').click(function( e ) {
var $cloneElem = $couriers.children('.myform').last().clone();
$cloneElem.closest('select').attr('value', $('select').val()).end()
.closest('input[type=text]').attr('value', $('input[type=text]').val()).end()
.closest('textarea').attr('value', $('textarea').val()).end()
.insertAfter( $couriers.children('.myform').last() );
e.preventDefault();
});
UPDATE
Replaced .find() with .closest()
JSFiddle Demo

Related

How to Fill value= section of form from another section of webpage?

So, right now I have this small unordered list.
<ul id="sortable2" class="connectedSortable">
<li id="litem1" class="ui-state-highlight">A Comfortable Life</li>
<li id="litem2" class="ui-state-highlight">An Exciting Life</li>
</ul>
Then, I have series of hidden inputs in a form for sending information to the next page.
<form action="Instrumental_Values1.php" method="POST">
<input type="hidden" name="item1" value="<script getElementById('litem1').innerhtml();></script>"/>
<input type="hidden" name="item2" value="<script getElementById('litem2').innerhtml();></script>"/>
</form>
My problem is that my bit of code to try to grab the list item values by ID and make the them equal to "value" in the hidden inputs doesn't work. I need to transfer those list items and make them the "value" in the hidden input.
So essentially, the next page is a php file that is just echoing those values back, like so:
<?php
$val1=$_POST['item1'];
$val2=$_POST['item2'];
echo $val1.' '.$val2;
?>
Does anyone know what I'm doing wrong or have an example to share? I have to use PHP to do this, a Javascript solution is not tenable.
This should work.
I've used .val().
Reference: jQuery Documentation
Add ids to the inputs:
<form action="Instrumental_Values1.php" method="POST">
<input type="hidden" id="item1" name="item1" value="" />
<input type="hidden" id="item2" name="item2" value="" />
</form>
Add this script to your page:
<script>
$("#item1").val($("#litem1").text());
$("#item2").val($("#litem2").text());
</script>
It looks like you're using classical javascript here, so following that style this might work:
<ul id="sortable2" class="connectedSortable">
<li id="litem1" class="ui-state-highlight">A Comfortable Life</li>
<li id="litem2" class="ui-state-highlight">An Exciting Life</li>
</ul>
<form id="theForm" action="Instrumental_Values1.php" method="POST">
<input type="hidden" id="formItem1" name="item1" value="" />
<input type="hidden" id="formItem2" name="item2" value="" />
</form>
<script>
//Set Form Value 1
var formItem1 = document.getElementById("formItem1");
formItem1.value = document.getElementById("litem1").innerHTML;
//Set Form Value 2
var formItem2 = document.getElementById("formItem2");
formItem2.value = document.getElementById("litem2").innerHTML;
//Auto submit the form
document.getElementById("theForm").submit();
</script>
The idea here is to set your form values in a script tag instead of trying inline JavaScript. From your original code, it looks like the values in your form would have been a string in the form of '<script getElementById('litem1').innerhtml();></script>' instead of the actual list value. Also, I didn't know how you where sending your form so the last line in the script tag will automatically send the form.
You dont't need to add ids or names to the elements and you need only one ul. The script will do that for you.
How it works
It simply writes the content of the li items in an array when the order changes and then writes the content to the hidden inputs.
<body>
<ul id="sortable" class="connectedSortable">
<li class="ui-state-highlight">A Comfortable Life</li>
<li class="ui-state-highlight">An Exciting Life</li>
<li class="ui-state-highlight">A Sense of Accomplishment</li>
</ul>
<form id="sortable-form" action="test.php" method="POST">
<input type="hidden" value="" />
<input type="hidden" value="" />
<input type="hidden" value="" />
<br />
<input type = "submit" value = "Next Page">
</form>
</html>
<script>
$(document).ready(function() {
// ADD IDS TO LI
var litem_id = 1;
$("#sortable li").each(function(){
$(this).attr('id', "litem" + litem_id);
litem_id++;
});
// ADD IDS AND NAMES TO INPUTS
var item_id = 1;
$("#sortable-form input[type='hidden']").each(function(){
$(this).attr('id', "item" + item_id);
$(this).attr('name', "item" + item_id);
item_id++;
});
$( "#sortable" ).sortable({
connectWith: "#shopping-cart"
});
$( "#sortable" ).sortable({
stop: function( event, ui ) {
var values = [];
$("#sortable li").each(function(){
// SAVE ITEMS IN ARRAY
values.push($(this).text());
});
var i = 0;
$("#sortable-form input[type='hidden']").each(function(){
// WRITE ITEMS TO INPUTS
$(this).val( $(values).get(i) );
i++;
});
}
});
});
</script>

jquery - copy value of input from one form to another (form and input named the same)

I would like to copy the value from an input in one form to the value of an input(with the same name) of the next form down. The forms and inputs are named the same. All it needs to do is copy the value of the title input to the title input one form down.
<form>
<input name="file" value="1.xml">
<input name="title" id="title" value="Smith">
<input type="submit" id="copy-down" value="copy">
</form>
<form>
<input name="file" value="2.xml">
<input name="title" id="title" value="Anderson">
<input type="submit" id="copy-down" value="copy">
</form>
etc...
In this case when the top "copy" button is clicked I would like jquery to overwrite Anderson with Smith.
$('#title').attr('value'));
Gives me Smith but I'm not sure what to do with that value once I have it.
Change HTML to this:
<form>
<input name="file" value="1.xml">
<input name="title" id="title1" value="Smith">
<input type="submit" id="copy-down1" value="copy">
</form>
<form>
<input name="file" value="2.xml">
<input name="title" id="title2" value="Anderson">
<input type="submit" id="copy-down2" value="copy">
</form>
Javascript:
function copyHandler() {
var copyVal = document.getElementById("title1").value;
var replaceInput = document.getElementById("title2");
replaceInput.value = copyVal;
}
document.getElementById("copy-down1").onclick = function(){
copyHandler();
return false;
}
Some notes:
This is so straightforward in vanilla javascript that I didn't add the jQuery code.
You should never assign multiple elements to the same ID, class or name can be used for that purpose.
The return false; portion of the onclick function is necessary so that the form doesn't reload when you click your submit button.
Let me know if you have any questions.
you can try
$(document).ready(function(){
$('form').on('submit', function(e){
e.preventDefault();
var GetNameAttr = $(this).find('input:nth-child(2)').attr('name');
var GetTitleValue = $(this).find('input:nth-child(2)').val();
var NextFormNameAttr = $(this).next('form').find('input:nth-child(2)').attr('name');
if(NextFormNameAttr == GetNameAttr){
$(this).next('form').find('input:nth-child(2)').val(GetTitleValue );
}
});
});
Note: this code will change the second input value in next form with
the second input value of form you click if the name is same .. you
can do the same thing with the first input by using :nth-child(1)
Demo here
if your forms dynamically generated use
$('body').on('submit','form', function(e){
instead of
$('form').on('submit', function(e){
for simple use I create a function for that
function changeNextValue(el , i){
var GetNameAttr1 = el.find('input:nth-child('+ i +')').attr('name');
var GetTitleValue1 = el.find('input:nth-child('+ i +')').val();
var NextFormNameAttr1 = el.next('form').find('input:nth-child('+ i +')').attr('name');
if(NextFormNameAttr1 == GetNameAttr1){
el.next('form').find('input:nth-child('+ i +')').val(GetTitleValue1);
}
}
use it like this
changeNextValue($(this) , nth-child of input 1 or 2);
// for first input
changeNextValue($(this) , 1);
// for second input
changeNextValue($(this) , 2);
Working Demo

Confusion performing 2 .finds() after cloning a div

Hi all I have the following code as seen below whch adds a new row consisting of a text field and radio button, I have written the JS to add a new row, and I use a .find() to append the new input field with a blank value. I am new to JS and want to perform another .find() when cloning to add a value to the radio input, could someone show me how to do so please.
<div id='1'>
<div class="template">
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
JS to add new row:
var $template = $('.template');
$('input[type=button]').click(function() {
$template.clone().insertAfter($template).find("input:text").val("");
});
Just get the cloned template and use any method you like on it before inserting it back:
var $template = $('.template');
$('input[type=button]').click(function() {
var $elem = $template.clone();
$elem.find("input:text").val("");
$elem.find("input:radio").val("whatever");
$elem.insertAfter($template);
});
Here's a fiddle: http://jsfiddle.net/SWCPD/1/
You can try like this -
var $clone = $template.clone();
$clone.find("input:text").val("");
$template.after($clone);
var $clonedNode = $template.clone();
$clonedNode.find('input:text').val('');
$clonedNode.find('input:radio').attr('checked', 'checked');
$template.insertAfter($clonedNode);
is to set the radiobutton to checked.

select particular input field name of particular form

i have some html code like this
<form name="first"><input name="firstText" type="text" value="General" />
<input name="secondText" type="text" value="General" />
<input name="ThirdText" type="text" value="General" />
<input name="FourthText" type="text" value="General" />
<input name="FifthText" type="text" value="General" />
</form>
<form name="second"><input name="firstText" type="text" value="General" />
<input name="secondText" type="text" value="General" />
<input name="ThirdText" type="text" value="General" />
<input name="FourthText" type="text" value="General" />
<input name="FifthText" type="text" value="General" />
</form>
i want to select "secondText" of form "second" using jquery or javascript and i want to change value of it using jquery.
Using jQuery:
var element = $("form[name='second'] input[name='secondText']");
Using vanilla JS:
var element = document.querySelector("form[name='second'] input[name='secondText']");
Changing the value: element.val(value) or element.value = value, depending of what you are using.
To the point with pure JS:
document.querySelector('form[name=particular-form] input[name=particular-input]')
Update:
This selector will return the input named "particular-input" inside form named "particular-form" if exists, otherwise returns null.
The selector filter "form[name=particular-form]" will look for all forms with name equals "particular-form":
<form name="particular-form">
The selector filter "input[name=particular-input]" will look for all input elements with name equals "particular-input":
<input name="particular-input">
Combining both filters with a white space, I mean:
"form[name=particular-name] input[name=particular-input]"
We are asking for querySelector(): Hey, find all inputs with name equals "particular-input" nested in all forms with name equals "particular-form".
Consider:
<form name="particular-form">
<input name="generic-input">
<input name="particular-input">
</form>
<form name="another-form">
<input name="particular-input">
</form>
<script>
document.querySelector('form[name=particular-form] input[name=particular-input]').style.background = "#f00"
</script>
This code will change the background color only of the second input, no matter the third input have same name. It is because we are selecting only inputs named "particular-input" nested in form named "particular form"
I hope it's more clear now.
;)
By the way, unfortunately I didn't found good/simple documentation about querySelector filters, if you know any reference, please post here.
// Define the target element
elem = jQuery( 'form[name="second"] input[name="secondText"]' );
// Set the new value
elem.val( 'test' );
Try
$("form[name='second'] input[name='secondText']").val("ENTER-YOUR-VALUE");
You can do it like this:
jQuery
$("form[name='second'] input[name='secondText']").val("yourNewValue");
Demo: http://jsfiddle.net/YLgcC/
Or:
Native Javascript
Old browsers:
var myInput = [];
myInput = document.getElementsByTagName("input");
for (var i = 0; i < myInput.length; i++) {
if (myInput[i].parentNode.name === "second" &&
myInput[i].name === "secondText") {
myInput[i].value = "yourNewValue";
}
}
Demo: http://jsfiddle.net/YLgcC/1/
New browsers:
document.querySelector("form[name='second'] input[name='secondText']").value = "yourNewValue";
Demo: http://jsfiddle.net/YLgcC/2/
You can try this line too:
$('input[name="elements[174ec04d-a9e1-406a-8b17-36fadf79afdf][0][value]"').mask("999.999.999-99",{placeholder:" "});
Add button in both forms. On Button click find nearest form using closest() function of jquery. then using find()(jquery function) get all input values. closest() goes in upward direction in dom tree for search and find() goes in downward direction in dom tree for search. Read here
Another way is to use sibling() (jquery function). On button click get sibling input field values.

How to get siblings in different DIVs or SPANs?

I have a number of forms on a page, like this:
<form>
<input type="hidden" name="id" value="someID1">
<div>
<span>
<input type="submit" class="submitClass">
</span>
</div>
<div>
<input type="text" name="name" class="someClass" value="name1">
</div>
</form>
<form>
<input type="hidden" name="id" value="someID1">
<div>
<span>
<input type="submit" class="submitClass">
</span>
</div>
<div>
<input type="text" name="name" class="someClass" value="name1">
</div>
</form>
Then I have some JS:
jQuery(document).ready(
function()
{
console.log("page loaded");
jQuery(".submitClass").on("click", function() {
var id = jQuery(this).siblings("input[name='id']").val();
var name = jQuery(this).siblings("input[name='name']").val();
console.log(id);
console.log(name);
return false;
});
}
);
JSFIDDLE: http://jsfiddle.net/sEXg3/
When the submit button is clicked, I want to stop the form from being submitted and get the values of the two inputs I have next to the submit button.
I tried doing this with the .siblings() function, but it doesn't work since the inputs are in different DIVs/SPANs (if I put them all right next to each other, it does work).
How can I accomplish this?
The elements you are looking for are not the sibling of the submit button.
In your case I would suggest to find the form element (you can find the form element in which the clicked button is present using .closest()) and them find the desired inputs fields inside it using .find()
jQuery(function ($) {
console.log("page loaded");
$(".submitClass").on("click", function () {
var $this = $(this),
$form = $this.closest('form');
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();
console.log(id);
console.log(name);
return false;
});
});
Demo: Fiddle
Since your .submitClass is placed in div and in span it's not a sibling of the other inputs... you can try something like this: (Working jsFiddle)
var id = jQuery(this).closest('form').find("input[name='id']").val();
var name = jQuery(this).closest('form').find("input[name='name']").val();
You first look for the parent form, then inside it look for the input fields.. an even more efficient version will be:
var $form = jQuery(this).closest('form');
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();

Categories