Appending/Replicating HTML from DOM in current state to a div - javascript

I have a form on a page. The form contains text inputs, checkboxes, selects (interactive elements). I want the user to be able to click a button, and reproduce a portion of the form elsewhere on the page, in the current state, preserving the text entered, the checkboxes checked, and the selects selected.
Currently I have this, which appends the HTML, however it grabs the HTML in the state it was when the page was loaded.
$('#create_unique_field').click( function() {
$('#unique_field_cnt').append($('#template_cnt').html());
});
I have tried using delegation using on(), like so, with the same results.
$( 'body' ).on( 'click', '#create_unique_field', function() {
$('#unique_field_cnt').append($('#template_cnt').html());
});
What I want is the current state of the HTML, not the HTML at the point when the page was loaded. How can I accomplish this?

It doesn't work that way, you need to bind values of form elements and create new form elements with that data. More or less it falls on var inputText = $('#someInputEl').val(); and then applying that values on new form elements and THEN inserting it.
Try this:
<input type="text" id='one'>
<button>submit</button>
<div id="target"></div>
$(function(){
$('button').click(function(){
var inputVal = $('#one').val();
var newInputEl = $("<input type='text' id='two'>");
newInputEl.val(inputVal);
$('#target').html( newInputEl );
});
});
This is rough sketch but you should make it work this way, here is fiddle.

Related

jquery - Add field dynamically not functioning fully

based on tutorial from here ,I'm trying to make some fields which can dynamically be added by a button an removed by another button. It almost works fine except that another group of fields that supposed to be created dynamically as well is not adding anything.
Here's what i did at codepen.
<div class="field_wrapper">
New Group
</div>
<script>
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div>X<table id="add_on_table"><tbody><tr><td><label class="field">Group Name</label><input type="text" name="product_addon_name[]"></td><td><input type="checkbox" name="product_addon_required[]"> Mark as Required</td></tr><tr><td><label class="field">Group Description </label><textarea name="product_addon_description[]"></textarea></td></tr><tr><table><thead><tr><td>Option Label</td><td>Option Price (RM) </td></tr></thead><tbody class="addonoption"><tr><td><input type="text" name="product_addon_option_label[]"></td><td><input type="text" name="product_addon_option_price[]"></td><td>X</td></tr> </tbody><tfoot><tr><td><input type="button" class="add_option" value="New Option"></td></tr></tfoot></table></tr></tbody></table></div>'; //New input field html
var AddRow = $('.add_option'); //Add button selector
var RowWrapper = $('.addonoption'); //Input field wrapper
var rowHTML = '<tr> <td><input type="text" name="product_addon_option_label[]"></td><td><input type="text" name="product_addon_option_price[]"></td><td>X</td></tr>';
var x = 1; //Initial field counter is 1
$(AddRow).click(function(){ //Once add button is clicked
$(RowWrapper).append(rowHTML); // Add field html
});
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});</script>
In reference to what I did in the linked codepen, the fields generated OK when pressed the 'New Group' link. However, the button 'New Option' does not create anything once clicked. You can see in the JS section i write some code to create field, but it's just not working. Any idea why? Btw, i'm quite noob at javascript/jquery, so, sorry if it's just a stupid mistake. Thanks in advance!
You need to use event delegation with the .add_option elements too. Since they are created after the DOM is initially rendered, your click handler does not attach to anything. You use event delegation for the .remove_button, so you can copy that syntax to make it work:
$(document).on("click", ".add_option", function(){ //Once add button is clicked
$(this).closest("table").find(".addonoption").append(rowHTML);
});
Also, I noticed that your selector is potentially messed up too because if you have multiple groups, it will add the html to each one of them. If this is the intended behavior, you can change the selector to $(".addonoption").append(rowHTML), otherwise, the above code will work for you!
The problem is that when you try to add a click handler to AddRow, your button does not exist yet. Instead of creating a handler to AddRow, you need to use the .on() function. Example:
$(".field_wrapper").on("click", ".add_option", function() {alert("foo");});
Explanation:
.field_wrapper as a selector already exists when you call on
click is the event you intend to handle
.add_option is a selector which will apply to existent and not yet existent elements inside .field_wrapper that match .add_option
the function is the event handler to be executed

