How to make JavaScript dynamic? - javascript

I want to move document.getElementById("b") checked in a loop.Is it possible? How can I make it happen?
<img class="img-responsive pic" id="picture" src="images/step1.png">
<?php
//get rows query
$query = $db->query("SELECT * FROM `template_design` WHERE `panel` = 'front'");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$im_id = $row['id'];
$images = "images/" .$row['image']. "";
?>
<div class="col-md-4 col-sm-4 wel-grid wow fadeInDown">
<div class="wel11">
<input type="radio" id="<?php echo 'radio_'.$im_id; ?>" name="front" onClick="changeSrc(<?php echo $im_id; ?>)">
<label for="<?php echo 'radio_'.$im_id; ?>" style="font-size:12px; cursor: pointer;">
<img id="<?php echo 'picture_'.$im_id; ?>" style="border: 1px solid #ccc;" class="img-responsive" src="<?php echo $images; ?>"></label>
</div>
</div>
<?php } } ?>
<script type="text/javascript">
function changeSrc(id) {
if (document.getElementById("radio_"+id).checked) {
document.getElementById("picture_"+id).src = "images/Ppicture3.png";
}
}
</script>
I want to repeat it in a loop ,as fradio0 i.e $front will increment, JavaScript also repeat in a loop to match each.

You can pass parameters with your id for example:
<input type="radio" id="<?php echo 'radio_'.$im_id; ?>" name="<?php echo $fname; ?>" onClick="changeSrc(<?php echo $im_id; ?>)">
and use it on script like
<script type="text/javascript">
function changeSrc(id) {
if (document.getElementById("radio_"+id).checked) {
}
}
</script>

Please try this. Pass radio id as attr id & save each images by respective id's, followed by respective id.png. Also remove onclick function from your html code.
<script type="text/javascript">
$("input:radio[name=front]").click(function() {
var id= $(this).attr('id');
document.getElementById("picture").src = "panel/front/" + id + ".png";
});
</script>

Related

Cant access value from the HTML dataset

