I have a table that creates rows when you press the Add Order Item It runs a function that appends this:
function Add() {
$('#table-order').append(
"<tr>" +
"<td><input type='text' class='order-qty'/></td>" +
"<td><input type='text' class='order-desc'/></td>" +
"<td><input type='text' class='order-options'/></td>" +
"<td><input type='text' class='order-price'/></td>" +
"<td><span class='btn-save'>Save</span>|<span class='btn-delete'>Delete</span></td>" +
"</tr>"
);
$(".btn-save").bind("click", Save);
$(".btn-delete").bind("click", Delete);
}
I am looking at some way to get all the input values (excluding the last TD cell).
The idea is: get all the values in an object or an array, split each line as the order willl have multiple rows.
Pass the object as a $_POST to php to then send to mongoDB
You can iterate through inputs and post collected values when click save button like;
var params = [];
$("input").each(function() {
params.push($(this).attr("class") + "=" + $(this).val())
});
$.ajax({
url:"your url",
method: "POST",
data: params.join("&"),
success: function(response) {
//handle response
}
});
You can see sample demo here: http://jsfiddle.net/9pFq4/
Related
I have a table that will display images stored in a DB as well as some other information. I have a column that has a link that the user can click to delete the image, this works fine however when the user does this I also want to remove the row that the user selects to remove but I can't seem to get it to work.
function removeSectionPhoto(image, section_id) {
if(confirm("Are you sure you want to delete this image?") == true) {
$.ajax({
type: "POST",
url: "remove_section_photo.php",
data: 'image='+image+'§ionID='+section_id,
success: function(data){
//this is supposed to remove the row but currently doesnt work
$("#"+$(this).data("remove-row")).remove();
}
});
}
}
The table rows are being output from PHP, this is what one of the table rows looks like:
echo "<tr id='fac_sec_photo_row". $imageRowCount ."'>";
echo "<td><a><img class='section_photo' src='" . $sectionPhotoRow['photo'] . "' alt='Section Photos' height='50' width='50'</a></td>";
echo "<td><input type='text' id='photoDesc' name='photoDesc[]' value='" . $sectionPhotoRow['photo_desc'] . "'</td>";
echo "<td><input type='file' id='new_section_photo' name='new_section_photo[]' onchange='displaySecImage(this)'></td>";
echo "<td><a href='#' class='removeImageRow' data-remove-row='fac_sec_photo_row". $imageRowCount . "' onClick='removeSectionPhoto(\"". $sectionPhotoRow['photo'] ."\", \"". $facilitySecId ."\")'>Remove</a></td>";
echo "</tr>";
What am I doing wrong, how can I remove the selected table row?
All right. I see part of the issue. You are mixing vanilla javascript with jquery. Jquery does a LOT behind the scenes that hides what javascript doesn't do. Since you are using a vanilla onclick inline on the element, this will likely refer to window, not the element that is being clicked on (I know, confusing). Jquery uses the function.prototype.apply method to re-map this to the target element. Javascript doesn't. But all is not lost, and there is an easy fix. The easiest of which is to just pass in $imageRowCount to your function as well. Then you can simply reference the id directly.
function removeSectionPhoto(image, section_id, row_id) {
if(confirm("Are you sure you want to delete this image?") == true) {
$.ajax({
type: "POST",
url: "remove_section_photo.php",
data: 'image='+image+'§ionID='+section_id,
success: function(data){
//this is supposed to remove the row but currently doesnt work
$("#"+row_id).remove();
}
});
}
}
And then:
echo "<td><a href='#' class='removeImageRow' onClick='removeSectionPhoto(\"{$sectionPhotoRow['photo']}\", \"{$facilitySecId}\", \"fac_sec_photo_row{$imageRowCount}\")'>Remove</a></td>";
Another option would be to pass in this to the function call in the onclick='removeSectionPhoto(this, ...etc...)' which would give your first argument (or whatever argument number you pass it in) a reference to that variable. Then $(ele).closest('tr').remove() would work.
Really though, you shouldn't mix vanilla js with jquery. Just use jquery to query for the elements and use it's event handlers and this wouldn't have been an issue (well, you still need to map this to self).
pass the $imageRowCount as a third argument into the function and then remove the row that way
echo "<td><a href='#' class='removeImageRow' data-remove-row='fac_sec_photo_row". $imageRowCount . "' onClick='removeSectionPhoto(\"". $sectionPhotoRow['photo'] ."\", \"". $facilitySecId ."\", \"". $imageRowCount ."\")'>Remove</a></td>";
function removeSectionPhoto(image, section_id,imageRowCount ) {
if(confirm("Are you sure you want to delete this image?") == true) {
$.ajax({
type: "POST",
url: "remove_section_photo.php",
data: 'image='+image+'§ionID='+section_id,
success: function(data){
//this is supposed to remove the row but currently doesnt work
$("#fac_sec_photo_row"+imageRowCount).remove();
}
});
}
}
What i'm trying to do here to populate second select from based from the first one with json format.
Everything goes okay i'm getting the results i need with exact num of rows from the model based on the ID which i send with the request but i have this error :
I'm trying to get the mark id based on the model selected which i have in database :
ID MARK_ID VALUE_MARK
Here is my jquery function :
$(document).ready(function(){
$("#mark").change(function() {
var markId= $("#mark").val();
if (markId!= "") {
$.get(
'upload/car_models?mark_id=' + markId,
function(data){
$.each(data, function(key, value){
$("#model").append("<option value='" + key + "'>" + value + "</option>");
})
},
"json"
);
}
});
})
And in my controller i'm doing json encode like this for the variable which is back from the model
echo json_encode($models);
How can i fix this problem with object Object.
Thanks. Any help will be appreciate.
EDIT :
Json structure :
[{"id":"50","mark_id":"50","value_mark":"Refine","value":"JAC"}, {"id":"50","mark_id":"50","value_mark":"Rein","value":"JAC"}]
Here is my json structure. id mark_id value_mark here have 2 rows returned from the model
Your data is an array of objects. WHen you loop over that array with $.each key will be index, and value will be object at that index.
Try:
$.each(data, function(i, obj){
$("#model").append("<option value='" + obj.value + "'>" + obj.value_mark + "</option>");
});
I guessed at what properties you want to assign to <option> value and text
Try this,
$(document).ready(function(){
$("#mark").change(function() {
var markId= $("#mark").val();
if (markId!= "") {
$.get(
'upload/car_models?mark_id=' + markId,
function(data){
var model=$("#model");
model.empty();
$.each(data, function(key, val){
model.append("<option value='" + val.value + "'>" + val.value_mark + "</option>");
});
},
"json"
);
}
});
})
I have the following script :
<script type="text/javascript" >
$('form').each(function() {
$(this).on('submit', function() {
var first_firstname = $(".first_firstname", this).val();
var first_lastname = $(".first_lastname", this).val();
var second_firstname = $(".second_firstname", this).val();
var second_lastname = $(".second_lastname", this).val();
var TeamName = $(".TeamName", this).val();
var dataString = 'first_firstname='+ first_firstname + '&first_lastname=' + first_lastname +
'&second_firstname=' + second_firstname + '&second_lastname=' + second_lastname + '&TeamName=' + TeamName;
$.ajax({
type: "POST",
url: "data.php",
data: dataString,
success: function(){
window.setTimeout(function(data)
{
$('#propspectDiv').html('Team Name Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
return false;
});
</script>
And the following php that generates a number of forms on a page using mysql database
<?php
echo '<table class="greensmalltbl" cellspacing="10px" cellpadding="5px"><div id="propspectDiv"></div>';
for ($i=1, $o=$totalEntrants; $i<=$half; $i++, $o=$o-1) {
$formid = $i;
echo "<div style='border:3px;'><form action='' method='post'>
<tr><td><input type='text' name='first_firstname' id='first_firstname' value='$firstName[$i]' />
<input type='text' name='first_lastname' id='first_lastname' value='$lastName[$i]' />
Skill Level : ".$skill[$i]."</td></tr>";
echo "<tr><td>WITH</td></tr>";
echo "<tr><td><input type='text' name='second_firstname' id='second_firstname' value='$firstName[$o]' />
<input type='text' name='second_lastname' id='second_lastname' value='$lastName[$o]' /> Skill Level ".$skill[$o]."</td></tr>";
echo "<tr><td>Enter Team Name : <input type='text' name='TeamName' id='TeamName' value='' />
<input type='submit' name='submit' value='Submit'></form></td></tr>";
}
echo '</table>';
?>
I want to update the db table with the TEAM NAME in each form
The problem is only the first forms input is passed all other forms do nothing
I have tried a number of variations to the ajax code but none have worked.
Can anyone find the problem here
This line will not return the form.
var parent = $(this).parent('form');
because your submit button is wrapped inside tr and td tags. Either get rid of those tags (they are invallid anyway, because your are not using them in a table), or update your code to:
var parent = $(this).closest('form');
closest() searches its way up to all the ancestors of an element, and will return the first match of the selector.
Check out the documentation here: http://api.jquery.com/closest/
Or, if you only have a single form in your page, you could just go:
var parent = $('form');
:: EDIT ::
OK. Forget all of the above. Seems like you are not even using the parent variable later in the code.
A more important problem is that even though you are catching the Click event on the form submit button, what you probably really want to do is catch the submit-event of the form.
So change your first line of code to this:
$('form').on('submit', function() {
Also, in your HTML, your code is invalid.
<form action'' method='post' id='$formid'>
action'' should be action = ''
Chances are this doesn't really fix your problem, because there might be more errors. Next time, try to validate your code before posting a question.
:: EDIT ::
Last edit, I promise. I quickly went trough your code again, and it seems you will have multiple forms. this means, that you will get elements in different forms with the same id's. An id should be unique for troughout the page. So when you try to get a value like this $("#second_firstname").val(); that won't work. because jQuery doesn't know what element you mean, so all elements that can appear multiple times in a page need to have a class and CAN NOT have an id.
You could then loop trough your forms by changing things to:
$('form').each(function() {
$(this).on('submit', function() {
var first_firstname = $(".first_firstname", this).val(); // . instead of # and use 'this' as context
// and so on..
// the rest of your code here.
}
});
table with forms can be seen here
Here is my block of Php code in which I am rendering the table row:-
Actually what I am trying to achieve is that on the click of the button in the first row I should be able to show the next row, which is previously hidden by using .hide() in the document ready script.
<?php
echo "<tr>";
echo "<td>"."<button id= \"btnnumber_". $i ." \" class=\"btn info toggler\" data-value=\" $val\">Show Info <i class=\"icon-arrow-down\"></i></button>"."</td>"; // On click of this button I am taking its id in Jquery getting the number at end creating the id of the next row in the Jquery script.
echo "</tr>";
echo "</tr>";
echo "<tr id=\"row_$i \" class=\"info_row\">";// This row is dynamically generated one each row has its unique id like 0 row is having id row_0,1 row is having id row_1 etc.
echo "<td id=\"student_count\">"."students count:"."</td>";
echo "<td id=\"start_date\">"."start date: "."</td>";
echo "<td id =\"end_date\">"."end date: "."</td>";
echo "<td></td>";
echo "</tr>";
?>
This row is initially set to hide in document ready by using the following JQuery:-
$(function(){
$('.info_row').hide();// On document load I am hiding all the element with class info_row.
$('.toggler').toggle(function(){// Then I am toggling between hide and show.
var currentId = $(this).attr('id');
var number = currentId.substr(currentId.length - (currentId.length - currentId.indexOf("_") - 1));
var rowId = 'row_' + number;
$("#" + rowId).show();
}, function(){
var currentId = $(this).attr('id');
var lastChar = currentId.substr(currentId.length - (currentId.length - currentId.indexOf("_") - 1));
var rowId = 'row_' + lastChar;
$("#" + rowId).hide();
});
});
I am not able to achieve the toggle i.e the row is not hiding and showing as I was trying to achieve.
Any help will be highly appreciated.
This line look like a problem
echo "<tr id=\"row_$i \"
In that there is a spurious space in the id.
echo "<tr id=\"row_$i\"
I am creating a popup dialog box where I need to put a set of values in hidden format, but when I am getting the value in AJAX post, I am getting only last value.
this is the PHP part:
$plan_ids=array();
foreach($test_plan as $plan)
{
$plan_ids[]=$plan['plan_id'];
}
?>
<?php
foreach($plan_ids as $id)
{
echo "<input type='hidden' id='plan_id' value='$id'>";
}
//var_dump($plan_ids);
// echo $plan['plan_id'];
?>
In the AJAX part I am doing:
$("#save").click(function () {
var name = $('#name').val();
var id = $('#release_id').val();
var plan_id = $('#plan_id').val();
//alert('hello');
$.ajax({
type: 'POST',
url: '/api/api.php?action=put_iteration&name=' + name + '&id=' + id + '&plan_id=' + plan_id,
data: "name=" + name + "&id=" + id + "&plan_id=" + plan_id,
success: function () {
$('#save').hide(function () {
$('div.success').fadeIn();
});
}
});
});
I'm clueless about HTML hidden fields.
Not a PHP guy, But some thoughts . Forgive me for syntax errors.
In the loop You are creating hidden element with the same ID. That is not good. Change the code sot hat the Id's will be ( SHOULD BE ALWAYS ) Unique.
<div>
foreach($plan_ids as $id)
{
echo "<input type='hidden' id='plan-$id' value='$id' class='myHidden'>";
}
Now in your script, use jQuery selectors based on the hidden item
var hiddenItems=$("input[type='hidden']");
may be now you can loop thru this
var items
$.each(hiddenItems,function(item,index){
items+= hiddenItems[index];
});
Or you can map function like this so that it will give a list of values of hidden fields comma seperated.
var itemsJoined=$("input[type='hidden']").map(function () {
return this.value;
}).get().join(',');
you can name all your hidden fields like an array name="plan_id[]"
And instead of passing it as a string you can have a wrapping FORM around hidden fields and then use jquery serialize function to POST it
Now you will get all the plan_id in the form of an array in the POST variable
Adding an example
<?php
echo '<form name="planidform" id="planidform">';
foreach($plan_ids as $id)
{
echo "<input type='hidden' name="plan_id[]" value='$id'>";
}
echo '</form>';
?>
After than in jQuery do it in following manner:
data: "name=" + name + "&id=" + id + "&"+$("#planidform").serialize(),
I think you want to change id='plan_id' to name='plan_id[]' for a start.... you are only allowed to have one element with a given id (i.e. id is required to be unique across elements in a given page).
you should put diffrent names / ids to the hidden fields.
if u want to submit them all at once u can store them in an array.
for example:
$i=0;
foreach($plan_ids as $id){
$i++;
echo "<input type='hidden' id='plan_id_$i' value='$id'>";}
then u can address or group them in JS.