jquery dynamic subselection combining last and form elements - javascript

Update
Tidied up the solution in progress and added some extra details
I have a form area which creates clones based on a template. In order to make sure the form transmits in an order, the script goes through the form at send time appending a number which defines the current batch set. Below is an over simplified representation of what is going on:
<form>
<div class="batch-template">
<div class="batch-piece">
<a class="clone" />
<input name="test-input">
<input name="another-test-input">
<select name="a-drop-down">
</div>
</div>
<div class="batch-paste-area">
</div>
</form>
When the page starts:
The contents of "batch-template" are stored to an object variable
The original template is removed from the page
An instance of the template is appended to the "batch-paste-area"
The following is an example of the output created after clicking twice.
<form>
<div class="batch-template">
</div>
<div class="batch-paste-area">
<div class="batch-piece">
<a class="clone" />
<input name="test-input">
<input name="another-test-input">
<select name="a-drop-down">
</div>
<div class="batch-piece">
<a class="clone" />
<input name="test-input">
<input name="another-test-input">
<select name="a-drop-down">
</div>
</div>
</form>
When it comes to submitting the form: prior to serialization, I would like the script to loop through each "batch-piece" within "batch-paste-area" and add a count value to the end of each form field name. Continuing with the set above, the result (to a browser) would seem like that shown below:
<form>
<div class="batch-template">
</div>
<div class="batch-paste-area">
<div class="batch-piece">
<a class="clone" />
<input name="test-input1">
<input name="another-test-input1">
<select name="a-drop-down1">
</div>
<div class="batch-piece">
<a class="clone" />
<input name="test-input2">
<input name="another-test-input2">
<select name="a-drop-down2">
</div>
</div>
</form>
So far, I can either loop through EVERY input within the paste area or just select the last.
Selecting the last batch-piece is simple:
var intCount = 1;
$('.batch-paste-area .batch-piece').each(function(){
/*
* Would like to be able to loop through form fields here
* Below is an attempt to select all form fields for current set
*/
$(this + ' input, '+ this + ' select').each(function() {
var strName = $(this).attr('name') + intCount;
$(this).attr('name', strName);
});
intCount++;
});

Frustratingly, I had actually tried the correct solution in advance but had forgotten to use the comma at the time!
var intCount = 1;
$('.batch-paste-area .batch-piece').each(function(){
/*
* Would like to be able to loop through form fields here
* Below is an attempt to select all form fields for current set
*/
$(this).find("input, select").each(function() {
var strName = $(this).attr('name') + intCount;
$(this).attr('name', strName);
});
intCount++;
});

Related

Add input to form if button is clilcked

