Jquery clone a div with inputs fields(and relative values) - javascript

I have to copy a div in which there are multiple input fields.
var a = $('#divscossalina1').html();
$('#riepilogo').html(a);
If i clone an input field directly,the relative value is cloned as well.
This is not happening if i clone the container div.(the fields are cloned but not the values)
Is there a way to clone all input fields with the values,simply cloning the container div?(or rather
writing only one clone() function and not how many the fields are.)

Html:
<div id="one">
<input type="text" name="product" value="5" class="in" />
<input type="text" name="product" value="6" class="in" />
<input type="text" name="product" value="7" class="in" />
</div>
<button id="button">Add field</button>
JQuery:
$('#button').click(function(){
$('#one').clone().insertAfter("#one");
});
This even clones the value in them, working Fiddle

In jQuery, there is a method named "clone". you can read api: http://api.jquery.com/clone/
$('riepilogo').html($('#divscossalina1').clone());
and see my fiddle demo : http://jsfiddle.net/bigxiang/533zU/
Hope it works:)

Related

Find the nearest id in javascript

I have two divs
<div class="maca">
<input type="hidden" value="1">
<div onclick="removeInput(nearest input type hidden)">Remove</div>
</div>
<div class="maca">
<input type="hidden" value="1">
<div onclick="removeInput(nearest input type hidden)">Remove</div>
</div>
I want to send as a parameter the value of nearest input type hidden of that div that we are clicking on
Im not 100% sure what you mean with nearest but with this you get the input hidden inside the div. By the way you could also put the element.parentNode.querySelector into the onclick but personally i like it more to split HTML and JS.
function removeInput(element){
let value = element.parentNode.querySelector("input[type='hidden']").value;
console.log(value);
}
<div class="maca">
<input type="hidden" value="1">
<div onclick="removeInput(this)">Remove</div>
</div>
<div class="maca">
<input type="hidden" value="5">
<div onclick="removeInput(this)">Remove</div>
</div>
You can send the event as a parameter to a javascript function and then find the input via the parentNode. This isn't a literal interpretation of your question since faithfully the "nearest" element is rather complex and probably not what you're looking for.
function removeInput(e) {
const nearestInput = e.target.parentNode.querySelector("input[type='hidden']");
console.log(nearestInput);
}
<div class="maca">
<input type="hidden" value="1" />
<div onclick="javascript:removeInput(event)">Remove</div>
</div>
<div class="maca">
<input type="hidden" value="1" />
<div onclick="javascript:removeInput(event)">Remove</div>
</div>
You should not use inline event listeners, which are widely considered bad practice.
Instead, use addEventListener to add the click listeners, and find the input (given your markup structure is fix like you've shown) using previousElementSibling:
for (const remover of document.querySelectorAll('.remove-input')) {
remover.addEventListener('click', () => remover.previousElementSibling.remove(), { once: true });
}
<div class="maca">
<input type="hidden" value="1" />
<div class="remove-input">Remove</div>
</div>
<div class="maca">
<input type="hidden" value="1" />
<div class="remove-input">Remove</div>
</div>

How can I add a div around two elements yourself using JQuery? [duplicate]

How would I go about using wrap() to wrap multiple elements (with different classes) inside a <div>?
For example, on the form I'm working on there is a big list of checkbox inputs and labels in the form of:
<input>
<label>
<input>
<label>
etc
I'm wanting to wrap a <div> around the input and label, so the result would be:
<div>
<input>
<label>
</div>
<div>
<input>
<label>
</div>
Thanks!
You can use the .wrapAll() method.
$('form > input').each(function(){
$(this).next('label').andSelf().wrapAll('<div class="test"/>');
});
If your markup has always the exact same order, I'd prefer to use:
var $set = $('form').children();
for(var i=0, len = $set.length; i < len; i+=2){
$set.slice(i, i+2).wrapAll('<div class="test"/>');
}
Should be significant faster.
Ref.: .wrapAll(), .andSelf(), .slice()
$('input+label').each(function(){
$(this).prev().andSelf().wrapAll('<div>');
});​
If you have something like this:
<input id="input1">
<label id="label1">
<input id="input2">
<label id="label2">
Then you can use jQuery:
jQuery("#input1").next().andSelf().wrapAll('<div id="newDiv" />');
jQuery("#input2").next().andSelf().wrapAll('<div id="newDiv" />');
and get this:
<div id="newDiv">
<input id="input1">
<label id="label1">
</div>
<div id="newDiv">
<input id="input2">
<label id="label2">
</div>
Worked for me :-)
jQuery function wrapAll allows you to wrap multiple elements but if you have a DOM like you wrote then it won't work too well as you can't easily match a part of label and input with a selector. I suggest adding some classes to each part and then using wrapAll.
<input class="i1"/>
<label class="i1"/>
<input class="i2"/>
<label class="i2"/>
$('.i1').wrapAll('<div/>');
$('.i2').wrapAll('<div/>');
This will give you
<div>
<input class="i1"/>
<label class="i1"/>
</div>
<div>
<input class="i2"/>
<label class="i2"/>
<div>

jQuery remove selected element, dynamically generated

