jquery dynamicaly add new row - php

I need to dynamically add new rows each time click on add button.i tried to do it as below.i'm using php codeigniter and jquery.i'm new to jquery and i'm struggling on how to append new row in jquery. But this jquery function is not working.pls help me to sole this problem.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p table class="datatable <tr><td width="200">').size() + 1;
$('#addNew').live('click', function() {
alert('ok');
alert(i);
$('<p>
<label for="trainer">Trainer: </label>
<td><select name="state_' + i +'"">
<option></option>
</select>
<select>
<option></option>
</select></td></tr></table>
Remove </p>').appendTo(addDiv);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
echo '<div id="addinput">';
echo '<p>';
echo '<table class="datatable">';
echo '<tr><td width="200">'.form_label('Trainer: ', 'trainer').'</td>';
$options4 = array(
0 => 'Select state',
1 => 'QLD',
2 => 'NSW',
3 => 'VIC',
4 => 'WA',
5 => 'ACT',
6 => 'NT',
7 => 'SA',
8 => 'TAS'
);
$options5[0] = 'Select below';
foreach ($trainers as $row) {
$name = $row->first_name.' '.$row->last_name;
$options5[$row->id] = $name;
}
echo '<td>'.form_dropdown('state', $options4, '', 'class="update_state" id="state"').' '.form_dropdown('trainers[]', $options5, 0).'Add</td></tr>';
echo '</table>';
echo '</p';
echo '</div>';

Hope this example here can help you:
http://fiddle.jshell.net/GxhSR/

The problem may be in your #addnew.click declaration. You are placing the html on separate lines. This can cause problems in some browsers (if not all). Javascript Strings cannot have literal line breaks. If you must separate the string across multiple lines, it is best practice to use concatenation. Your code:
$('#addNew').live('click', function() {
alert('ok');
alert(i);
$('<p>
<label for="trainer">Trainer: </label>
<td><select name="state_' + i +'"">
<option></option>
</select>
<select>
<option></option>
</select></td></tr></table>
Remove </p>').appendTo(addDiv);
Should be written as:
$('#addNew').live('click', function() {
alert('ok');
alert(i);
$('<p>' +
'<label for="trainer">Trainer: </label>' +
'<td><select name="state_' + i +'"">' +
'<option></option>' +
'</select>' +
'<select>' +
'<option></option>' +
'</select></td></tr></table>' +
'Remove </p>').appendTo(addDiv);
See How do I break a string across more than one line of code in JavaScript? for more information on this.
Note that I don't know if this will fix your problem but it is a place to start. Also, Always check the developer's console in your browser. It will give you hints on where your javascript is broken,

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p>'+
'<table id="datatable"><tr><td width="200"></td><td>'+
'<select name="state_' + i +'" id="state">'+
'<option value="0">Select State</option>'+
'<option value="1">QLD</option>'+
'<option value="2">NSW</option>'+
'<option value="3">VIC</option>'+
'<option value="4">WA</option>'+
'<option value="5">ACT</option>'+
'<option value="6">NT</option>'+
'<option value="7">SA</option>'+
'<option value="8">TAS</option>'+
'</select><select name="trainer_' + i +'" id="trainer"><option></option></select>'+
'Remove</td></tr></table></p>').appendTo(addDiv)
i++;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
});
});
</script>

Related

jQuery working on PC but not on WAMP or Shared Server

I don't know why but I have a piece of code which works on my system but is not working on WAMP or Shared server.
Below is my piece of code :-
<html>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript">
(function($) {
$.ajax({
url:"select2.json",
type:"GET",
dataType:"json",
success:function(data){
var selectedDepartment, selectedSubproj;
$.fn.changeType = function() {
var options_projname = '<option>Select<\/option>';
$.each(data, function(i, d) {
options_projname += '<option value="' + d.projname + '">' + d.projname + '<\/option>';
});
$("select#projname", this).html(options_projname);
$("select#projname").change(function() {
var index = $(this).get(0).selectedIndex;
var d = data[index - 1]; // -1 because index 0 is for empty 'Select' option
selectedDepartment = d;
var options = '';
if (index > 0) {
options += '<option>Select<\/option>';
$.each(d.subproj, function(i, j) {
options += '<option value="' + j.title + '">' + j.title + '<\/option>';
});
} else {
options += '<option>Select<\/option>';
}
$("select#subproj").html(options);
});
$("select#subproj").change(function() {
var index = $(this).get(0).selectedIndex;
selectedSubproj = selectedDepartment.subproj[index -1];
var options = '';
if (index > 0) {
$.each(selectedSubproj.unit, function(i, b) {
//options += '<option value="' + b.name + '">' + b.name + '<\/option>';
options += '<input type="checkbox" name="' + b.name + '" value="' + b.name + '">' + b.name + '<br/>';
});
} else {
options += '<option>Select<\/option>';
}
$("#unit").html(options);
});
};
}
});
})(jQuery);
$(document).ready(function() {
$("form#search").changeType();
});
</script>
<form id="search" action="" name="search">
<select name="projname" id="projname">
<option>Select</option>
</select>
<select name="subproj" id="subproj">
<option>Select</option>
</select>
<div name="unit" id="unit">
</div>
</form>
</body>
</html>
I am getting the following error when I run in WAMP or Shared Server.
http://s8.postimg.org/vj19w76v9/error.png
But it runs fine if I run it like a normal html file on my pc.
My JSON is also rendering very well so I know that there is no issue with it.
I tried clearing cache and all the good stuff but its eating my brain off...
Would be glad if someone could help.
Thanks in advance... Cheers...
The problem is that you are defining your changeType plugin in your success callback of the ajax call. Thus, at the time the document is ready, when you call that plugin, it will be undefined. You will need to define the plugin first and think of a way to pass the data variable you get from the ajax call by parameter. I believe something rough like this should work:
(function ($) {
$.fn.changeType = function (data) {
var selectedDepartment, selectedSubproj;
var options_projname = '<option>Select<\/option>';
$.each(data, function (i, d) {
options_projname += '<option value="' + d.projname + '">' + d.projname + '<\/option>';
});
$("select#projname", this).html(options_projname);
$("select#projname").change(function () {
var index = $(this).get(0).selectedIndex;
var d = data[index - 1]; // -1 because index 0 is for empty 'Select' option
selectedDepartment = d;
var options = '';
if (index > 0) {
options += '<option>Select<\/option>';
$.each(d.subproj, function (i, j) {
options += '<option value="' + j.title + '">' + j.title + '<\/option>';
});
} else {
options += '<option>Select<\/option>';
}
$("select#subproj").html(options);
});
$("select#subproj").change(function () {
var index = $(this).get(0).selectedIndex;
selectedSubproj = selectedDepartment.subproj[index - 1];
var options = '';
if (index > 0) {
$.each(selectedSubproj.unit, function (i, b) {
//options += '<option value="' + b.name + '">' + b.name + '<\/option>';
options += '<input type="checkbox" name="' + b.name + '" value="' + b.name + '">' + b.name + '<br/>';
});
} else {
options += '<option>Select<\/option>';
}
$("#unit").html(options);
});
};
})(jQuery);
$(document).ready(function () {
$.ajax({
url: "select2.json",
type: "GET",
dataType: "json",
success: function (data) {
$("form#search").changeType(data);
}
});
});

Insert PHP code in JQuery

Good day every one. I want to insert my php code in my jquery. I want to show my data in database using PHP and I want to put it in a option box. I used var in jquery plus the code of my php but isn't working. Please help me.
Shows the data:
<?php
$res2 = mysql_query("SELECT * FROM expense_maintenance ORDER BY name Asc");
while ($result2 = mysql_fetch_assoc($res)){
$name = $result2["name"];
?>
jquery code(dynamic adding text box)
var nitem =0;
var ntotal = 0;
var option = <?php echo" <option value='$name'>$name</option>";} ?>;
function totalItemExpence(){
ntotal = 0;
$('.expense_cost').each(function(){
if($(this).val() != ""){
ntotal += parseFloat($(this).val());
}
});
//$('#total').val(ntotal);
}
$(document).on('change keyup paste', '.expense_cost', function() {
totalItemExpence();
mytotal();
});
$('.btn').click(function() {
nitem++;
$('#wrapper').append('<div id="div' + nitem + '" class="inputwrap">' +
'<select class="expense_name" id="' + nitem '">"'+ option +'"</select>' +
'<input class="expense_desc" placeholder="Expense Description" id="' + nitem + '" required/>' +
'<input class="expense_cost" onkeypress="return isNumber(event)" placeholder="Expense Cost" id="' + nitem + '" required/> ' +
'<br><br></div>');
});
$('.btn2').click(function() {
ntotal = $('#total').val();
$("#div" + nitem + " .expense_cost").each(function(){
if($(this).val() != ""){
ntotal -= parseFloat($(this).val());
}
});
$("#div" + nitem ).remove();
nitem--;
$('#total').val(ntotal); });
Try this for while loop :
<?php
$res2 = mysql_query("SELECT * FROM expense_maintenance ORDER BY name Asc");
$options = '';
while ($result2 = mysql_fetch_assoc($res)){
$options .= "<option value='{$result2["name"]}'>{$result2["name"]}</option>";
}
?>
And JS part :
...
var option = "<?php echo $options; ?>";
...
This line:
var option = "<?php echo "<option value='$name'>$name</option>"; ?>";
must be in your .php file, because php code won't be executed in a .js file (that's why it's called .php)...
You can wrap that line in a <style> tag in your .php file
Also, don't forget to add these things --> "
And to remove this one --> }

jQuery autocomplete function not working?

I have a page where a user can click a button which says "Add a Skill" and then it should display an input box where you type in your skill, it should display another input box where your skill level should appear and then a horizontal slider where you select your skill level.
I have table in the database called 'skill_list' which has two columns: id and name. The name field will contain thousands of skills in it which you can select from.
I also need the functionality for it to only post the form if the skill exists in the database.
What I am asking is how to get the autocomplete working with jQuery based on my current code or could someone rewrite it slightly for me?
At the moment I have the following code and it throws up no errors in the firebug console and everything works aas normal but I'm really unsure what I have to do to get this working:
skills.php - auto() function (controller):
public function auto(){
$skill = $_POST['skill-0'];
$query = $this->db->query('SELECT * from skill_list WHERE name LIKE "'.$skill.'%" ORDER by name ASC LIMIT 10');
$data = array();
if ( $query && mysql_num_rows($query) ){
while( $row = mysql_fetch_array($query, MYSQL_ASSOC) ){
$data[] = array(
'label' => $row['name'],
'value' => $row['id']
);
}
}
echo json_encode($data);
flush();
}
skills.php (view)
<form method="post" action="skills/add" id="container">
<script>
$.fn.addSlide = function () {
return this.each(function () {
var $this = $(this),
$num = $('.slide').length++,
$name = $('<input type="text" class="inputField" id="autoskill" name="skill-' + $num + '" placeholder="What\'s your skill?"></div>'),
$slide = $('<br><div class="slide" id="slider-' + $num + '"></div><br>'),
$amt = $('<input name="amount-' + $num + '" id="amount-' + $num + '" class="inputField" readonly placeholder="Slide to select this skill level..."/><br>');
$this.append($name).append($amt).append($slide);
$slide.slider({
value: 0,
min: 0,
max: 5,
step: 1,
slide: function (event, ui) {
$amt.val(ui.value);
}
});
});
}
$('body').on('click', '.addNew', function(event) {
event.preventDefault();
$('#newFields').addSlide();
});
var count = 0;
$(document).ready(function(){
$('#autoskill').autocomplete({
source:'skills/auto', minLength:2
});
$('.addNew').click( function(event){
event.preventDefault();
$('#length').html(count);
count++;
});
$('.submitButton').click( function(event){
$('#container').append('<input type="hidden" name="count" value="' + count + '">');
});
});
</script>
<button class="addNew submitButton"> Add a Skill </button><br>
<div id="newFields"></div>
<input type="submit" class="submitButton" value="Save Skills">
</form>
Hopefully someone can help, Thanks!
make $name into this
$name = $('<input type="text" class="inputField" id="autoskill-'+$num+'" name="skill-' + $num + '" placeholder="What\'s your skill?"></div>'),
then after
$this.append($name).append($amt).append($slide);
add
$('#autoskill'+$num).autocomplete({
source:'skills/auto', minLength:2
});
and remove the autocomplete line completely from ur ready function
then for json make
$data[] = array(
'label' => $row['name'],
'value' => $row['id']
);
into
$data[$row['id']]=$row['name']

jQuery/PHP Select checkboxes from $_SESSION variable

I'm not sure if I'm doing this completely wrong, but I'm hoping what I'm trying to do is possible.
I have an existing ajax jquery function that saves the "selected" checkboxes from a user and stores them in $_SESSION['order_items'][index]['cheeseids'][]; When a user goes to recall this "item", I'd like to have the same checkboxes "selected" as before. See example below:
[order_items] => Array
(
[1] => Array
(
[cheeseids] => Array
(
[0] => 1
[1] => 2
[2] => 4
)
My "change/restore" jquery function uses the following variables to get the index number:
var productIDValSplitter = (this.id).split("_");
var productIDVal = productIDValSplitter[1];
The function I'm trying to use to "re-select" boxes 1, 2, 4 (from cheeseids array) is not working (it is inside my jQuery function). It actually causes the entire jQuery code to not work:
<?php
foreach($_SESSION['order_items'] as $key => $value)
{
?>
var idnum = <?php echo $value['<script type="text/javascript">productIDVal</script>']['cheeseids'] ?>;
$("div.cheesebox input[type=checkbox]").eq(" + idnum + ").attr("checked", "checked");
<?php
}
?>
JS Output:
var idnum = ;
$("div.cheesebox input[type=checkbox]").eq(" + idnum + ").attr("checked", "checked");
var idnum = ;
$("div.cheesebox input[type=checkbox]").eq(" + idnum + ").attr("checked", "checked");
Entire JS/jQuery function that I'm adding the PHP too:
$("#basketItemsWrap li img.change").live("click", function(event) {
var productIDValSplitter = (this.id).split("_");
var productIDVal = productIDValSplitter[1];
$("#notificationsLoader").show();
$.ajax({
type: "POST",
url: "includes/ajax/functions.php",
data: { productID: productIDVal, action: "deleteFromBasket"},
success: function(theResponse) {
$("div#order_qty input").attr('value', $("#order_" + productIDVal + " #order_qty").text());
$("div#order_listprice input#price1").attr('value', $("#order_" + productIDVal + " #order_listprice").text().replace("$", ""));
$("div#order_price input#discprice1").attr('value', $("#order_" + productIDVal + " #order_price").text().replace("$", ""));
$("div#order_price input#itemprice1").attr('value', $("#order_" + productIDVal + " #order_itemprice").text().replace("$", ""));
//The following functions restore the order details in the select menus, checkboxes, and radio buttons
//Restores the item selected
for(var i = 0; i < $("#item1 option").size(); i++)
{
if($("#order_" + productIDVal + " #order_item").text() == $("#item1 option:eq("+i+")").text())
{
$("#item1 option:eq("+i+")").attr("selected", "selected");
//$("#item1").val(i);
CalcPrice(1);
}
}
//Restores the promotion selected
for(var i = 0; i < $("#promo1 option").size(); i++)
{
if($("#order_" + productIDVal + " #order_promo").text() == $("#promo1 option:eq("+i+")").text())
{
$("#promo1 option:eq("+i+")").attr("selected", "selected");
//$("#promo1").val(i);
CalcPromo(1);
}
}
<?php foreach($_SESSION['order_items'][1]['cheeseids'] as $id): ?>
$("div.cheesebox input[type=checkbox]#<?php echo $id;?>").attr("checked", "checked");
<?php endforeach; ?>
//Restores the cheese options selected
// $('div.cheesebox input[type=checkbox]').size(); i++)
//$('div.cheesebox input[type=checkbox]').eq(1).attr('checked', 'checked');
$("#order_" + productIDVal).hide("slow", function() {$(this).remove();Calc();});
$("#notificationsLoader").hide();
}
});
});
PHP/HTML code to generate the checkboxes:
<?php
//Display all "cheese" options in a checkbox group
foreach($_SESSION['ingr_cheese'] as $key => $value)
{
echo "<div class=\"cheesebox\" style=\"float:left; width:175px; margin-bottom:7px;\">";
echo "<input type=\"checkbox\" name=\"cheese1\" id=\"cheese1\" class=\"cheeseCheck\" value=\"".$key."\"> <label for=\"cheese1\">".$value['cheese']."</label></br>";
echo "</div>";
}
?>
If the array you listed is already is an accurate representation of what's in the $_SESSION array, then this code should do what you're looking for.
<?php foreach($_SESSION['order_items'][1]['cheeseids'] as $id): ?>
$("div.cheesebox input[type=checkbox]#<?php echo $id;?>").attr("checked", "checked");
<?php endfor; ?>
This should generate javascript that looks like this:
$("div.cheesebox input[type=checkbox]#1").attr("checked", "checked");
$("div.cheesebox input[type=checkbox]#2").attr("checked", "checked");
$("div.cheesebox input[type=checkbox]#4").attr("checked", "checked");
This code assumes your markup for the checkboxes looks (somewhat) like this:
<div class=".cheesebox">
<input type="checkbox" id="1">
<input type="checkbox" id="2">
<input type="checkbox" id="3">
<input type="checkbox" id="4">
</div>
I verified the selector syntax, but if that doesn't work, then I probably made a bad assumption about the markup of your checkboxes. Paste in some more of your html if this isn't enough to point you in the right direction and I'll take another swing at it.

How to call/activate the 2nd select list only after 1st select list was selected?

I have the following select list:
SELECT LIST 1:
<select name="productcolor" id="productcolor" onChange="GetAvailProductSizes();">
<option value=""><? echo $langdata['oneprodpage_selectcolor']; ?>...</option>
<? foreach ($thisproduct['availcolors'] as $color) { ?>
<option value="<? echo $color['id']; ?>"><? echo $color['name']; ?></option>
<? }; ?>
</select>
SELECT LIST 2:
<select name="productsize" id="productsize" style="width: 120px;">
<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>
</select>
If in LIST 1 no options where selected, LIST 2 will be empty. It's like LIST 2 depends of LIST 1.
This is made with this function:
<script type="text/javascript"><!--
function GetAvailProductSizes() {
$('select#productsize option').remove();
$('select#productsize').append('<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>');
var color = $('#productcolor').val();
if (color > 0) {
var availsizes;
var http_request = new XMLHttpRequest();
http_request.open( "GET", '<? echo ROOT; ?>/autocompleteavailsizes/?productid=<? echo $thisproduct['id']; ?>&color=' + color, true );
http_request.send(null);
http_request.onreadystatechange = function () {
if ( http_request.readyState == 4 ) {
if ( http_request.status == 200 ) {
availsizes = eval( "(" + http_request.responseText + ")" );
for (var i = 0; i < availsizes.length; i++) {
$('select#productsize').append('<option value="' + availsizes[i].id + '">' + availsizes[i].name + '</option>');
};
} else {
alert( "There was a problem with the URL." );
}
http_request = null;
}
};
};
}
//-->
</script>
Now, I want the SELECT LIST 2 to be hidden until SELECT LIST 1 was not touched. Any help please with PHP or jQuery. Thank you!
Simply add display:none to the style attribute of the second list and use $('select#productsize').show(); inside your function to let it appear,

Categories