I am using Dataset to get some different values when doing drag and drop from one div to another. but I am not able to access the additional attributes such as data-customerId when I call the Javascript function.
HTML with PHP dynamic data:
<fieldset id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
<legend style="color:cadetblue; border:white; width:auto; font:bold">Vacant parking spots</legend>
<?php $counter = 0; foreach ($sql_get_vacant_spots_results_ as $row) { ?>
<div id="<?php echo $counter; ?>" data-customerid="<?php echo $arr_users[0]['customer_id']; ?>" data-y="<?php echo $row['spot_no'] ?>" data-z="<?php echo $row['location_id'] ?>" style="float: left; width: 120px;height: 80px;padding: 10px;border-radius: 20px;margin: 10px;background-color: cadetblue;" draggable="true" ondragstart="drag(event)" width="88" height="31">
<labled style="color: white; font:bold; font-size:large;"><?php echo 'Spot: ' . $row['spot_no'] . ' Gate: ' . $row['parking_gate_id'] ?></label>
</div>
<?php $counter++; } ?>
</fieldset>
<fieldset id="div2" ondrop="drop(event)" ondragover="allowDrop(event)">
<legend style="color:cadetblue; border:white; width:auto; font:bold">Current parking spots of the customer</legend>
<?php $count = 0; foreach ($arr_users as $user) { ?>
<div id="<?php echo $count ?>" data-customerid="<?php echo $user['customer_id'] ?>" data-y="<?php echo $user['spot_id'] ?>" data-z="<?php echo $user['location_id'] ?>" style="float: left; width: 120px;height: 80px;padding: 10px;border-radius: 20px;margin: 10px;background-color: cadetblue;" draggable="true" width="88" height="31">
<labled style="color: white; font:bold; font-size:large;"><?php echo 'Spot: ' . $user['spot_id'] . ' Gate: ' . $user['gate_id'] ?></label>
</div>
<?php $count++; } ?>
</fieldset>
And here is the Javascript:
function drop(ev) {
const el = document.querySelector('#' +ev.dataTransfer.getData("text")); //prints: Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#33' is not a valid selector.
console.log('drop', el.dataset.customerid);
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
Fixed by accessing the id like this:
const el = document.querySelector("[id=" + "\'" + ev.dataTransfer.getData("text") + "\'" + "]");
EDIT:
Html element id:
id="count_id<?php echo $counter; ?>"

post jquery array to php page when checking checkboxes

i have dynamic number of checkboxes and a button to post the checked elements to another page .. here is the code:
<div class="overSelect"></div>
<div id="checkboxes<?php echo $aa['id']; ?>">
<?php
$pid = select::property($aa['name']);
$arr2 = select::properties($pid);
$cc = 1;
foreach ($arr2 as $aa2) { ?>
<div style="padding-right: 20px" class="row"><label>
<input type="checkbox" value="<?php echo $aa2['name'] ?>" name="checks<?php echo $aa['id'] ?>[]"id="check<?php echo $aa['id']; ?>"><?php echo $aa2['name'] ?>
</label></div>
<?php } ?>
</div>
<a class="btn btn-primary btn-sm" name="update-all"onclick="update_all('prop_id<?php echo $aa['id']; ?><?php $counter; ?>','checks<?php echo $aa['id'] ?>')"id="btn-all<?php echo $aa['id']; ?><?php $counter; ?><?php echo $p['id']; ?>">save</a>
i tried this code but it is not working
<script type="text/javascript">
function update_all(a, b) {
var aa = document.getElementById(a).value;
var values = new Array();
$("input:checkbox[name=b]").each(function () {
if ($(this).is(":checked")){
values.push($(this).val());
}
});
alert(aa);
alert(values.length);
alert(values);
}
</script>
if the checkboxes checked .. it's value will be added to the array and posted to php page
any help please .. thanks in advance

How to show check box text if it is not next to check box using jQuery

I am trying to achieve checked value text should visible like shown in the image:
Without refresh or any click can anyone help me out?
This is my php dynamic from :
<div class="products-row">
<?php $tq=$conn->query("select * from os_tiffen where tiffen_status=1 order by id_tiffen ASC");
while ($tiffen = $tq->fetch_assoc()) {
?>
<div class="col-md-3">
<div class="foodmenuform row text-center">
<input multiple="multiple" type="checkbox" id="<?php echo $tiffen['tiffen_image']; ?>" name="tifeen" hidden>
<label for="<?php echo $tiffen['tiffen_image'];?>"><img src="img/tiffen/<?php echo $tiffen['tiffen_image']; ?>" class="img img-responsive" /></label>
<h3 class="FoodName"><?php echo $tiffen['tiffen_name'];?></h3>
</div>
</div>
<?php } ?>
</div>
This is my script to show the text:
<script type="text/javascript" language="JavaScript">
$( document ).ready(function() {
var FoodMenu = $('input[type=checkbox]:checked').map(function(){
return $(this).next('.FoodName').text();
}).get().join("<br>");
$("#selectedfood").html(FoodMenu);
});
</script>
Out put id: <a id="selectedfood"></a></li>
You could try to get all checked options’ text on checkbox change event and append selected values to “selectedfood”. The following sample code is for your reference.
<script>
$(function () {
$(".foodmenuform [type='checkbox']").change(function () {
var FoodMenu = "";
var ischecked = $(".foodmenuform [type='checkbox']:checked").each(function () {
FoodMenu += $(this).siblings(".FoodName").text() + "<br/>";
})
$("#selectedfood").html(FoodMenu);
})
})
</script>
Its easier thank i thought:
var checkedFood = $('input[type=checkbox]:checked').map(function(){
//console.log($('input[type=checkbox]:checked').serialize());
return $(this).val();
}).get().join("<br>");
$("#selectedfood").html(checkedFood);
Form:
<div class="products-row">
<?php $tq=$conn->query("select * from os_tiffen where tiffen_status=1 order by id_tiffen ASC");
while ($tiffen = $tq->fetch_assoc()) {
?>
<div class="col-md-3">
<div class="foodmenuform row text-center">
<input type="checkbox" id="<?php echo $tiffen['id_tiffen'];?>" class="Foodmenu" value="<?php echo $tiffen['tiffen_name'];?>" name="tifeen[]" hidden>
<label for="<?php echo $tiffen['id_tiffen'];?>"><img src="img/tiffen/<?php echo $tiffen['tiffen_image']; ?>" class="img img-responsive" /></label>
<h3><?php echo $tiffen['tiffen_name'];?></h3>
</div>
</div>
<?php } ?>
</div>

Magento Product pag - displaying related products that are out of stock

I'm not too experienced in PHP but my goal here is to have related product swatches not display on the page if they are out of stock.(highlighted in screenshot)
Related product swatches are highlighted
Here is the PHP code:
<ol class="mini-products-list" id="block-related">
<?php foreach($this->getItems() as $_item): ?>
<li class="item">
<?php if(!$_item->isComposite() && $_item->isSaleable()): ?>
<?php if (!$_item->getRequiredOptions()): ?>
<input type="checkbox" class="checkbox related-checkbox" id="related-checkbox<?php echo $_item->getId() ?>" name="related_products[]" value="<?php echo $_item->getId() ?>" />
<?php endif; ?>
<?php endif; ?>
<div class="product">
<img src="<?php echo $this->helper('catalog/image')->init($_item, 'thumbnail')->resize(50) ?>" width="50" height="50" alt="<?php echo $this->escapeHtml($_item->getName()) ?>" />
<div class="product-details">
<p class="product-name"><?php echo $this->escapeHtml($_item->getName()) ?></p>
<?php echo $this->getPriceHtml($_item, true, '-related') ?>
<?php if ($this->helper('wishlist')->isAllow()) : ?>
<?php echo $this->__('Add to Wishlist') ?>
<?php endif; ?>
</div>
</div>
</li>
<?php endforeach ?>
</ol>
And here is the related jQuery/JS:
<script type="text/javascript">
//<![CDATA[
$$('.related-checkbox').each(function(elem){
Event.observe(elem, 'click', addRelatedToProduct)
});
var relatedProductsCheckFlag = false;
function selectAllRelated(txt){
if (relatedProductsCheckFlag == false) {
$$('.related-checkbox').each(function(elem){
elem.checked = true;
});
relatedProductsCheckFlag = true;
txt.innerHTML="<?php echo $this->__('unselect all') ?>";
} else {
$$('.related-checkbox').each(function(elem){
elem.checked = false;
});
relatedProductsCheckFlag = false;
txt.innerHTML="<?php echo $this->__('select all') ?>";
}
addRelatedToProduct();
}
function addRelatedToProduct(){
var checkboxes = $$('.related-checkbox');
var values = [];
for(var i=0;i<checkboxes.length;i++){
if(checkboxes[i].checked) values.push(checkboxes[i].value);
}
if($('related-products-field')){
$('related-products-field').value = values.join(',');
}
}
//]]>
</script>
Any help would be appreciated, thank you!
Are you sure that you have the option Display out of stock products set to No? (System -> Configuration -> Inventory)
You can also try to add $_item->isAvailable() to if statement.
The Solution I ended up going with: adding $_item->isAvailable() to if statement gives the desired effect of related products that are out of stock will not display as a related product swatch on the product page.

Auto calculation of div values on blur

I am generating a table of divs from mysql database with code as below :
<?php
$sql = "SELECT * FROM menuitem";
$result = mysql_query($sql); $i =1;
while ($row = mysql_fetch_array($result)) {?>
<div class="orderblock">
<div class="orderlist">
<div class="pimage">
<p></p>
</div>
<div class="pdesc">
<p><?php echo $row['prodname']; ?></p>
<p><?php echo substr($row['proddesc'], 0, 20); ?></p>
</div>
<div class="portion">
<input type="text" onblur="document.getElementById('tot<?php echo $i;?>').value=document.getElementById('por<?php echo $i;?>').value * document.getElementById('pri<?php echo $i;?>').value;" id="por<?php echo $i;?>" name="<?php echo $row['prodname']; ?>" >
</div>
<div class="price">
<p id="pri<?php echo $i;?>"><?php echo $row['price']; ?></p>
</div>
<div class="total">
<p><input style="border: none;" type="text" id="tot<?php echo $i;?>" disabled="disabled" value=""> </p>
</div>
</div>
</div>
<?php $i++; }
?>
this is my final code, finally I got it working but I am getting NaN as result could any please sort it for me.
thanks
Try this now. Before try this remove your blur event from html.I hope this will help you.
$(document).ready(function () {
$("input[type=text]").blur(function () {
var portion = $(this).val();
var price = $(this).parent().parent().find(".price p").text();
if(isNaN(portion)==false)
{
var tot = portion * price;
$(this).parent().parent().find(".total p input").val(tot);
}
else
{
$(this).parent().parent().find(".total p input").val(0);
}
});
});
Demo here

Categories