Getting the last element of a form jquery - javascript

I am a beginner in programming and am stuck in a problem. I want to find the last child (element) of parent (form). Then I want to insert an input element after the last child but it should be inside the form not after the form (outside). The form might contain input elements as well as select elements. How to accomplish it? I have tried the following ways but they don't work unfortunately.
var lastRepeatingGroup = $('.form-to-be-submitted:last'); // this one gives me the whole form meaning if I add something it will added at the end of the form
var lastRepeatingGroup = $('.form-to-be-submitted input:last'); //this gives me the last input element
var lastRepeatingGroup = $('.form-to-be-submitted input select').last(); //this does nothing, I think its an error
$newSection = $('<input type="button" value="newbutton" name="mybutton"/>');
newSection.insertAfter(lastRepeatingGroup); // when I use this statement it adds after the form not inside the form

So you just need some guidance on CSS Selectors and Jquery methods.
First lets look at:
The form might contain input elements as well as select elements.
So in CSS to do an or you need to use a comma:
input,select
if you are looking for direct descendants you need to use a >
form > input, form > select
These are then wrapped in jquery:
$('form > input, form > select')
Which yields all items, so we use last() to grab the last element:
var $last = $('form > input, form > select').last();
(if you don't need the > just remove it).
This was pretty close:
var lastRepeatingGroup = $('.form-to-be-submitted input select').last();
but it's looking for a select element in a input element in that class. Just needs a little adjustment:
var lastRepeatingGroup = $('.form-to-be-submitted input, .form-to-be-submitted select')
.last();
If you want to insert the element at the end of a specific element, you don't need to find the last item. Just use jquery's append
Except:
Consider the following HTML:
<h2>Greetings</h2>
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
You can create content and insert it into several elements at once:
$( ".inner" ).append( "<p>Test</p>" );
Each inner element gets this new content:
<h2>Greetings</h2>
<div class="container">
<div class="inner">
Hello
<p>Test</p>
</div>
<div class="inner">
Goodbye
<p>Test</p>
</div>
</div>

This should work:
$('.form-to-be-submitted').children().last()
.children() will select all the children in your form and .last() filters that further to only select the last child.
And to insert content after that element, just use .after() like:
$('.form-to-be-submitted').children().last().after('<input>')
Example:
$('.form-to-be-submitted').children().last().after('<input type="radio">')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-to-be-submitted">
<input type="text">
<input type="radio">
<input type="checkbox">
<select>
<option></option>
</select>
</form>

JQuery not needed. To insert a new element just before the end of the form, simply use .appendChild().
var frm = document.getElementById("theForm"); // Get reference to form
// Create a new element and configure it
var newElement = document.createElement("input");
newElement.id = "txtUser";
// Simply append it to the form.
frm.appendChild(newElement);
console.log(frm.elements[frm.elements.length-1]); // Get last element in form
<form id="theForm">
<input type="text">
<select>
<option>one</option>
<option>two</option>
<option>three</option>
</select>
<button type="button">Click Me</button>
</form>

Related

Get value from div to textbox

Is there a way to get the value from a div element to textbox?
My script codes
$(document).ready(function() {
barcode.setHandler(function(barcode) {
$('#result').html(barcode);
});
barcode.init();
I show the result with the following code
<div id="result"></div>
I fail to get the div value into the textBox.
<input type="text" id="result">
To achieve expected result, use below option
Avoid using same id for multiple elements , instead of that use class or two different ids or use one as class and for other use as id
$(document).ready(function() {
console.log( $('#result').text())
$('.result').val( $('#result').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">1222</div>
<input type="text" class="result">
code sample - https://codepen.io/nagasai/pen/yjomXp
Ids need to be unique on a given page; your input and div both have the same id. To insert from the div to the input, first get the text inside the div, then apply that to the input using .val().
const foo = $('#foo').text();
$('#bar').val(foo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
This is inside the div
</div>
<input type="text" id="bar"></input>

How to copy an input element with its value?

I have simple textboxes generated by AJAX.
<input type='text' id='txt1' name='txt1_nm' />
What I'd like to do, when I press a button. The input is all copied inside a different div with its new value inserted by user.
I use
$('#txt1').html();
but, the value is not copied only the textbox
You need to make use of clone() so that you get the element with its value. Type anything in the textbox in the snippet below and press the Copy button.
//detect the click of the copy button
$('#copyBtn').click(function(){
//get the clonned element
var inputElement = $('#txt1').clone();
//add clonned element to a new div
$('#copiedDiv').html(inputElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='text' id='txt1' name='txt1_nm' />
</div>
<div id='copiedDiv'></div>
<button id='copyBtn'>Copy</button>
If you want to add multiple cloned items then you will require to change the id of the input element and then append that to the page. You can do like this to achieve it,
//detect the click of the copy button
$('#copyBtn').click(function(){
//get the last input item
var $inputEl = $('input[name="txt1_nm"]:last');
//get the next id number
var num = parseInt( $inputEl.prop("id").match(/\d+/g), 10 ) +1;
//clone and set a new id for this element
var $cloneEl = $inputEl.clone().prop('id', 'txt'+num );
//add clonned element to a new div
$('#copiedDiv').append($cloneEl);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='text' id='txt1' name='txt1_nm' />
</div>
<div id='copiedDiv'></div>
<button id='copyBtn'>Copy</button>
$(document).on('click','#myBtn',function(){
value=$('#txt1').val();
$('#myDiv').empty();
$('#myDiv').append($('#txt1').clone());
$('#txt1').val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='txt1' name='txt1_nm' />
<button type="button" id="myBtn">Click Me</button>
<div id="myDiv"></div>
You can simply use:
$('#txt1').clone()
It will perform a deep clone of that element with all of its content.
NOTE: Cloning an element will also duplicate its ID if it has one.
You should change any ids to classes beforehand.
This is from the documentation:
Note: Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.

Jquery dynamic creating HTML divs on click

I’m looking for some direction for my problem.
I’ve HTML divs and I want to replicate it when user clicks on span with id plus-1.
This is my html
<div id = “tab”>
<div class="row">
<div>
<select id="ProjectsFolder0FolderId" name="data[ProjectsFolder][0][folder_id]">
<option value="1">Project Presentation</option>
<option selected="selected" value="4">Project Root</option>
</select>
</div>
<div>
<div>
<input type="text" required="required" id="ProjectsFolder0Linux" value="xyz" name="data[ProjectsFolder][0][linux]">
</div>
</div>
<div id="plus-1" >
<span>
Click here
</span>
</div>
</div>
</div>
Jquery
$(document).on('click', '#plus-1' , function() {
var html = "<div class=\"row\" >"
???
+ "</div>";
$('#tab').append(html);
});
It is appending above html defined in jquery , but I don’t know how to append entire HTML efficiently as required above on each click.
Demo FIDDLE
Jquery
$(document).on('click', '#plus-1' , function() {
var html = $(this).parent().clone();
html.find('#plus-1').attr('id','plus-'+($('#tab').find('.row').length+1));
$('#tab').append(html);
});
Made a jsfiddle for you - http://jsfiddle.net/23GCn/. You also have an error in your html, you need to use correct parenthesis on <div id="tab">
jQuery(function($){
var count = 1;
$(document).on("click", "[id^='plus']", function(){
newBlock = $(this).parents(".row").clone();
count += 1;
// change id of Plus button
newBlock.find("[id^='plus']").attr("id", "plus-"+count);
// Change id and name of select box
newBlock.find("select")
.attr("id", "ProjectsFolder"+count+"FolderId")
.attr("name", "data[ProjectsFolder]["+count+"][folder_id]");
// Same for input
newBlock.find("input[type='text']")
.attr("id", "ProjectsFolder"+count+"Linux")
.attr("name", "data[ProjectsFolder]["+count+"][linux]");
// append new element to your tab
$("#tab").append(newBlock);
});
});
Note that [id^='plus'] type selectors are very inefficient, means, slow. Consider using classes instead of ids, this way you avoid all of the code required to change ids, since you can't have elements with same id on your page obviously.

jQuery cannot recognize appended cloned elements using jQuery.appendTo()

I want to make a list of group inputs allow user to dynamically let user add/remove group row:
<div id="div-form-denominations" class="form-denominations">
<div id="row-0" class="form-denomination">
<div class="form-field">
<div class="form-field">
<div class="form-field">
<input id="_denominations[0].id.reference" class="removableHiddenOrder" type="hidden" name="denominations[0].id.reference" value="87-070329-034COP-4444">
<input id="_denominations[0].denomination" class="removableHiddenDenom" type="hidden" name="denominations[0].denomination" value="10000">
<a id="deleteBtn-[0]" class="action-link delete-denomination" href="#">
<div class="spacer"></div>
</div>
<div id="row-1" class="form-denomination">
<div class="form-field">
<div class="form-field">
<div class="form-field">
<input id="_denominations[1].id.reference" class="removableHiddenOrder" type="hidden" name="denominations[1].id.reference" value="87-070329-034COP-4444">
<input id="_denominations[1].denomination" class="removableHiddenDenom" type="hidden" name="denominations[1].denomination" value="">
<a id="deleteBtn-[1]" class="action-link delete-denomination" href="#">
<div class="spacer"></div>
</div>
<div id="row-2" class="form-denomination">
<div class="form-field">
<div class="form-field">
<div class="form-field">
<input id="_denominations[2].id.reference" class="removableHiddenOrder" type="hidden" name="denominations[2].id.reference" value="">
<input id="_denominations[2].denomination" class="removableHiddenDenom" type="hidden" name="denominations[2].denomination" value="">
<a id="deleteBtn-[2]" class="action-link delete-denomination" href="#">
<div class="spacer"></div>
</div>
<div id="row-3" class="form-denomination">
.......
</div>
So each row include a group of form-field which include an input or select component(not show in above code) and some hidden fields and a delete link to remove current row from view.
Also I create a link to dynamic add a new row into the section
var rowTemplate = null;
j(document).ready(function() {
// Save the row template
rowTemplate = j('.form-denomination:first-child').clone();
j("#add_link").click(function() {
add_denomination();
});
});
and here is the content of add_denomination function that clone the first row and replace any cloned id with new index, and append the cloned row after last row of the list.
function add_denomination() {
var index = j('.form-denomination').length;
// set the new row id
var newRowId = 'row-' + index;
var newRow = rowTemplate.clone().attr('id', newRowId);
// Replace the id/name attribute of each input control
newRow.find('div, input, select, a').each(function() {
replaceAttribute(j(this), 'id', index);
replaceAttribute(j(this), 'name', index);
j(this).val('');
});
// add new element to the DOM
newRow.appendTo('.form-denominations');
alert("new list size = " + j(".delete-denomination").length);
console.log("DONE!");
}
each time click on the add-link the pop up alert show the new list size (j(".delete-denomination").length increment by 1), which in my understanding, new row appended successfully.
The problem is the following method
// delete denomination row
j('.delete-denomination').click(function () {
j(this).parent().remove();
}
ONLY WORKS FOR THE NON-CLONED ROW !!! Using firebug I can clearly see the appended row is successfully appended with same structure and same element as original rows but only difference is the id.
However, each time when I click on deleteBtn-[i], in which i is the cloned/appended row's index, the code even not going into the j('.delete-denomination').click() function, which in my understanding, Dom or jquery didn't recognize the new rows hence the failure of identifying the link by jQuery. It's kind of contradictory to the previous alert message that telling the size of list has grown.
But when I click on deleteBtn-[i] where i is the non-cloned row, everything works fine...
So the question is: how to append/add new doms and make them identified by jQuery or Dom? What is wrong in above processing? Is there any way to refresh the list so that Dom/jQuery understand the appended rows from all perspective?
jQuery 1.7+
j(".form-denomination").on("click", ".delete-denomination", function(){
j(this).parent().remove();
});
jQuery 1.3+
j(".delete-denomination").live("click", function(){
j(this).parent().remove();
});
jQuery 1.4.3+
j(".form-denomination").delegate(".delete-denomination", "click", function(){
j(this).parent().remove();
});
The problem is a matter of order and when expressions are evaluated. When you call jQuery with a selector, the selector is evaluated at that time to select the matching elements which exist at that time. The click handler is then registered to only those elements. Elements which are created later are, naturally, not affected.
One solution, demonstrated in another example, uses jQuery's "live events" to apply the selector at the time each event is fired to determine what elements, if any, it would match. There is a performance implication to this approach.
Another solution is to register the desired event handler on the newly created elements when you create them.
Add 'true' to the clone method in order to copy the data as well as the events attached to the original element.
rowTemplate = j('.form-denomination:first-child').clone(true);
This is disabled by default. Here is the clone documentation:
https://api.jquery.com/clone/
P.s. You don't need the click function within the document.ready and it won't bind until after the click.

Pass Info to form input when link is clicked

I have some html that looks as so:
<h3 class="basic left-top-border-radius">Basic<br /> 500<span>$25</span></h3>
<a class="signup colorbox" href="#text-signup-form">More Info</a>
When More Info is clicked a lightbox pops up with a simple info request form. Here is my problem. I would like when the link is clicked to have the text of the h3 header passed to a form input field that is hidden so I know which plan they clicked on for more info.
The input looks like so:
<input type="text" class="cat_textbox" id="CAT_Custom_440761" name="CAT_Custom_440761" maxlength="1024" />
How would I do this using jQuery? (I thought of using jQuery .text() method but I read that does not work with forms and I do not know how to pass the h3 text anyway.
NOTE There are multiple h3 elements on the page.
You can do the following with this code.
$('.signup').click(function(){
var planTitle = $('h3').text();
$('#CAT_Custom_440761').val(planTitle);
});
As you click on the button it will search for the h3 tag (would be better to attach an ID to the h3 tags) grab the text of that element and insert it into the value of the input field.
If you aren't able to attach an ID to the h3 tag you can search for the prev instance of h3 and take the text from that.
$('.signup').click(function(){
var planTitle = $(this).prev('h3').text();
$('#CAT_Custom_440761').val(planTitle);
});
You can try this:
$('a').click( function() {
var text = $(this).parent().find('h3').text();
$(this).parent().find('.cat_textbox').val(text);
})
perhaps you can use this code
<form action="test1.asp" id="testform">
<input type="hidden" id="test3" value="">
<input type="BUTTON" id="submit" onclick="modify_value()"/>
</form>
<script type="text/javascript">
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'testvalue';
document.getElementById("testform").submit();
}
</script>

Categories

Resources