Well,
I've been trying to figure this out for quite a while now with absolutely no luck.
Right now, I have an HTML form with jQuery that can dynamically add or remove a charge. This information is then put into a php array and stored into a database.
What I want, is to be able to pull that array from a database, count the entries, and place them into the correct number of input boxes on an HTML form. I would still like jQuery to be used here, as I would like users to be able to add or remove charges in this 'edit' stage.
If it's confusing, please ask questions.
jQuery v
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'name' + newNum)
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
$('input[name="name[]"]:last').val(null);
// enable the "remove" button
$('#btnDel').attr('disabled','');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
</script>
HTML v
<tr id="input1" style="margin-bottom:4px;" class="clonedInput">
<td><span style="color:#00CD00;">Charge:</span></td>
<td><input type="text" name="name[]" size="35"/></td>
</tr>
<tr>
<td><input type="button" id="btnAdd" value="Add Another Charge" /></td>
<td><input type="button" id="btnDel" value="Remove Charge" /></td>
</tr>
Also, if you seen any improvements I can use in my code, please do suggest. I am fairly new to using jQuery, and I am wanting to learn as much as I can.
While repopulating the products in jquery is possible, I would try to repopulate them using php within a tag. This is purely to simplify the development. Populating with jquery would require getting the elements in a json feed and based on that, you can possibly re-use the same code you have to re-populate but this time, with a value in the text box.
Related
I have a form where I need to dynamically add as many text fields as the user wants to. I want the text fields to be an array, for example:
<input type="text" name="room_text[]">
I've already built something I thought would work. It successfully adds more text boxes. I added two more text boxes with javascript dynamically, making the form look like this:
<input type="text" name="room_text[]">
<input type="text" name="room_text[]">
<input type="text" name="room_text[]">
BUT, when I posted it to the PHP file, it only gets the first value. The reason why I know this is a javascript problem is becuase it works fine if you have more than one text box on page load. Its just when you add more text boxes with javascript.
If this helps, this is the jquery function I use to add the boxes:
$('.add').live("click", function() {
var mu = $(this).parent('td').parent('tr');
var clone = $(this).parent('td').parent('tr').clone();
$(clone).children('td').children('.add').remove();
$(clone).children('td').children('.redtext').remove();
$(clone).children('td').children('.remove').css("display", "inline");
$(clone).css("display", "none");
$(mu).after(clone);
$(clone).show("fast");
});
I believe the problem resides in the .clone() function. Can you try a different method, say ...
$('.add').live("click", function() {
var mu = $(this).parent('td').parent('tr');
var clone = '<tr>' + $(this).parent('td').parent('tr').html() + '</tr>';
$(clone).children('td').children('.add').remove();
$(clone).children('td').children('.redtext').remove();
$(clone).children('td').children('.remove').css("display", "inline");
$(clone).css("display", "none");
$(mu).after(clone);
$(clone).show("fast");
});
UPDATED - Oops. In that version "clone" is a string, not an element, so the .children() functions aren't working ... here's a corrected version:
$('.add').live("click", function() {
var mu = $(this).parent('td').parent('tr');
var clone = $('<tr>' + $(mu).html() + '</tr>');
$(clone).children('td').children('.add').remove();
$(clone).children('td').children('.redtext').remove();
$(clone).children('td').children('.remove').css("display", "inline");
$(clone).hide();
$(mu).after(clone);
$(clone).show("fast");
});
Long time lurker, first time poster.
I have a page that can dynamically (with Javascript / jQuery) add key => value pair inputs to a form. These fields need to be returned to PHP as an array for processing, so the keys are all named "complete_fields[]" and the values are all named "complete_values[]". Now here is my problem. If I fill in some inputs then want to add another key => value pair, I can click on a button and the Javascript will work its magic. However, because the HTML "value=" part is not filled out, the inputs I have already filled out are erased by the Javascript. So my question is this: How can I dynamically set the HTML value of the input with JS, even though all the inputs are named the same? If this is not possible, how can I add to the end of a div without erasing all the rest of the HTML?
Here is the Javascript add input code:
function addCompleteField() {
var oldhtml = $("#complete_fields").html();
var newrow = '<tr><td><input type="text" name="complete_fields[]" > => <input type="text" name="complete_values[]" ></td></tr>';
$("#complete_fields").html(oldhtml+newrow);
}
Rather than mucking around with HTML, just clone the elements using jQuery's clone method:
function addCompleteField() {
var table = $('#complete_fields'),
lastRow = table.find('tr').last(),
newRow = lastRow.clone(true);
newRow.find('input').val(''); // blank the new row's input elements
newRow.appendTo(table);
}
I'm working on a form where when user clicks "add server" a div block is repeated. I managed to work that out. But if I have only one server block I want the attribute name="servername" and if there are more elements that attribute should be name="servername[]" on all blocks.
I tried and only thing that works is when clicked add server first and second block gets name="servername[]", but when I click one more time first block gets name="servername[][]".
$('#addserver').click(function() {
var num = $('.clone').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// Create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#server1').clone().attr('id', 'server' + newNum);
// Insert the new element after the last "duplicatable" input field
$('#server' + num).after(newElem);
// Add [] for PHP array
$('#server' + num + ' input', '#server' + newNum + ' input').attr('name', function() {
return this.name + '[]';
});
// Enable the "remove" button
$('#delserver').attr('disabled','');
// You can only add 5 elements
if (newNum == 5) $('#addserver').attr('disabled','disabled');
});
$('#delserver').click(function() {
var num = $('.clone').length; // how many "duplicatable" input fields we currently have
$('#server' + num).remove(); // remove the last element
// enable the "add" button
$('#addserver').attr('disabled','');
// If only one element remains
if (num-1 == 1) {
// Remove [] because it's not php array anymore
$('#server1 input').attr('name', function() {
s = this.name.substring(0, this.name.length - 2);
return s;
});
// Disable "remove" button
$('#delserver').attr('disabled','disabled');
}
});
$('#delserver').attr('disabled','disabled');
Here's html example:
<div class="clone" id="server1">
<input type="text" name="servername" size="40" />
</div>
I need [] because of php array, but if user is entering one server and there is [] in name it doesn't work.
I think that you should simply have name="servername[]" no matter what.
Since you can get it to work when servername contains more than one element, I don't see what stops you from having it work correctly with only one (or even none at all) element as well.
If you are not completely convinced, consider how much trouble you are having right now, trying to fight against what I suggest.
Add a check
if ($(this).attr('name').substr(-2) != '[]') {
return $(this).attr('name') + "[]";
}
I'm building a search form with several filter options on the results page.
It's a basic search form, results show in an friendly url such as: domain.com/resuts/country/age/type/
The filters are simply checkboxes which on click, should reload the page with a query string to identify what has been checked/unchecked. (there is no submit, preferably the update would rebuild the query string with every check box click).
So, for example, on click of some checkboxes we'd build a query string on the end,
eg:domain.com/resuts/england/20-29/female/?scene=hipster&status=single
Can anybody point me to a jquery resource or a code snippet which may assist in getting this done?
Many thanks,
Iain.
The jQuery.get function will automatically handle creating and building the query string when you pass a key-value pair:
http://docs.jquery.com/Ajax/jQuery.get
You can use this selector for checked checkboxes:
$('input:checkbox:checked')
If your html looks like
<input type="checkbox" name="scene" value="hipster" />
I guess you can use something like
var tmp = [];
$('input:checkbox:checked').each(function(){
tmp.push($(this).attr('name') + '=' + $(this).val());
});
var filters = tmp.join('&');
$('.checkbox_class').change(function () {
let filter = $('.checkbox_class');
let types = [];
$.each(filter, function( index, input ) {
if(input.checked)
{
types[index] = input.value;
}
});
let typeQueryString = decodeURIComponent($.param({type:types}));
console.log(typeQueryString);
});
Is this what your looking for? When you click the checkboxes it shows the selected values up top. when you submit the form it shows you the same value in an alert
<div id="buffer" style="height:2em; border:1px solid black; margin-bottom:1em"></div>
form action="#" method="get">
input type="checkbox" id="j" name="state" value="state">state
input type="checkbox" name="city" value="city">city
input type="checkbox" name="type" value="type">type
input type="submit" value="click me">
/form>
$().ready(function(){
//just a simple demo, you could filter the page by the value of the checkbox
$('form input:checkbox').bind('click',function(){
if($(this).attr('checked')==false){
//remove it from the query string
var pieces=$('#buffer').text().split('/');
var $this_val=$(this).val();
for(var i=0;i<pieces.length-1;i++){
//console.log($(this).val());
//console.log(pieces[i]);
if(pieces[i]==$this_val){
//remove value from the buffer
pieces.splice(i);
}
$('#buffer').text(pieces.join('/')+'/');
}
}else{
//add the value to the query string
$('#buffer').append($(this).val()+'/');
}
});
//on form submit
$('#filterWrapper form').submit(function(){
var queryString='';
$.each($('form input:checkbox:checked'),function(){
queryString+=$(this).val()+'/';
});
alert('this will get send over: '+queryString);
return false;//remove this in production
});
Sorry about the broken HTML, the editor doesnt like form tags and input tags
I'm generating an html file which looks like:
<tr id="ID001" property1="PROPERTY001"><td><input type="checkbox"
name="row_checkbox_ID001"></td><td>...</td><td>...</td></tr>
<tr id="ID002" property1="PROPERTY002"><td><input type="checkbox"
name="row_checkbox_ID002"></td><td>...</td><td>...</td></tr>
When the user selects individual rows for deletion, how can I (through jQuery), pass this to a php script?
I will need to build something like this:
$(document).ready(function () {
$('#contact-form input.contact-delete').click(function (e) {
e.preventDefault();
$.get("deleterecord.php", ...);
});
});
There can be 0, 1 or multiple rows... The HTML being generated is under my control and can be modified.
Clarification:
I want to have a button above all these rows which the user can click on AFTER he has selected the rows from the table.
<div id='contact-form'><h2>Contacts</h2>
<input type='button' name='contact-delete' value='Delete Record(s)'
class='contact-delete'/>
The TRs need to be deleted, but BEFORE that, the deleterecord.php script needs to be called with the TR ids.
Use HTML arrays
<input type="checkbox" name="chk[]" value="01234">
<input type="checkbox" name="chk[]" value="98765">
You could create a JSON object containing details of any rows selected (ID's or whatever you need) and send that to your php script. Check out this article on json, php + jquery.
I believe, you are looking for similar behavior:
$('#contact-form input.contact-delete').click(function (e) {
var $this = $(this);
// find the table row, in which are elements contained
var $tr = $this.closest('tr');
// take id
var id = $tr.attr('id');
// ajax with id
$.get("deleterecord.php?id="+id, function (data) {
// remove table row on success
$tr.remove();
});
e.preventDefault();
});
Sorry for answering my own question, but the SO post at: Getting all selected checkboxes in an array neatly solves my problem!
For future visitors to this page, pay attention to variable names in your HTML and how you're accessing the input checkboxes in jQuery!