I have a form and I can dynamically add more lines but if I try to remove a specific line it does not work, however the first line gets removed with no problem.
Here is the html:
<form class="order-form">
<div class="product-lines">
<!-- Product Line Section -->
<div class="product-line">
<img alt="remove" src="img/close.png" />
<input class="input-text" name="product-code" type="text" placeholder="Product Code" ></input>
<input class="input-text" name="product-quantity" type="text" placeholder="Quantity"></input>
<input class="input-text" name="product-discript" type="text" placeholder="Discription of Product"></input>
<label class="label-sign">£</label>
<input class="input-text" name="product-price" type="text" placeholder="RRP Price"></input>
<br>
</div>
</div>
<div id="product-btn">
<input name="btn-add-line" type="button" value="Add new line"></input>
<input name="btn-update" type="button" value="Update"></input>
<input name="btn-submit" type="submit" value="Submit Order"></input>
<label class="label-sign">£</label>
<input class="input-text" name="order-info" type="text" placeholder="Order total" ></input>
</div>
</form>
The jQuery code I have tried:
$(".btn-close").on("click", function(e){
$(e.currentTarget).parent().remove();
});
I've also Tried
$(e.currentTarget).parents("div.product-lines).next("div.product-line).remove();
Any help would be most appreciated, also a explanation would be very helpful for me to learn.
Try something like
$(".product-lines").on("click", ".btn-close", function(e){
$(e.currentTarget).parent().remove();
});
You cannot attach events to objects that are not currently on page (lines).
You have to attach click event on product-lines object and when it is clicked you delegate event to "closest" product-line object!
You will need to changed the jQuery slightly to allow for Event Delegation. This means all elements added in future will get the event attached to them too.
$(document).on("click", ".btn-close", function(e){
$(e.currentTarget).parent().remove();
});
$('body').on('click','button id/class',function(){
$(e.currentTarget).parent().remove();
});
but if u use this code it will remove <div class="product-line">...</div>
why you want to remove this div.
i dont get your question very well. Explain in details and step by step .

PrototypeJS get value of each input

I write following function to read inputs from my fieldset, it works but I have no idea how to read value of selected this way input
$$('#split_edit div label input').each(
function(item) {
console.log(item);
}
);
This is my html structure, I can't read input value using its ID because they are dynamically generated.
<fieldset id="split_edit">
<div class="top-10">
<label>
<span class="span-3 left">Item 1 (%)</span>
<input type="text" class="text" name="packet_1" value="0" id="packet_3">
</label>
</div>
<div class="top-10">
<label>
<span class="span-3 left">Item 1 (%)</span>
<input type="text" class="text" name="packet_2" value="0" id="packet_7">
</label>
</div>
</fieldset>
How to select value from input selected by each function in PrototypeJS?
I'm sorry for obvious question but I have started using PrototypeJS several hours ago.
Using item.value:
$$('#split_edit div label input').each(function(item) {
console.log(item.value);
});

Duplicating HTML elements and the contents within in the HTML document

Suppose I have the following code:
<div id="Car1Container">
<label id="Car1YearLabel" for="Car1Year">Year</label>
<input id="Car1Year" name="Car1Year" type="text" maxlength="4" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<label id="Car1MakeLabel" for="Car1Make">Make</label>
<input id="Car1Make" name="Car1Make" type="text" maxlength="15" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<label id="Car1ModelLabel" for="Car1Model">Model</label>
<input id="Car1Model" name="Car1Model" type="text" maxlength="16" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<button id="AddVehicleButton1" name="AddVehicleButton1" type="button" onclick="AddVehicle()">Add Vehicle</button>
</div>
<div id="Car2Container" style = "display: none;">
<label id="Car2YearLabel" for="Car2Year">Year</label>
<input id="Car2Year" name="Car2Year" type="text" maxlength="4" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<label id="Car2MakeLabel" for="Car2Make">Make</label>
<input id="Car2Make" name="Car2Make" type="text" maxlength="15" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<label id="Car2ModelLabel" for="Car2Model">Model</label>
<input id="Car2Model" name="Car2Model" type="text" maxlength="16" onfocus="FieldOnFocus(this)" onkeydown="FieldOnKeyDown(this)" onkeyup="FieldOnKeyUp(this)" onblur="FieldOnBlur(this)"/>
<button id="AddVehicleButton2" name="AddVehicleButton2" type="button" onclick="AddVehicle2()">Add Vehicle</button>
</div>
Currently, AddVehicle() just changes the Car2Container style to 'block'. I have a finite number of these and I want it to be dynamic. I have some code to attempt to write it to a page, but it erases everything on the page and doesn't really work.
I want to write an AddVehicle() function to duplicate the Car1Container and place it right below in the HTML document (except all the 1s become 2s). This is turning out to be quite a challenge! Can anyone help get me moving in the right direction?
Thanks!
You can use cloneNode(true) for cloning the block, then go through childNodes property to find all the children (maybe recursively) and replace their ids and names.
Added: Here's a working example:
var container = document.getElementById('Car1Container');
var copy = container.cloneNode(true);
container.parentNode.appendChild(copy);
The jQuery Clone() will do this rather nicely. Granted, it won't increase the ID's, but I'm not convinced it needs to. Just name the fields CarYear, CarMake etc. When the values are posted to the server, if you've duplicated three of the div's, they'll be comma-separated. If necessary, you could iterate through the items and change the id's manually.
I think the jquery clone function would be useful for this.
If you want to use jquery you can just do:
var index = 1;
function copycar(){
index++;
var $tmp = $("#Car1Container").clone();
$tmp.children().each(function(){
var oldID = $("this").attr("id");
var newId = oldId.substring(0,3)+index+oldId.substring(4);
$(this).attr("id", newId);
}
$("#Car1Container").after($tmp);
}
Without using jQuery, just raw JavaScript you could use insertAdjacentHTML.
Example:
document.getElementById(‘ID’).insertAdjacentHTML(position, markup)
where position can be "beforebegin", "afterbegin", "beforeend", or "afterend"
http://lionheart.sg/insertadjacenthtml/
This should be faster than the clone method in jQuery.

Categories

Resources