I'm using jQuery clone and children concepts for my project. I'm using one table within div (class is clonedInput), by clicking one button I'm cloning the whole div and inserting it after the div. In this time:
"
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
$('#input' + num).after(newElem);
"
by using this I'm increasing the div id. At the same time I want to increase the table tr and td's id. For that I tried children.attr(). But this is not increasing the table ids. Can anyone clarify this for me?
Thanks in advance.
I have a function which creates inputs in a row with incremented ids. This is not the thing you are looking for but i am sure it will give you a fairly good idea to how to do the task.
var numbers =0
$(function() {
var newRowNum = 0;
$('#addnew').click(function() {
newRowNum++;
///////////// <a> <td> <tr>
var addRow = $(this).parent().parent();
///////////// In the line below <tr> is created
var newRow = addRow.clone();
$('input', addRow).val('');
$('td:first-child', newRow).html();
$('td:last-child', newRow).html('<a href="" class="remove">Remove<\/a>');
$('input', newRow).each(function(i) {
var newID = newRowNum + '_' + i;
$(this).attr('id', newID).attr('name', newID);
});
addRow.before(newRow);
$('a.remove', newRow).click(function() {
$(this).parent().parent().remove();
return false;
});
return false;
});
numbers = newRowNum;
});
It is not clear what are you trying to do, but my guess is that you can try:
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone();
newElem.attr('id', 'input' + newNum);
$('#input' + num).after(newElem);
the whole
$('#input' + num).clone().attr('id', 'input' + newNum);
part may not be giving you clone object but rather boolean result or some integer.
If the problem is not resolved you may try append() function also.
Related
I'm pretty new to web programming so, making a logic for a web-page, I made a mistake and now I'm in trouble.
I named some divs like "Dv_1.2.1.3" (without knowing the problems linked to using the dot) and I have issues trying to clone (via jquery called by button) some of these.
The button id contains the id of the div I want to clone, so, my logic is:
1) extract the id of the div;
2) get the div and clone it (giving a new id).
I'm stuck with getting the div because of the dots in the id.
The below code is what I've done so far:
$('.CloneDiv').click(function () {
var SplittedId = (this.id).split('_');
if (SplittedId[0]=='Clone'){
alert('SplittedId 1 =' + SplittedId[1]);
//Modify id to use it to find the div to clone
var UsableId = SplittedId[1].replace(/\./g, '\\\\.');
alert('UsableId =' + UsableId);
//Count existing elements
var ClonedNum = $('#' + 'Dv_' + UsableId + '_').length;
ClonedNum++;
var OrigElem = $('#' + 'Dv_' + UsableId).length;
alert('OrigElem =' + OrigElem); //THIS IS 0
//NO ELEMENTS FOUND BUT THE ELEMENT EXISTS
//Clone the element and give new id
var ClonedElem = $('#' + 'Dv_' + UsableId).clone().attr('id', function( i, val ) {
return val + '_' + ClonedNum;
});
ClonedElem.find("input").val("");
if (ClonedNum > 1){
ClonedNum--;
var AnteId = '#' + 'Dv_' + UsableId + '_' + ClonedNum;
alert(AnteId);
$(AnteId).after(ClonedElem);
}else{
var AnteId = '#' + 'Dv_' + UsableId;
alert('AnteId = ' + AnteId);
$(AnteId).after(ClonedElem);
};
}else if(SplittedId[0]=='Del'){
alert(SplittedId[0]);
alert('Del');
}else{
//error
};
});
Might these help: developer.mozilla.org/en-US/docs/Web/API/CSS/escape , Polyfill: github.com/mathiasbynens/CSS.escape/blob/master/css.escape.js
I am working on ecommerce website.
My table gets value from session.
It looks like :
On Checkout I want to get all the values of table.
I have used jquery for this.
Here is my code:
<script>
$('#chhk').on('click',function(e) {
e.preventDefault();
alert('click');
var table = $("#tbl tbody");
table.find('tr').each(function (i, el) {
var $tds = $(this).find('td'),
product = $tds.eq(2).text(),
price = $tds.eq(3).text(),
quantity = $tds.eq(4).attr('value'),
total = $tds.eq(5).text();
alert('Row ' + (i + 1) + ':\nProduct: ' + product
+ '\nPrice: ' + price
+ '\nQuantity: ' + quantity
+ '\nTotal: ' + total);
});
});
</script>
Here
'#chhk' is checkout button id
'#tbl' is my table id
I am getting blank value of quantity by this script as it is input field
Any help would be appreciated..
Try replace this:
quantity = $tds.eq(4).attr('value');
with:
quantity = $tds.eq(4).val();
As .attr('value') gives the value at the start, while .val() gives current property.
More info:
jQuery .val() vs .attr("value")
replace this:
quantity = $tds.eq(4).attr('value'),
with
quantity = $tds.eq(4).find("input").val(),
well I tried to do it separately and am getting expected result.
$('#chhk').on('click',function(e) {
e.preventDefault();
alert('click');
var table = $("#tbl tbody");
table.find('tr').each(function (i, el) {
var $tds = $(this).find('td'),
product = $tds.eq(2).text(),
price = $tds.eq(3).text(),
total = $tds.eq(5).text();
var qty = $(this).find('td input:first').val();
alert('Row ' + (i + 1) + ':\nProduct: ' + product
+ '\nPrice: ' + price
+ '\nTotal: ' + total
+'\n Qua:' + qty);
});
});
Have dealed quantity separately.
Could do with some help I have a simple ajax powered stickies app (with jquery UI and PHP) in development, my code below stores X, Y for dragged items posts it to a database and loops results back to a div. I have successfully built code for a text version (akin to post it notes) but I am trying to do a draggable/scalable version to hold images. But when I do this my positions are being stored in the database looped out into a #projbaord div but not being used to correctly position the HTML elements (i have checked the page source and the style: is showing correct x, y but this is not reflected on screen).
I think the problem must be in the loop out of the PHP and style of the position x, y but cannot seem to fathom it out! Any ideas or another way of achieving same result?
I thought this maybe a position:relative/absolute problem but that seems to be okay - I am stumped at present! Hope you can genius can help!
Javascript to handle behaviour and store values in database:
function imageStickyDragXYUpdate(){
$(".imagesticky").each(function(index){
var resizethese = $(this).children();
$(this).draggable({
cursor: 'move',
stack: '.imagesticky',
opacity: '0.5',
containment: '#projboard',
scrollspeed: '40',
scrollSensitivity: '10',
stop:function(){
var coord=$(this).position();
var coordLeft = coord.left;
var coordTop = coord.top;
var imageStickyid = $(this).attr('imagestickyid');
//alert('x='+ coordTop + 'y=' + coordLeft + 'id=' +imageStickyid);
var datastring = 'xupdateimg='+ coordTop + '&y=' + coordLeft + '&imgstickyid=' +imageStickyid + '&projid=' + proj_id + '&uid=' + uid;
//alert(datastring);
$.ajax({
type: "POST",
url: "uploaddata.php",
data: datastring,
success: function(data){
$("#projboardresults").html(data);
textStickyDragXYUpdate();//not important other function for working text stickies
imageStickyDragXYUpdate();
}
});
}
});
});
}
PHP to show results
<?php
$user_id= $_POST['uid'];
$proj_id=$_POST['projid'];//to be validated as int
$get_imgsticky_query = "SELECT * FROM imagesticky WHERE user_id = $user_id AND project_id=$proj_id";
$get_imgsticky_result=mysql_query($get_imgsticky_query);
while($row=mysql_fetch_assoc($get_imgsticky_result)){
$x = $row['imagesticky_x'];
$y = $row['imagesticky_y'];
$imagesticky_w = $row['imagesticky_w'];
$imagesticky_h = $row['imagesticky_h'];
$imagesticky_url = $row['imagesticky_url'];
$imagesticky_id = $row['imagesticky_id'];
echo '<div class="imagesticky" imagestickyid="'.$imagesticky_id.'" style="position: absolute; left:'.$x.'px; top:'.$y.'px;">
<a class = "clickaddimage" href="addimage.php"><img src="images/clicktoadd.png" alt="add image" title="Click to add image"</a>
<img src="'.$imagesticky_url.'" width="'.$imagesticky_w.'" height="'.$imagesticky_h.'"/>
<img src="images/closey.png" title="delete" alt="delete"/>
</div>';
}
?>
var datastring = 'xupdateimg='+ coordTop + '&y=' + coordLeft + '&imgstickyid=' +imageStickyid + '&projid=' + proj_id + '&uid=' + uid;
This line was the problem, I had the X variable storing the Y value and the Y coordinate storing the X variable! So my code appeared to be placing items in the wrong place, but was actually working perfectly. That is what you get for being a new father and trying to code! Why did I could not spot this yesterday? LOL!
I'm cloning input fields on a table that have an autocomplete class. When I clone the fields I have no problem. The problem is that in the cloned fields, the autocomplete doesnt work (on the one that is not cloned it does work). My autocomplete code is this:
$(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().prop('id', 'input' + newNum);
newElem.find(':input').each(function() {
var name = $(this).attr('name').replace(/\d+$/, '');
$(this).prop({id: name + newNum, name: name + newNum}).val("");
});
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').prop('disabled','');
// business rule: you can only add 15 names
if (newNum == 15)
$('#btnAdd').prop('disabled','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').prop('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').prop('disabled','disabled');
});
$('#btnDel').prop('disabled','disabled');
});
My Autocomplete code is :
var autoc = {
source: "lib/search.php",
minLength: 1,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
};
var renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a style='height:75px; text-align:center; font-weight:bold;'>"+ item.label + "</a>" )
.appendTo( ul );
};
$(".member").each(function (i) {
$(this).autocomplete(autoc).data("autocomplete")._renderItem = renderItem;
});
I've been trying to fix it by putting the autocomplete code inside of the clone code, Im not sure what Im doing wrong. It would be great if somebody could help! Thanks!
You have to reinitialize the autocomplete field after it's been cloned. And I think wrapping it within .live() is necessary as well
My solution to this was something like this:
$('#my_clone_button').live('click',function() {
my_clone_script; #this is my function to clone
$('select your new cloned input').each(function() {
$(this).autocomplete('destroy');
enable_autocomplete($(this), json_url); #this is my function to initialize autocomplete
});
});
try $('#input' + num).clone(true) passing true tells the clone to copy the events and data also. This means that it will copy that the input is a autocomplete field.
I have a table which I can dynamically add and delete any number of rows to. Once the data is all entered by the user I am using the jQuery AJAX functionality to POST it to a mysql database so there is no page redirect or refresh.
The only way I could think of getting it to work was using this for loop in my jQuery, effectively posting each row to the database separately. How dumb is this? Should I be getting all the table data and posting it once? There could be any number of rows varying on user and the user could add and delete rows as much as he wants before submitting.
The strange i variable counting is due to there being two th rows at the top of the table. I couldn't work out a smart way of doing this.
I was a bit paranoid about the data always being associated with the correct row.
Thankyou for your time.
jQuery(function() {
jQuery(".button1").click(function() {
// process form here
var rowCount = jQuery('#dataTable tr').length;
for (var i = 2; i < rowCount; i++){
// the four elements of each row I am storing to the mysql
var txtRow1 = jQuery('#txtRow' + (i-1)).val();
var tickerRow1 = jQuery('#tickerRow' + (i-1)).val();
var quantRow1 = jQuery('#quantRow' + (i-1)).val();
var valueRow1 = jQuery('#valueRow' + (i-1)).val();
var dataString = 'txtRow1='+ txtRow1 + '&tickerRow1=' + tickerRow1 + '&quantRow1=' + quantRow1 + '&valueRow1=' + valueRow1;
//alert (dataString);return false;
jQuery.ajax({
type: "POST",
url: "http://rccl.co.uk/form_action1.php",
data: dataString
});
};
return false;
});
});
It looks very clearly to me as if you have a well-established index of the row in question, using your variable i. Most form handlers server-side will unpack repeated keys of the form into a list, for stuff like many checkboxes with the same name. You could exploit that here.
datastring = '';
for(var i=2; i<rowCount; i++) {
var txtRow1 = jQuery('#txtRow' + (i-1)).val();
var tickerRow1 = jQuery('#tickerRow' + (i-1)).val();
var quantRow1 = jQuery('#quantRow' + (i-1)).val();
var valueRow1 = jQuery('#valueRow' + (i-1)).val();
dataString = datastring + 'index[]=' + (i-1) + 'txtRow1[]='+ txtRow1 + '&tickerRow1[]=' + tickerRow1 + '&quantRow1[]=' + quantRow1 + '&valueRow1[]=' + valueRow1;
}
Then make the ajax call with the whole string.
On the server-side, you should get arrays for each of these, the first of each of which corresponds to the first row, the second of each of which corresponds to the second row, and so on.
It's been a long time since I used PHP, but I believe the [] symbols for each key item are necessary to clue PHP's $_POST that it should convert the various keys' contents into arrays.
I would try posting it all at once.
Reasons
fewer calls, less chance of your message getting lost in transit (your server rejecting requests because of flood)
you don't have to worry about requests responding out of order (maybe not an issue, but having an ass load of jumbled responses could potentially be an issue)
it will be faster for large numbers of rows getting saved at once