I'm not really sure the best way to go about this but I've laid the framework.
Basically, I would like to add the functionality so that when my #moreItems_add button is clicked and calls the moreItems function, I simply want to add a new Input field below it, and so on. I want to limit this to 10 fields though, so I show that in the function.
The only trick is, I will be submitting all fields via ajax to save to the database, so I need to try and keep track of an ID with each.
What's the best way to continue the javascript here so that I can append an input field on button press and keep track of IDs for each?
<div class="modal-body">
<form id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
<button id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</form>
</div>
<div class="modal-footer">
<input type="submit" name="saveItems" value="Save Items">
</div>
<!-- modal JS -->
<script type="text/javascript">
function moreItems(){
var MaxItems = 10;
//If less than 10, add another input field
}
</script>
You can use the jQuery .insertBefore() method to insert elements right before "more items" button. Below is the code representing this:
var maxItems = 1;
function moreItems() {
if (maxItems < 10) {
var label = document.createElement("label");
label.id="ItemLabel"+maxItems;
label.innerHTML = "Item "+(maxItems+1)+": ";
var input = document.createElement("input");
input.type='text';
input.name = 'item'+maxItems;
$('<br/>').insertBefore("#moreItems_add");
$(label).insertBefore("#moreItems_add");
$(input).insertBefore("#moreItems_add");
maxItems++;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
<form id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
<button type="button" id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</form>
</div>
<div class="modal-footer">
<input type="submit" name="saveItems" value="Save Items">
</div>
Something like this should do the trick:
<!-- modal JS -->
<script type="text/javascript">
var MAX_ITEMS = 10,
added = 0;
function moreItems(){
if (added >= MAX_ITEMS) return;
var newField = document.createElement('input');
newField.type = 'text';
// TODO: Any field setup.
document.getElementById('items').appendChild(newField);
added++;
}
</script>
In terms of tracking each field with an ID, that should always be done by the back-end for data integrity and safety reasons.
some years ago I've wrote an article about making a repeated section using jQuery.
The live example is available on jsFiddle.
In the example you can find that both "add" and "remove" button are available, however you can set just the "add" button for your purpose.
The idea to limit to specific number of repeated boxes is to watch the number of repeatable elements just created in the context. The part of code to change in the live example is rows 13-18:
// Cloning the container with events
var clonedSection = $(theContainer).clone(true);
// And appending it just after the current container
$(clonedSection).insertAfter(theContainer);
There you should check if the number of repeated elements is less than <your desired number> then you will allow the item to be created, else you can do something else (like notice the user about limit reached).
Try this:
const maxItens = 10,
let itensCount = 0;
function moreItems() {
if (itensCount++ >= maxItens) {
return false;
}
let newInput = document.createElement('input');
// use the iterator to make an unique id and name (to submit multiples)
newInput.id = `Items[${itensCount}]`;
newInput.name = `Items[${itensCount}]`;
document.getElementById('items').appendChild(newInput);
return false;
}
Add type "button" to stop submiting the page (also, your button have two ID):
<button id="moreItems_add" onclick="moreItems();" type="button">More Items</button>
The submit button must be inside the form to work:
<form>
<div class="modal-body">
<div id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
</div>
<button id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</div>
<div class="modal-footer">
<button type="submit">Save Items</button>
</div>
</form>
To append itens in sequence the button must be outside of div "itens".

Dynamically Added Input Value disappear on next addition

I am creating a webpage with ability to add input box dynamically , everything works fine. But whenever I add a new input box the value from all the input box added above that field get cleared automatically.
Here is the html which is generated on addition of the element
<div class="main_text_area" id="got_id_from_server">
<p>Add Delay For :</p>
<div class="remove_bg button btn" name="some_id_from_server"></div>
<p>
<div contenteditable class="text_im" placeholder="Enter Delay" id="some_id_from_server" onchange="post_delay(this)"></div>
</p>
<p>
<input class="text_im" placeholder="Select" type="text" id="some_id_from_server" list="some_id_from_server" onchange="post_delay(this)">
<datalist id="some_id_from_server">
<option value="Minutes"></option>
<option value="Hours"></option>
<option value="Days"></option>
</datalist>
</p>
</div>
This behavior occurs because adding new elements to your Dom will cause the Website to kind of render the view again & again so the (in this case) not stored values of a "input field given no ID attribute" you have inputted into your input-element will just reset.
So have a look at this two code snippets:
var count = 0;
function createInput(event) {
count++;
document.body.innerHTML += "<input value='Input #"+ count + "' / >"
event.preventDefault();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="createInput()">Create Input</button>
Edit: Using jQuery will be the better solution so have a look at this code (To prevent the reset of the input fields you have to use "append()". Try it on your own!:
var count = 0;
$(function() {
$("#createInput").click(function(event) {
count++;
$('form').append('<input type="text" value="Input #' + count + '" />');
event.preventDefault();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="myForm" accept-charset="utf-8">
<button id="createInput">Create Input</button>
</form>

Jquery Need siblings value but not working

I want to populate the value of the "eventTitle" in "Requirement" input box when some one click on the corresponding check box. i.e If some one clieck on the check box of Vels Group Of Instutions then automatically i want this to populate in texbox with name "Requirement" if multiple check box are clicked i want it to be comma seperated. Below is the code i tried to get but it is not working and getting undefined.
<div class="wid100">
<div class="eventTitle">Vels Group Of Instutions</div>
<div class="eventDate">2017-07-25</div>
<div class="eventVenue">This is world wide institute of technology </div>
<div class="selectEvent">
<input type="checkbox" class="seminar selected" id="179">
<label for="179"></label>
</div>
</div>
<div class="wid100">
<div class="eventTitle">Title goes here</div>
<div class="eventDate">2017-07-25</div>
<div class="eventVenue">sdfdsafasdfdsafdsafsadfsdfsdf </div>
<div class="selectEvent">
<input type="checkbox" class="seminar" id="179">
<label for="179"></label>
</div>
</div>
<input type="text" name="Requirement" placeholder="Title 01" id="divclass" required="required" class="pull-left" />
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
$(".seminar").click(function () {
if ($(this).is(":checked")) {
//checked
$(this).addClass("selected");
var event_title = "";
event_title = $(".selected").siblings('.eventTitle').val();
console.log(event_title); return false;
} else {
//unchecked
$(this).removeClass("selected");
}
});
.eventTitle is not the sibling of .selected and the .eventTitle is a div element having no value, text there. change this line
event_title = $(".selected").siblings('.eventTitle').val();
to
event_title = $(this).parent().siblings('.eventTitle').text();
or
event_title = $(this).parent().siblings('.eventTitle').html();
The issue you have is because .eventTitle is not a sibling of the clicked checkbox, so the DOM traversal logic is wrong. div elements also do not have a val(), so you should use text() or html() instead.
However, you can improve the logic and also achieve the comma separated list of the selected event titles by using map() to build an array which you can then join() before setting in the value of #divclass. Try this:
$(".seminar").click(function() {
$(this).toggleClass('selected', this.checked);
var eventNames = $('.seminar:checked').map(function() {
return $(this).closest('.wid100').find('.eventTitle').text();
}).get().join(',');
$('#divclass').val(eventNames);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wid100">
<div class="eventTitle">Vels Group Of Instutions</div>
<div class="eventDate">2017-07-25</div>
<div class="eventVenue">This is world wide institute of technology </div>
<div class="selectEvent">
<input type="checkbox" class="seminar selected" id="179">
<label for="179"></label>
</div>
</div>
<div class="wid100">
<div class="eventTitle">Title goes here</div>
<div class="eventDate">2017-07-25</div>
<div class="eventVenue">sdfdsafasdfdsafdsafsadfsdfsdf </div>
<div class="selectEvent">
<input type="checkbox" class="seminar" id="179">
<label for="179"></label>
</div>
</div>
<input type="text" name="Requirement" placeholder="Title 01" id="divclass" required="required" class="pull-left" size="100" />
I'd suggest changing the id of the #divclass to something more descriptive, as the element is not a div, and it's an identifier, not a class.
Finally, your .seminar elements have the same id attribute which is invalid. You should ensure that the ids are unique within the DOM - assuming that this is not just a typo from copy/pasting the code in the question.

Javascript Add Row to HTML Table & Increment ID

This is my first post on this site so hopefully you will go easy on me. I'm trying to create an HTML / PHP form and use a small piece of Javascript to add additional rows to a table when a button is clicked and increment the ID for the two fields.
The button works in adding the rows however it doesn't seem to increment the ID, just use the same ID as the previous row. Hopefully someone could help?
$(window).load(function(){
var table = $('#productanddates')[0];
var newIDSuffix = 2;
$(table).delegate('#button2', 'click', function () {
var thisRow = $(this).closest('tr')[0];
var cloned = $(thisRow).clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
id = id.substring(0, id.length - 1) + newIDSuffix;
$(this).attr('id', id);
});
cloned.insertAfter(thisRow).find('input:date').val('');
newIDSuffix++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blue-bar ta-l">
<div class="container">
<h1>Submit Your Insurance Renewal Date(s)</h1>
</div>
</div>
<div class="grey-bar">
<div class="container">
<div class="rounded-box">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" autocomplete="off" required />
</div>
<div>
<label for="name">Renewal Dates</label>
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="5" id="productanddates" class="border">
<tr>
<td>
<select name="insurance_type1" id="insurance_type1">
<option></option>
<option>Car</option>
<option>Home</option>
<option>Van</option>
<option>Business</option>
<option>GAP</option>
<option>Travel</option>
</select>
</td>
<td>
<input type="date" name="renewal_date1" id="renewal_date1" />
</td>
<td>
<input type="button" name="button2" id="button2" value="+" />
</td>
</tr>
</table>
<div>
<label for="telephone_number">Contact Number</label>
<input type="tel" id="telephone_number" name="telephone_number" pattern="\d{11}" autocomplete="off" required />
</div>
<div>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" autocomplete="off" required />
</div>
<div>
<input name="submit" type="submit" value="Submit" class="btn">
</div>
</div>
cloned.insertAfter(thisRow).find('input:date').val('');
This line isn't correct. It will throw an invalid selector error.
You need to change it to:
cloned.insertAfter(thisRow).find('input[type="date"]').val('');
jQuery actually does support the :INPUT-TYPE format in selectors, but not the new HTML5 input types (yet): so using input[type="date"] here is the correct way for now to select an element with an HTML5 type. Please notice the quotes around the value. If you want to select an attribute with a certain value.
A selector overview of css selectors here: W3schools.
Because this line is throwing an error your newIDSuffix never gets updated, because the script halts at the line before that because of the script error.
#Charlietfl raises a valid point about learning more about classes and DOM traversal. However that will not fix this code. Or explain why your code isn't working. Nevertheless it's a good tip.
I've gone ahead an taken a stab at a cleaner version of what I think that you are trying to accomplish. I'll walk through the major updates:
Updated the button id and name from "button2" to "button1" - I assumed that you would want to keep the indices in sync across the inputs in each row.
Changing $(window).load(function() { to $("document").ready(function() { - While either will work, the former will wait until all images have finished loading, while the latter while fire once the DOM has completed building. Unless you REALLY want the images to load first, I'd recommend $("document").ready(), for faster triggering of the code.
Removing the [0] references - the primary reason to use [0] after a jQuery selector collection is to reference the DOM version of the selected jQuery element, in order to us a "vanilla" JavaScript method on it. In all cases, you were re-rwapping the variables in $(...), which just converted the DOM element back into a jQuery object, so that extra step was not needed.
Changed the .delegate() method to .on() - as Howard Renollet noted, that is the correct method to use for modern versions of jQuery. Note that the "event" and "target" parameters have swapped places in on, from where they were in delegate.
Changed the event target from #button2 to :button - this will make sure that all of the buttons in the new rows will also allow you to add additional rows, not just the first one.
Switched the clone target from the clicked row to the last row in the table - this will help keep your row numbering consistant and in ascending order. The cloned row will always be the last one, regardless of which one was clicked, and the new row will always be placed at the end, after it.
Changed the indexing to use the last row's index as the base for the new row and use a regular expression to determine it - with the table being ordered now, you can always count on the last row to have the highest index. By using the regular expression /^(.+)(\d+)$/i, you can split up the index value into "everything before the index" and "the index (i.e., on or more numbers, at the end of the value)". Then, you simply increment the index by 1 and reattach it, for the new value. Using the regex approach also allows you to easily adapt, it there ever get to be more than 9 rows (i.e., double-digit indices).
Updated both the id and name attributes for each input - I assumed that you would want the id and name attributes to be the same for each individual element, based on the initial row, and, you were only updating the id in your code, which would have caused problems when sending the data.
Changed $("input:date") to $("input[type='date']) - as Mouser pointed out, this was really the core reason why your code was failing, initially. All of the other changes will help you avoid additional issues in the future or were simply "code quality"-related changes.
So . . . those were the major updates. :) Let me know if I misunderstood what you were trying to do or if you have any questions.
$("document").ready(function() {
$('#productanddates').on('click', ':button', function () {
var lastRow = $(this).closest('table').find("tr:last-child");
var cloned = lastRow.clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
var regIdMatch = /^(.+)(\d+)$/;
var aIdParts = id.match(regIdMatch);
var newId = aIdParts[1] + (parseInt(aIdParts[2], 10) + 1);
$(this).attr('id', newId);
$(this).attr('name', newId);
});
cloned.find("input[type='date']").val('');
cloned.insertAfter(lastRow);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blue-bar ta-l">
<div class="container">
<h1>Submit Your Insurance Renewal Date(s)</h1>
</div>
</div>
<div class="grey-bar">
<div class="container">
<div class="rounded-box">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" autocomplete="off" required />
</div>
<div>
<label for="name">Renewal Dates</label>
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="5" id="productanddates" class="border">
<tr>
<td>
<select name="insurance_type1" id="insurance_type1">
<option></option>
<option>Car</option>
<option>Home</option>
<option>Van</option>
<option>Business</option>
<option>GAP</option>
<option>Travel</option>
</select>
</td>
<td>
<input type="date" name="renewal_date1" id="renewal_date1" />
</td>
<td>
<input type="button" name="button1" id="button1" value="+" />
</td>
</tr>
</table>
<div>
<label for="telephone_number">Contact Number</label>
<input type="tel" id="telephone_number" name="telephone_number" pattern="\d{11}" autocomplete="off" required />
</div>
<div>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" autocomplete="off" required />
</div>
<div>
<input name="submit" type="submit" value="Submit" class="btn">
</div>
</div>
cloned.insertAfter(thisRow).find('input[type="date"]').val('');

POST DATA issues when adding new elements to the page

Hi all I have a form in which I dynamically add in a new row consisting of a text box and check button on button press. However I need some sort of way to know which checkbuttons were pressed in the post data and therefore need a value field consisting of an ID on each of the the check buttons, code is seen below:
<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);
});
can anyone suggest a good way to help me know in the post data which text field, links to which check button, and to know if it was pressed?
at the moment if you were to add 3 rows and check row 3 I have no way of identifying that row three was the button pressed - This is my issue
after you cloned it, change the name so you know about this input
also it's good to have a counter for naming:
like : 'somename[myInput' + counter + ']'
update:
var counter = 0;
var $template = $('.template');
$('input[type=button]').click(function() {
counter++;
$template.clone().attr('name' , 'somename[myInput' + counter + ']').insertAfter($template);
});
now you have array named:somename which you can have a loop over its content on your form handler.

Categories

Resources