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.
Related
I have some checkboxes, that when checked adds their respective classes to the <body> element via Ajax:
<input type="checkbox" name="<?php echo $opt;?>" class="onoffswitch-checkbox" id="myonoffswitch-<?php echo $n;?>" value="true"<?php echo (dh_switch_setting_get($opt, '0') == '0' ? "" : " checked='checked'");?> />
<label class="onoffswitch-label" for="myonoffswitch-<?php echo $n;?>" data-class="<?php echo $obj['class'];?>"></label>
(function($) {
$(function() {
$("LABEL[for^=myonoffswitch]")
.each(function() {
// ---Which label was clicked? ---
var which = $(this).attr("for");
var cls = $(this).data("class");
if ( $("INPUT[id=" + which + "]").is(":checked") ) {
$("BODY").addClass(cls);
} else {
$("BODY").removeClass(cls);
}
$(this).parents(".onoffswitch").on("click", function() {
if (!$("INPUT[id=" + which + "]").is(":checked")) {
$("BODY").addClass(cls);
} else {
$("BODY").removeClass(cls);
}
var val = $("INPUT[id=" + which + "]").is(":checked") ? "1" : "0";
console.info("Set " + which + " to " + val)
$.ajax({
url: './',
type: "POST",
data: $("INPUT[id=" + which + "]").attr("name") + "=" + val + "&<?php echo MD5("DH");?>=1",
success: function (response) {
},
error: function (jqXhr, e, responseText) {
console.log(arguments);
alert("Oops. Something went wrong: " + responseText);
}
});
});
});
});
})(jQuery);
I also have a dynamic PHP stylesheet style.php as below:
<?php
header("Content-type: text/css;charset: UTF-8");
require('styles1.php');
require('styles2.php');
require('styles3.php');
?>
I'm trying to get some IF statements to work where if the body has a class, then require() the specified styles.
I tried variations of this, but nothing is working:
<?php
header("Content-type: text/css;charset: UTF-8");
$classes = get_body_class();
if (in_array('class1',$classes)) {
require ( 'styles1.php' );
}
if (in_array('class2',$classes)) {
require ( 'styles2.php' );
}
if (in_array('class3',$classes)) {
require ( 'styles3.php' );
}
?>
Can anyone help me out here?
In an ajax call, i need to obtain, as a response, the value of a parameter of a JSON object, but i don't understand how to do it.
If this is my PHP file in which i reproduce the JSON structure
echo " { ";
echo '"general" : {';
echo '"obj" : [
{"name" : "Primo", "description" : "Descrizione associata alla prima voce"},
{"name" : "Secondo", "description" : "Descrizione associata alla seconda voce"},
{"name" : "Terzo", "description" : "Descrizione associata alla terza voce"}
]}}';
And this is my HTML file
$(document).ready(function(e) {
$('#name li').click(function() {
var name = $(this).text();
url = "example.php?name=" + name;
$.getJSON(url,
function(json) {
//for (i = 0; i < json.general.obj.length; i++) {
//output = "<tr>";
output = "<td>" + json.general.obj[0].name + "</td>";
output += "<td>" + json.general.obj[0].description + "</td>";
//output += "</tr><br/>";
console.log(output);
$("#response").append(output);
//}
});
});
});
<ul id="name">
<li data-id="1">Primo</li>
<li data-id="2">Secondo</li>
<li data-id="3">Terzo</li>
</ul>
<div id="response">
<!--Data goes here-->
</div>
Which is the right way to go? Where do i need to place the $_REQUEST['name'] variable to receive back as a response the desired "Description" value?
I'm stuck there
You can use the data-id to retrieve the specific item of the array by its index, something like this:
$('#name li').click(function() {
var name = $(this).text();
var index = $(this).data('id') -1;
var url = "example.php?name=" + name;
$.getJSON(url, function(json) {
output = "<p>" + json.general.obj[index].name + "</p>";
output += "<p>" + json.general.obj[index].description + "</p>";
$("#response").append(output);
});
});
Example fiddle
Note that I changed td in the output to p as td elements are only valid within tables.
Also, if you only want the data of the last clicked element to be visible (instead of appending a new set each time) you can use:
$("#response").html(output);
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 --> }
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>
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,