Give Default Checked Value To The Checkbox Using Jquery - javascript

I tried to add checked property to a specific checkbox using jquery, but it seems doesn't work properly.
Checkbox Function Display
function product_category_loop_array ($product_category_array = array (), $parent_id = 0, $margin = -20) {
if (!empty ($product_category_array[$parent_id])) {
$margin = $margin + 20;
foreach ($product_category_array[$parent_id] as $items) {
echo "<input style='margin: 0 0 0 ".$margin."px; overflow: hidden;' id='".$items['id']."' class='category_checkbox left' name='product_category[]' type='checkbox' value='".$items['id']."'><label class='category_checkbox_label left'>".$items['name']."</label>
<div class='clear'></div>";
product_category_loop_array ($product_category_array, $items["id"], $margin);
}
}
}
function product_category () {
$db_connect = mysqli_connect (db_host, db_username, db_password, db_name);
$product_category_query = $db_connect->query ("SELECT id, name, parent_id FROM `product_category` ORDER BY name ASC");
$product_category_array = array ();
if (mysqli_num_rows ($product_category_query)) {
while ($row = mysqli_fetch_array ($product_category_query, MYSQLI_ASSOC)) {
$product_category_array[$row['parent_id']][] = $row;
}
product_category_loop_array ($product_category_array);
}
}
HTML
<div id="tabs-2" class="product_detail hide">
<div class="left">
<form class="product_detail_form" method="post" action="">
<?php product_category () ?>
<p class="detail_submit"><input name="save_product_category" type="submit" value="Save"></p>
</form>
</div>
</div>
Jquery
<script>
$ (document) .ready (function () {
<?php echo $hide_div ?>;
var selected_array = <?php echo json_encode ($product_category_selected) ?>;
$.each (selected_array (key, value) {
$ ("#"+value).prop("checked", true);
});
});
</script>
Any help will be appreciated.

Use
$ ("#"+value).attr("checked", "checked");

<script>
$(document).ready(function() {
<?php echo $hide_div ?>;
// DECODE JSON IN JS
var selected_array = $.parseJSON(<?php echo json_encode ($product_category_selected) ?>);
$.each(selected_array(key, value) {
$("#" + value).prop("checked", true);
});
});
</script>

Related

js get php variable with dynamic name

I have a simple button calling a js function. There I want use the php var with dynamic names. Any Idea please?
<?php
$counter = 1;
${"fotos" . $counter++} = array();
foreach ($row as $item) {
${"fotos" . $counter}[] = $item->img;
}
?>;
//will generate two vars:
$fotos = [img1];
$fotos1 = [img1,img2];
<button type="button" onClick="verAdjuntos(<?php echo $counter; ?>)" class="btn btn-xs btn-default"> View</button>
//parameter passed verAdjuntos(1) forxample
When id parameter is null, the if condition works fine. But adding id to php var name is the problem...
<script type="text/javascript">
function verAdjuntos(id){
if (id == null){
var fotos = <?php echo $fotos ?>; //output ok
alert(JSON.stringify(fotos));
}else{
var fotos = <?php echo $fotos?> + id; /// how do name $fotos1 here?
alert(JSON.stringify(fotos));
};
}
</script>
Doing alert work fine too:
alert(JSON.stringify(fotos1));
Solved doing with array of arrays from php variable.
<?php
$counter = 1;
$fotos = array();
foreach ($row as $item) {
$allfotos[$counter] = array($item->img);
$counter++;
}
?>;
//will generate two vars:
$fotos[1] = [img1];
$fotos[2] = [img1,img2];
<button type="button" onClick="verAdjuntos(<?php echo $counter; ?>)" class="btn btn-xs btn-default"> View</button>
<script type="text/javascript">
function verAdjuntos(id){
if (id == null){
var fotos = <?php echo $allfotos ?>;
alert(JSON.stringify(fotos));
}else{
<?php
$js_array = json_encode($allfotos);
echo "var javascript_array = ". $js_array . ";\n";
?>
var fotos = JSON.parse(javascript_array[id]);
alert(JSON.stringify(fotos));
};
}
</script>

opencart Price range slider extension