create reset value button on select2

im using select2 and try to create a reset button for each select. i have 6 select.
my script is like this
$('.deggre').on('change', function() {
var deggre = $( this ).val();
var span = $("#dropdownMenu1").find('span').clone(); // Copy 'X' span.
$("#dropdownMenu1").text(deggre); // Insert text first.
$("#dropdownMenu1").append(span); // Then, append the 'X' span.
if($(this).val() == "")
$('#dropdownMenu1').css({"display": "none"});//value is none then hide
else
$('#dropdownMenu1').css({"display": "inline-block"});//have value then show
});
$("#dropdownMenu1").click(function(){
$(".deggre").val("");
});
my script didnt work for this case. how to solve this problem?
i need to show the button when we choose option on select2, and give innerHtml to the button. and then when the button click, its will reset his own select then the button is gone cause it didnt get the value.
heres my jsfiddle
https://jsfiddle.net/acvxeq8x/2/
You need to trigger the change
$("#dropdownMenu2").click(function(){
$(".position").val("").trigger('change');
});
I have updated your fiddle: https://jsfiddle.net/acvxeq8x/3/
Here is the simplified and minimal version of your code which is pretty straight forward. The code below seems long because of comments added within for explanation. Hope you will ignore them once you understand.
HTML Changes
<div class="wrap">
<!--Remove everything within wrap div and keep one copy of button in js to dynamically
construct the button tag-->
</div>
New CSS added
button.btnspl{
margin:10px;
/*Bit styling for dynamically created buttons*/
}
JS Changes
//Bind single change event to all your select element
$('.deggre,.position,.year').on('change', function() {
var ctrl=$(this); //reference for current element
var ctrlClass=ctrl[0].classList[0]; //get the first class which will be the class given
//to your original select element like deggre, position, year etc.,
$('button.btnspl[data-control="'+ctrlClass+'"]').remove();
//Since your select element is single select type, I hope you want to keep only one tag
//for each select. So, you remove other tags with above line
if(ctrl.val() == "")return; //return if value is empty, you aren't creating anything
var btn=$('<button class="btn btn-grey btnspl" type="button"><span class="glyphicon glyphicon-remove"></span></button>');
//Button copy from your wrap div
var option = $('<span>'+ctrl.val()+'</span>');
//get the selected option and place it in span
var span = $(deggre).insertBefore(btn.find('span'));
//insert the above created span before the glyphicon-remove in button
btn.attr('data-control',ctrlClass);
//the created button should have information about the control which created it
//so wrapping the ctrlClass [deggre, year, position] into data-* attribute of created button
//this will be used to remove particular button and clear its respective select,
//on different scenarios
$('.wrap').append(btn);
//append the button to .wrap div
});
//attaching close click event to glyphicon-remove.
//Read about event-delegation for dynamically created elements
//button is dynamically created here
$('.wrap').on('click','.glyphicon-remove',function(){
var ctrl=$(this).closest('.btn');
//get the parent of the clicked remove icon using closest
var ctrlClass=ctrl.attr('data-control');
//get its data-control attribute added during creation
$('.'+ctrlClass).val("").trigger('change');
//empty its value and trigger change
ctrl.remove();
//remove the control
})
JSFiddle DEMO

Insert value in input box by clicking a hyperlink

