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.
Related
I need help with this. I need to make the value in the other place change all the time while user session is active. How can I get the value from a span and make other value in a data change?
Look at there!
1 <div class="pt-uea-container">
2 <span class="pt-uea-currency pt-uea-currency-before"> € </span>
3 <input type="text" class="pt-field pt-uea-custom-amount" autocomplete="off" name="pt_items[1][amount]" id="pt_uea_custom_amount_1" value="199" placeholder="" data-parsley-errors-container="#pt_uea_custom_amount_errors_1">
4 <input type="hidden" class="pt-field pt-uea-custom-amount-formatted" name="pt_items[1][amount]" value="199" data-pt-price="199">
5 <input type="hidden" name="pt_items[1][label]" value="Amount:">
6 <input type="hidden" name="pt_items[1][tax_percentage]" value="0">
7 <input type="hidden" name="pt_items[1][type]" value="open">
8 <div id="pt_uea_custom_amount_errors_1"></div>
9 <span class="form-price-value">85</span>
10 </div>
The value in row 9 needs to constantly change values in row 3 and 4 on the same session. Don't mind the value in row 6.
Let me know how I can get this done. Or maybe a different approach?
Greetings!
========
So this is what I got for now from you guys:
jQuery(document).ready(function($) {
var checkViewport = setInterval(function() {
var spanVal = $('.form-price-value').text();
$('#pt_uea_custom_amount_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').attr('data-pt-price', spanVal);
}, 1000);
});
This code works, but it only affects my needs when I put my mouse in pt-field pt-uea-custom-amount and add a space in it. Then it does apply to the page source. But this is not correct. The source needs to get changed too without touching that class or a space or something!
You can easily do this with the help of jQuery.
With the help of jQuery I would do like this.
Understanding what input field needs to be tracked for changes. I will give all this field a class (track-me).
In the document ready, I will look for changes for that tracked field.
On change of that field I will get the value and put in other input fields (class copy-to - or you can do whatever you like).
See an example below,
HTML
<form>
<div class="">
<input type="text" class="track-me" value=""/>
</div>
<div class="">
<input type="text" class="copy-to" value=""/>
</div>
<div class="">
<input type="text" class="copy-to" value=""/>
</div>
<div class="">
<input type="text" class="copy-to" value=""/>
</div>
<div class="">
<div class="">Please type anything in the first input box</div>
</div>
</form>
jQuery
$(document).ready(function(){
$('.track-me').change(function (){
$('.copy-to').val($(this).val())
});
});
I made comments in the above jQuery code so you can understand. Also, I have made a fiddle so you can play and have a look. In this fiddle, I am using Bootstrap4 just for the purpose of styling, you don't have to worry about that.
Link to fiddle
https://jsfiddle.net/anjanasilva/r21u4fmh/21/
I hope this helps. Feel free to ask me any questions if you have. Cheers.
This is not an ideal solution. I'm not sure there is a verified way of listening for when the innerHTML of a span element changes. This sort of stuff is usually based on user interaction, and the value of the span will be modified by your page. The best solution would be to use the same method that updates the span element to update the values of you hidden input fields.
However, I've placed an interval that will run every second, that takes the text value of the span element and gives it to the values of the 2 input fields:
function start() {
setInterval(function() {
document.getElementById("pt_uea_custom_amount_1").value = document.getElementById("price_value").innerHTML;
document.getElementById("pt_uea_custom_amount_2").value = document.getElementById("price_value").innerHTML;
}, 1000);
}
window.onload = start();
<div class="pt-uea-container">
<span class="pt-uea-currency pt-uea-currency-before"> € </span>
<input type="text" class="pt-field pt-uea-custom-amount" autocomplete="off" name="pt_items[1][amount]" id="pt_uea_custom_amount_1" value="199" placeholder="" data-parsley-errors-container="#pt_uea_custom_amount_errors_1">
<input type="hidden" class="pt-field pt-uea-custom-amount-formatted" name="pt_items[1][amount]" value="199" data-pt-price="199" id="pt_uea_custom_amount_2">
<input type="hidden" name="pt_items[1][label]" value="Amount:">
<input type="hidden" name="pt_items[1][tax_percentage]" value="0">
<input type="hidden" name="pt_items[1][type]" value="open">
<div id="pt_uea_custom_amount_errors_1"></div>
<span id="price_value" class="form-price-value">85</span>
</div>
MutationObserver should work here..
const formValuePrice = document.querySelector( '.form-price-value' );
const inputText = document.querySelector( 'input[type="text"]' );
// timer to change values
window.setInterval( () => {
formValuePrice.textContent = Math.round( Math.random() * 100 );
}, 1000 );
// mutation observer
const observer = new MutationObserver( ( mutationsList ) => {
inputText.value = formValuePrice.textContent;
} );
observer.observe( formValuePrice, { childList: true } );
https://codepen.io/anon/pen/LgWXrz?editors=1111
try this, simple using jquery, you can check in inspect element for value attribute data-pt-price
Update: you can using jquery event .on() like change, click, keyup or else to Attach an event handler function for one or more events to the selected elements,
you can read the doc here.
here the updated code
$(function() {
var spanVal = $('#price_value').text();
$('#pt_uea_custom_amount_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').attr('data-pt-price', spanVal);
$('#pt_uea_custom_amount_1').on('change click keyup', function() {
$('#pt_uea_custom_amount_formatted_1').val($(this).val());
$('#price_value').text($(this).val());
$('#pt_uea_custom_amount_formatted_1').attr('data-pt-price', $(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pt-uea-container">
<span class="pt-uea-currency pt-uea-currency-before"> € </span>
<input type="text" class="pt-field pt-uea-custom-amount" autocomplete="off" name="pt_items[1][amount]" id="pt_uea_custom_amount_1" value="199" placeholder="" data-parsley-errors-container="#pt_uea_custom_amount_errors_1">
<input type="hidden" class="pt-field pt-uea-custom-amount-formatted" name="pt_items[1][amount]" value="199" data-pt-price="199" id="pt_uea_custom_amount_2">
<input type="hidden" name="pt_items[1][label]" value="Amount:">
<input type="hidden" name="pt_items[1][tax_percentage]" value="0">
<input type="hidden" name="pt_items[1][type]" value="open">
<div id="pt_uea_custom_amount_errors_1"></div>
<span id="price_value" class="form-price-value">85</span>
</div>
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".
I'm trying to add the rows dynamically plus auto-increment of a counter.I want to start with 1 then 2 then 3 and so on . I have added my code on plunker ,in which every time the max value is getting in first column like 4 then 1,1,2,3.Where am i going wrong ?i Want it to be 1,2,3,4.
Here is the plunker link http://plnkr.co/edit/GuDbJ3SHOPvWkHfNfd8E?p=preview
var _counter = 0;
function Add() {
_counter++;
var oClone = document.getElementById("template").cloneNode(true);
oClone.id += (_counter + "");
document.getElementById("placeholder1").appendChild(oClone);
document.getElementById("myVal").value=_counter;
}
<div id="placeholder1">
<div id="template">
<div>
Value:<input type="text" id="myVal" placeholder="1">
Quantity:<input type="text" placeholder="Qty">
<input type="button" onClick="Add()" value="Click! ">
</div>
</div>
I think it is because you have multiple divs with the id="myVal". The id attribute should be unique on the page. If not, your page will still load, but you may have unexpected behavior.
You are changing the id of the template div, but not the myVal div.
I assume you are looking for something like this:
var _counter = 0;
function Add() {
_counter++;
var oClone = document.getElementById("template").cloneNode(true);
oClone.id += (_counter + "");
document.getElementById("placeholder1").appendChild(oClone);
oClone.getElementsByClassName("myVal")[0].value = _counter;
}
<div id="placeholder1">
<div id="template">
<div>
Value:
<input type="text" class="myVal" placeholder="1">Quantity:
<input type="text" placeholder="Qty">
<input type="button" onClick="Add()" value="Click! ">
</div>
</div>
</div>
In your original you are cloning your template with the same id for the input. So when you do document.getElementById("myVal").value=_counter;, you only get the first input. I changed it to use class instead and get the input with the appropriate class that is a child of the cloned node.
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++;
});
Code below contains certain tags in all four.
Image-1
here is the code :
<div style='background-color:YellowGreen;height:20px;width:100%;margin-top:15px;font-weight: bold;'>
Delegate(s) details: </div>
<div style="border:1px solid black;"><br/>
<div id="delegates">
<div id="0">
Name of the Delegate:
<input name='contact_person[]' type='text' size="50" maxlength="50" />
Designation:
<select name='delegate_type_name[]' class='delegate_type'>
<option value='select'>Select</option>
<option value='Main'>Main</option>
</select>
</div><br/>
</div>
<div>
<input type="button" name="more" value="Add More Delegates" id="add_more" />
<br />
<br />
</div>
</div>
In the above code on line 5 where <div id="0"> changes to value 1 in script that I mentioned in "add_more"
And the javascript for "add_more" is given below
jQuery('#add_more').click(function(){
var id = jQuery('#delegates > div:last').attr('id');
var temp = "<div id='"+(parseInt(id)+parseInt('1'))+"'> Name of the Delegate: <input type='text' size='50' maxlength='50' name='contact_person[]' /> Designation:";
temp += "<select name='delegate_type_name[]' class='delegate_type additional_delegate'><option value='select'>Select</option><option value='Additional'>Additional</option><option value='Spouse'>Spouse</option></select> <input type='button' name='rem' value='Remove' id='remove' /></div><br/>";
jQuery('#delegates').append(temp);
});
In the javascript code above I have added a remove button in the temp+ variable
<input type='button' name='rem' value='Remove' id='remove' />
Image-2 shows the remove button every time I click on "Add more Delegates" button.
In the image-2 I click on Add More Delegates button it shows the "remove" button on the right of drop down select list.
I want a jQuery function for remove button, so that when I click on remove it should remove <div id="1"> and also reset content before removing the div tag. Below image-3 is the output that I want when I click on remove button.
code that I tried was this from some reference is this
jQuery('#remove').click(function(){
var id = jQuery('#delegates > div:last').attr('id').remove();
});
but no luck.
Thanks.
You can't give an element id that is only a number, it must be #mydiv1, #mydiv2 or something similar, i.e. beginning with a letter not a number.
For starters your markup is a total mess. There is no way you should be using for layout purposes. Read up on tableless layouts and css.
The first thing you need to change is the id's of your div. An id cannot start with a numeric. I suggest naming the first div delegate0. Secondly, you are adding a remove button on every new row with the same id - all id's on a page should be unique so i suggest you change this to class="remove".
As for your question, it really boils down to needing to add a jQuery handler to the remove buttons using the .livedocs method.
This is as simple as:
jQuery('.remove').live('click',function(){
$(this).closest('div').remove();
});
Also, you need to keep a running counter of the id of the items added, and increment this every time a new row is added.
var nextDelegate = 1;
jQuery('#add_more').click(function(){
... your code here
nextDelegate++;
});
Also, I removed the superfluous <br/> after each div.
Live example: http://jsfiddle.net/cb4xQ/