Please help me to correct the code. Where it is conflicting with other javascript action. This price filter in opencart is stopping the action of Add to cart in category page. following is the code where php is called inside the javascript. Something is missing or not properly coded.
<div class="row">
<div class="slide-filter">
<h2><?php echo $heading_title; ?></h2>
<div class="list-group">
<div class="list-group-item">
<div id="filter-group1">
<div id="scale-slider"></div>
<button type="button" id="button-price-filter" class="filter-button"><?php echo $button_filter; ?></button>
</div>
</div>
</div>
</div>
</div>
and the javascript is
$("#scale-slider")
.slider({
min: <?php echo round($price_range_min) ; ?>,
max: <?php echo round($price_range_max) ; ?>,
range: true,
values: [<?php echo (isset($price_range[0])?$price_range[0]:0); ?>, <?php echo (isset($price_range[1])?$price_range[1]:$price_range_max); ?>]
})
.slider("pips", {
rest: false,
<?php if (!$right_code) { ?>
prefix: "<?php echo $price_code; ?>",
<?php } else { ?>
suffix: "<?php echo $price_code; ?>"
<?php } ?>
})
.slider("float");
(function( $ ) {
$(function() {
$('#button-price-filter').on('click', function() {
priceRange = [];
$('#scale-slider .ui-slider-tip').each(function(){
priceRange.push($(this).html());
});
$('.<?php echo $product_class; ?>').hide();
$('.clearfix').remove();
$('.<?php echo $product_class; ?>').each(function(){
if( $(this).find( ".price span.price-new" ).length ) {
var price = $(this).find( ".price span.price-new" ).html().replace('<?php echo $price_code; ?>','').replace(',','');
} else {
var text = $(this).find('.price').html().replace('<?php echo $price_code; ?>','');
if( $(this).find( ".price span" ).length ) {
var price = text.substring(0,text.indexOf('<span')).replace(',','');
} else {
var price = text.replace(',','');
}
}
price = parseInt(price);
if( !isNaN(price) && (price > priceRange[0] && price < priceRange[1]) ){
$(this).fadeIn("slow");
}
});
});
});
})(jQuery);
remove the $('.clearfix').remove(); ,may be work perfectly

how to php js variable to jquery file

how i can parse an Variable (php with js script) to an js file (jquery)?
This is what i do:
<script type='text/javascript'>
<?php
session_start();
$var1 = $_SESSION['one'];
$var2 = $_SESSION['two'];
$con = mysqli_connect("");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$result = mysqli_query($con,"Select name FROM table WHERE one < '". $var1 . "' OR two < '". $var2 . "'");
$rows=array();
while($row=mysqli_fetch_array($result))
{
$rows[]=$row["name"];
}
$js_array = json_encode($rows);
echo "var stat = ". $js_array . ";\n";
?>
</script>
In my js file i have this:
$(document).ready(function($)
{
for (var x = 0; x < stat.length; x++) {
$(".class#" + stat[x]).css("background-color", "#e74c3c");
alert(stat);
}});
My browser show this :
var stat = ["a1","a2","a3"];
How i can now get the php js_array to the stat variable (js)?
Alternatively, since your using jquery, you could use $.each() function. This is very useful to what you want to achieve. Consider this example:
<div class="class" id="a1" style="width: 50px; height: 50px;"></div>
<div class="class" id="a2" style="width: 50px; height: 50px;"></div>
<div class="class" id="a3" style="width: 50px; height: 50px;"></div>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var stat = null;
<?php
// sample data
$array_from_db = array('a1', 'a2', 'a3');
$data = json_encode($array_from_db);
echo "stat = $data;"; // assign it to stat
?>
// use $.each();
$.each(stat, function(index, element){
// random colors for example's sake
var color = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
$('.class#'+element).css({backgroundColor: color});
});
});
</script>

get the unique id of div generated using while loop