A table column displays student id numbers as follows:- (PHP code)
echo "<td><b><a href = '#'><h1>".$res['studid']."</h1></a></b></td>";
Below the table there is an input box to enter student id
I want to add the value of $res variable into the input box when the user clicks the above link.
That value will be later used to search the result of that particular student
How to achieve this with Javascript?
var studentLinks=document.querySelectorAll('td>b>a>h1');
for(var i=0;i<studentLinks.length;i++){
studentLinks[i].parentNode.addEventListener('click',function(){
document.getElementById('yourInputField').value=this.children[0].innerHTML;
});
}
Non-jQuery way of applying this functionality to all elements.
By the way, the a element is then non-essential, so it could as well be removed and td>b>h1 be written as the selector instead.
Anyways, the above JavaScript is applied to all links. You can also put an e inside the brackets after function and at the top of the function block add e.preventDefault(); to make absolutely sure that the page doesn’t redirect anywhere.
var link = document.getElementById('studentId');
var input = document.getElementById('search');
link.addEventListener('click', function() {
input.value = this.innerText;
});
<td><b><h1>Some text</h1></b>
</td>
<input type="text" id="search">
Well a Jquery way...
$("#table a").click(function(){
$("#input").val($(this).find('h1').text());
});

Change Text Field Once Drop Down Has Been Selected (Multiple forms on 1 page)

I'm looking to change the value of a <p> tag once an option from a drop down has been selected. I have that working but my issue is I am going to have lots of forms on one page and feel like I am repeating my code. Is there a way to do this with a function for example? To save me writing a new section of javascript everytime a form gets added to my page?
My javascript code:
$('.orderProduct select#packageOption').change(function(){
$('#packagePrice').html($(this).val());
});
$('.orderProduct2 select#packageOption').change(function(){
$('#packagePrice2').html($(this).val());
});
Thanks.
Add a data-element-id attribute to each select like:
<select data-element-id="packagePrice">...</select>
<select data-element-id="packagePrice2">...</select>
then you simply need this jQuery code:
$('select[data-element-id]').change(function(){
var $this = $(this);
var id = $this.data('element-id');
$('#' + id).html($this.val());
});
If you want to avoid the extra attribute you could use jQuery's DOM traversing functions, to locate which p you should update.

jQuery clone() leaves user data in input field

See jsfiddle: http://jsfiddle.net/bjCz3/
html
<table>
<tr class="copyMe">
<td><input type="text" name="test" /></td>
</tr>
</table> <a id="clickMe" href="#">Click Me</a>
jquery
$('#clickMe').click(function(event){
event.preventDefault();
var tr = $('.copyMe:last');
var newTr = tr.clone();
newTr.appendTo(tr.parent());
});
If you type text in the input, and click the click me, the row (including the input) is cloned and inserted - and has the data you entered.
The API for clone() says:
The .clone() method performs a deep copy of the set of matched
elements, meaning that it copies the matched elements as well as all
of their descendant elements and text nodes. For performance reasons,
the dynamic state of form elements (e.g., user data typed into input, and textarea or user selections made to a select) is not copied
to the cloned elements. The clone operation sets these fields to
their default values as specified in the HTML.
http://api.jquery.com/clone/
So why does my input have the value filled in, and more important, how can I prevent it? I want them to be empty/default like the documentation implies. I tried specifying both arguments as false even though they default to that, and it still copies it.
If you are working with inputs that aren't checked or have values set on page load. ( or you want defaults that are set)...cache a row before user touches one . Then clone that stored row to append when needed
/* store row on page load*/
var tr = $('.copyMe:last').clone();
$('#clickMe').click(function(event){
event.preventDefault();
var newTr = tr.clone();....
})
As far as a way to clear it yourself.
$('#clickMe').click(function(event){
event.preventDefault();
var tr = $('.copyMe:last');
var newTr = tr.clone();
newTr.find('input').val('');
newTr.appendTo(tr.parent());
});
Update
newTr.find("input[type=text], textarea").val("");
newTr.find('input:checkbox').removeAttr('checked');
http://jsfiddle.net/bjCz3/3/
Do it yourself after filling a bug report at jquery:
$('#clickMe').click(function(event){
event.preventDefault();
var tr = $('.copyMe:last');
var newTr = tr.clone();
newTr.find(":input").val(''); //find all input types (input, textarea), empty it.
newTr.appendTo(tr.parent());
});
Updated working fiddle: http://jsfiddle.net/bjCz3/2/

Categories