<?php
include('config/config.php');
if($_POST)
{
$q=$_POST['searchword'];
$sql_res=mysql_query("select uid,username,email,media,country from select_tag where username like '%$q%' or email like '%$q%' order by uid LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$username=$row['username'];
$email=$row['email'];
$media=$row['media'];
$country=$row['country'];
$b_username='<b>'.$q.'</b>';
$b_email='<b>'.$q.'</b>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="display_box" id="display">
<img align="top" src="<?php echo $media; ?>" style="width:40px; height:40px;" />
<span class="name" id="name" data-ruid="<?php echo addslashes($row[uid]); ?>" style="position: relative;top:11px;" onclick="showselected_people();"><?php echo $final_username; ?></span></div>
<?php
}
}
?>
so i edited the post but now i m getting error "Use of undefined constatnt uid"..???
you can use uid in your span like this:
<span class="name" id="name-<?php echo $row[uid] ?>" style="position: relative;top:11px;"><?php echo $final_username; ?></span></div>
then in jquery:
$(".name").on('click', function(){
var arr = this.id.split('-');
var id = arr[1]; //its your uid
});
By this code, when you'll click on div, there will be store the user name in userName variable.
var parElem = document.getElementById('display');
parElem.addEventListener('click', getName);
var userName;
function getName(){
var allspan = this.getElementsByTagName('span');
for(var i=0; i<allspan.length; i++){
if(allspan[i].id == 'name'){
userName = allspan[i].innerHtml;
break;
}
}
}
Though #Awlad Liton's solution is adequate, I usually prefer placing such data in separate attributes.
<span class="name" id="name" data-ruid="<?php echo addslashes($row['uid']); ?>" ....
Then in JS:
$(".name").on('click', function() {
var rowId = $(this).attr("data-ruid");
//and maybe even clean it up
rowId = parseInt(rowId);
});

Javascript function calls php

I´m really frustrated about a problem with my website. From a php File, I get this list of JSON:
{"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurstel"},"Recipe_9":{"ID":"9","TITLE":"Schnitzel"},"Recipe_10":{"ID":"10","TITLE":null},"Recipe_19":{"ID":"19","TITLE":null},"Recipe_20":{"ID":"20","TITLE":"Hundefutter"},"Recipe_26":{"ID":"26","TITLE":"Apfelstrudel"},"Recipe_37":{"ID":"37","TITLE":null},"Recipe_38":{"ID":"38","TITLE":"AENDERUNG"},"Recipe_39":{"ID":"39","TITLE":null},"Recipe_40":{"ID":"40","TITLE":"Schnitzel"},"Recipe_42":{"ID":"42","TITLE":"Release-Test"},"Recipe_43":{"ID":"43","TITLE":"Wurstel2"}}},"Message":null,"Code":200}
In my html file, I´ve got a JS function that parses this JSON data and save it to a array.
<script type="text/javascript">
function test() {
//var availableTags = new Array(400);
//availableTags[0] = "Test";
alert("misstake");
var availableTags = JSON.parse(<?php include("/php/search_new.php"); ?>);
alert("misstake");
//var availableTags = JSON.parse(<?php include("/php/getAllRecipes.php"); ?>);
alert("misstake");
for(var i=0;i<availableTags.length;i++){
alert("<b>availableTags["+i+"] is </b>=>"+availableTags[i]+"<br>");
}
alert("Hallo");
}
</script>
I´m sure, the function is called because I tried it just with a alert in it.
Here´s my HTML:
<body>
<form action="search.html" onsubmit="test()">
<input type="text" class="searchinput" style="margin-left: 850px; margin-top: 0px; width:170px; background: #fff url(images/search_icon.png) no-repeat 100%;" placeholder="Suchen..."></input>
<input type="submit" value="" width: 5px></input>
</form>
</body>
So there must be a mistake at
var availableTags = JSON.parse(<?php include("/php/search_new.php"); ?>);
What is the problem? How can I figure out that?
If you need the php:
<?php
include 'db_connect.php';
session_start();
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 1200)) {
session_destroy();
session_unset();
}
else
{
$_SESSION['last_activity'] = time();
}
$arr = array('Data' => null,'Message' => null,'Code' => null);
$sql = "SELECT * FROM RECIPES";
$result = mysql_query($sql,$db) or exit("QUERY FAILED!");
while($row = mysql_fetch_array($result))
{
$arr['Data']['Recipes']['Recipe_'.$row['recipes_id']]['ID'] = $row['recipes_id'];
$arr['Data']['Recipes']['Recipe_'.$row['recipes_id']]['TITLE'] = $row['title'];
}
if($arr['Data'] == null)
{
$arr['Message']= "nothing found";
$arr['Code'] = 404;
}
else
{
$arr['Code'] = 200;
}
mysql_close($db);
echo json_encode($arr);
?>
You don't need to do a JSON.parse you can simply do
var availableTags = <?php include("/php/search_new.php"); ?>;
And name your php file as somename.php and make sure it is on some local or hosted server.
and you can see you data as,
alert(a['Data']["Recipes"]["Recipe_5"]["ID"]);

Categories

Resources