Create a custom selected list - javascript

Well im adding to database some records but i dont like the way i did and wanted to make something way easier for the user and better.
What i did was: http://i.imgur.com/AYrPyCn.jpg
And what i want is: http://i.imgur.com/aKNBTtO.jpg
Well i guess i know how to create the divs geting all the images from database and the horizontal scroll bar but what i dont know is when i select the image that id from image will appear on the input create by me.
Help needed.
Code from what i have:
<select name="id_artigo" id="attribute119">
<?php
do {
?>
<option value="<?php echo $row_artigos['id_artigo']?>" ><?php echo $row_artigos['id_artigo']?></option>
<?php
} while ($row_artigos = mysql_fetch_assoc($artigos));
?>
</select>
<div id="editimg"><p><img src="images/artigos/1.png" id="main" /></p></div>
Js:
$('#attribute119').change(function () {
$('#main').attr('src', 'images/artigos/' + $('#attribute119 :selected').text() + '.png');
});

You can use jQuery slideshow plugin like jcarousel or jssor.
Just do a google search on "jQuery slideshow" or "jQuery carousel".
I recommend you to use jcarousel.
Anas

Since you don't want it to look like a drop-down any more, replace the drop-down with a hidden field, which will hold the ID of the item they select:
<input type="hidden" name="id_artigo" />
(for testing you could use type="text" instead)
Give each of your images a data-id-artigo attribute:
<img class="artigo_img" src="images/artigos/1.png" data-id-artigo="1">
When an image is clicked, update the hidden ID's value:
$('.artigo_img').on('click', function() {
var idArtigo = $(this).data('idArtigo'); // get the artigo ID from the `data-` attribute
$('[name="id_artigo"]').val(idArtigo); // update the value of the hidden field
});
When the form is submitted, id_artigo will be equal to the selected item, just like before.

I see now that you just want to select 1 image, this answer is for selecting multiple images.
(not tested, so there might be some errors)
<style>
.img_holder
{
height:100px;
clear:both;
}
.floating_img
{
float:left;
width:100px;
height:100px;
}
.img_selected
{
border:1px solid black;
}
</style>
<div class="img_holder">
<?php
$img_id_arr = array();
do {
$selected = true; //<--implement if they are selected
$selected_class = '';
if($selected)
$img_id_arr[] = $row_artigos['id_artigo'];
$selected_class = ' img_selected';
}
?>
<div class="floating_img<?php echo $selected_class; ?>" onclick="toggle_img(<?php echo $row_artigos['id_artigo']; ?>);"><img src="images/artigos/<?php echo $row_artigos['id_artigo']; ?>.png" id="main" /></div>
<?php
} while ($row_artigos = mysql_fetch_assoc($artigos));
?>
<input typ="hidden" id="my_selected_images" name="my_selected_images" value="<?php echo implode(';',$img_id_arr); ?>">
<script>
function toggle_img(img_id)
{
var selected_imgs = $('#my_selected_images').value;
var img_arr = selected_imgs.split(";");
var found = false;
var new_arr = [];
for (i = 0; i < img_arr.length; i++) {
if(img_id == img_arr[i])
{
found = true;
//deselect img
}
else{
//leave other item untouched
new_arr.push(img_arr[i]);
}
}
if(!found)
{
new_arr.push(img_id);
//select img
}
$('#my_selected_images').value = new_arr.join(';');
}
</script>
</div>

Related

On any select option display only last inserted record

I have a little problem. I have a simple select field and get options from the database when the user clicks on any option I get an input box with the name of the last inserted record from the database, and I need to display the input box with the name of what the user selected not the last record. Code is bellow:
<div class="col-md-6 mb-3">
<label>Odaberite dimenziju produkta</label>
<select class="select2" name="size_id[]" multiple="multiple" id="selectBox" onchange="changeFunc();">
<?php
$get_sizes = "select * from sizes";
$sizes = mysqli_query($con,$get_sizes);
while($row_size = mysqli_fetch_array($sizes)){
$size_id = $row_size['id_size'];
$size_name = $row_size['productSize'];
$i++;
echo "<option value=".$size_name.">".$size_name."</option>";
} ?>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12 mb-3">
<div id="textboxcont" style="display: inline-flex; width: 100%;"></div>
<script type="text/javascript">
function changeFunc() {
document.getElementById('textboxcont').innerHTML = '';
var selectBox = document.getElementById("selectBox");
var selectedValues = Array.from(document.getElementById('selectBox').selectedOptions).map(el=>el.value);
//alert(selectedValues)
for( var i = 0; selectedValues.length > i; ++i ) {
var i1 = document.createElement("input");
i1.setAttribute("type", "text");
i1.setAttribute("name", "<?php echo $size_name; ?>");
i1.setAttribute("id", "<?php echo $size_name; ?>");
i1.setAttribute("placeholder", "Enter price for <?php echo $size_name; ?>");
i1.setAttribute("class", "form-control txtt");
// you may want to change this
// add the file and text to the div
document.getElementById('textboxcont').appendChild(i1);
}
}
</script>
</div>
I need when the user clicks on one of four available selected options to display selected inputs with different names. Now when users select any 1 or 2 or 3 available options they display only the last records from the database. Any help why?
You are having problem here..
for( var i = 0; selectedValues.length > i; ++i ) {
var i1 = document.createElement("input");
i1.setAttribute("type", "text");
i1.setAttribute("name", "<?php echo $size_name; ?>");
i1.setAttribute("id", "<?php echo $size_name; ?>");
i1.setAttribute("placeholder", "Enter price for <?php echo $size_name; ?>");
i1.setAttribute("class", "form-control txtt");
// you may want to change this
// add the file and text to the div
document.getElementById('textboxcont').appendChild(i1);
}
Your $size_name var contains last value of the query data array that you looped already while adding options to the select.
You should not use that to set attribute while creating input.
You should use the values that you have collected in selectedValues.
You can either itarate through it or use array index like selectedValues[ i ] to set input attribute like below.
function changeFunc() {
document.getElementById('textboxcont').innerHTML = '';
var selectBox = document.getElementById("selectBox");
var selectedValues = Array.from(document.getElementById('selectBox').selectedOptions).map(el=>el.value);
//alert(selectedValues[0]);
for( var i = 0; selectedValues.length > i; ++i ) {
var i1 = document.createElement("input");
i1.setAttribute("type", "text");
i1.setAttribute("name", selectedValues[i]);
i1.setAttribute("id", selectedValues[i]);
i1.setAttribute("placeholder", "Enter price for " + selectedValues[i] );
i1.setAttribute("class", "form-control txtt");
// you may want to change this
// add the file and text to the div
document.getElementById('textboxcont').appendChild(i1);
}
}

How do I make a standalone repeating jQuery function

I have been working on a filter function in jQuery for a simple unordered list. Each list is inside a block with a filter that can be modified in the back-end (Wordpress) to filter out specific strings. The filter also has a reset button to set it back to the original state.
Now I've been asked to make this a repeatable list. Repeating the list itself wasn't a problem but the filter now filters out items in all existing lists.
So the filter does work but it gets a bit overexcited filtering out all elements that have the class filter-list_item. I thought adding a number to the class on the parent div on each loop and then adding a for loop in jQuery to target these specific classes would fix this. Hence the $list_count and listCount variables. This however does the exact same thing and still affects all lists. I'm not sure why. Any help on how to make it so that the filters only filter out items in their corresponding lists would be much appreciated.
This is the current jQuery for the filter function:
$(document).ready(function (){
// Content filter
var lists = $(".filter-list").length;
for(var listCount = 0; listCount < lists; ) {
$(".filter-list-"+listCount).find(".content-filter").change(function() {
// Retrieve the option value and reset the count to zero
var search = $(this).val(), count = 0;
$(".filter-list_item").each(function(){
// Remove item if it does not match the value
var string = this.innerText;
var found = strSearch(search.toLowerCase(), string.toLowerCase());
if (found) {
$(this).css("display", "block");
// Show the list item if the value matches and increase the count by 1
count++;
} else {
$(this).css("display", "none");
}
// Show reset button
if($(this).index() > 0) {
$(".filter-reset").addClass("active");
}
});
// Update the count
if(count == 0) {
$(".filter-select-results").text("No results for " +search);
} else if(count > 0) {
$(".filter-select-results").text('');
}
});
// Reset filter
$(".filter-reset").click(function() {
$(".content-filter").prop('selectedIndex',0);
$(".filter-list_item").css("display", "block");
$(".filter-reset").removeClass("active");
$(".filter-select-results").text('');
});
listCount++;
}
});
// Search function
function strSearch(search, string) {
var n = string.search(search);
if(n >= 0) {
return true;
}
return false;
}
And this is the PHP used to build the lists
<?php
$list_count = 0;
foreach ($layout['list'] as $list) { ?>
<div class="container filter-list filter-list-<?php echo $list_count++; ?>">
<div class="title-wrapper">
<h2><?php echo $list['title']; ?></h2>
<?php echo $list['description'];
// Content filter
if($list['content_filter'] == true) { ?>
<div class="filter-container">
<button class="filter-reset"><i class="fa-icon fa fa-undo"></i></button>
<select class="content-filter" name="filterselect">
<option value="all" disabled selected>Selecteer een locatie</option>
<?php foreach($list['filter_options'] as $filter) { ?>
<option value="<?php echo $filter['option']; ?>"><?php echo $filter['option']; ?></option>
<?php } ?>
</select>
</div>
<?php } ?>
</div>
<div class="filter-select-results"></div>
<ul class="filter-list_items">
<?php foreach($list['list_items'] as $list_item) { ?>
<?php if( $list_item['link'] ) { ?>
<li class="filter-list_item"><?php echo $list_item['item']; ?></li>
<?php } else { ?>
<li class="filter-list_item">
<span><?php echo $list_item['item']; ?></span>
</li>
<?php } ?>
<?php } ?>
</ul>
</div>
Replace $(".filter-list_item").each(function(){ with $(this).closest(".filter-list").find(".filter-list_item").each(function(){
This is assuming .content-filter-element is part of a .filter-list. closest then navigates to the first parent satisfying the condition. Whether that condition holds is a bit unclear from the php code you showed.

img tag being added onto an already open img tag

Excuse the vague question title. Not entirely sure on how to word this.
Basically my issue stems from a bit of jquery in which when setting the data attr in the html the img tag shows some odd behavior as shown below.
<img src="images/gallery/
<img src="/images/gallery/bob.png" class="thumbnail" data="1">
" class="popupImage">
From what I am seeing is the class "popupImage" is not replacing the class "thumbnail" however the img tag nested in the outer img tag should be a seperate entity all together, my mind is baffled, and have been at this for hours and probably just need a new pair of eyes to look over it.
Any help would be greatly appreciated
This is the full html code and jQuery code for the gallery.
If I can provide anymore information who needs it please ask and I shall try and give some more where possible.
HTML
<?php
$data = $db->query("SELECT * FROM `gallery_items` ORDER BY id ASC");
//display query results
?>
<br /><br />
<?php
foreach($data as $item)
{
echo "<a data='".$item['id']."' class='noStyle'>
<img src='/images/gallery/".$item['image']."' class='thumbnail' data='".$item['id']."'>
</a>";
}
if(count($data) < 1){
echo "<p style='text-align: center;'><br /><br />No results found</p>";
}
?>
<div class="image">
<button class="prev" data="unset"><</button>
<img src='' class="popupImage">
<button class="next" data="unset">></button>
</div>
jQuery
$(".noStyle").click(function(){
loadPopup($(this).attr("data"));
});
offFocus();
function loadPopup(id){
imgSrc = "/images/gallery/"+$("a[data='"+id+"']").html();
$("div.background").fadeIn(400, function(){
$(".popupImage").attr("src", imgSrc);
$(".image").fadeIn(500);
reFocus();
setPrevNext($("button[data='"+id+"']"));
});
$(window).resize(function(){
reFocus();
});
function reFocus(){
$(".image").css({"left": (($(window).width()/2) - ($(".image").width()/2))+"px", "top": (($(window).height()/2) - ($(".image").height()/2))+"px"});
};
}/*close loadPopup */
function setPrevNext(buttonObj){
objects = $(".button");
firstObj = $(".button:first");
lastObj = $(".button:last");
prev = undefined;
next = undefined;
if(buttonObj.attr("data") == firstObj.attr("data"))
prev = lastObj;
else
prev = objects.eq(objects.index(buttonObj)-1);
if(buttonObj.attr("data") == lastObj.attr("data"))
next = firstObj;
else
next = objects.eq(objects.index(buttonObj)+1);
$(".prev").attr("data", prev.attr("data"));
$(".next").attr("data", next.attr("data"));
//next = buttonObj.next("button").attr("data");
//$(".next").attr("data", "next");
}
function offFocus() {
$(".background").click(function(){
$(".background").css({"display": "none"});
$(".image").css({"display": "none"});
});
};

Display array of products one by one by brand

I have a code in which i want to display product list from array.
I am getting around 1000 products from an array of n number of brands.n can be 1,2,3..etc.
I want to display 2 products of one brand then 2 products from second brand and then 2 from next brand and so on it should be repeated while displaying..
Homepage.php
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
#image{
width:250px;
height:250px;
border:1px solid black;
}
</style>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="brand"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
function get_disc_value(){
var d_value=[];
$('input[name="discount"]:checked').each(function () {
d_value.push(this.value);
});
return d_value.join(',');
}
$(document).ready(function(){
checkboxValidate = function (e) {
if(e)e.preventDefault();
//alert("hi");
//var os = $('#originState').val();
//var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
var disc=get_disc_value();
//var queryString = "os=" + os;
var data = "?ser=" + ser;
var queryString = "&ser=" + ser;
// alert(ser);
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: {ser:ser,disc:disc},
dataType : 'html',
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
}
$( "[type=checkbox]" ).change(checkboxValidate);
checkboxValidate();
});
</script>
brand
<input type="checkbox" name="brand" value="Sunbaby" id="check" />Sunbaby
<br/>
<input type="checkbox" name="brand" value="Advance Baby" id="check"/>Advance Baby
<br/>
store
<br/>
<input type="checkbox" name="discount" value="10" />10
<br/>
<input type="checkbox" name="discount" value="20" />20
<br/>
<input type="checkbox" name="discount" value="30" />30
<br/>
<button id="btnSubmit">sort</button>
<div id="image">
<img src="http://img5a.flixcart.com/image/sunglass/4/u/y/mb-d4-09b-miami-blues-free-size-275x275-imadzkhuchryqjgp.jpeg" width="250px" height="250px"/>
</div>
<div id="results">
sdfsdfsdfsdfdsfgsdgsbsfgvf
</div>
</body>
</html>
sortingajax.php
<?php
include('connection.php');
$query=$_POST['ser'];
$query2=$_POST['disc'];
$query=explode(",",$query);
$query = array_filter($query);
$query2=explode(",",$query2);
$query2 = array_filter($query2);
$result=count($query);
$result1=count($query1);
//echo $result;
echo $query;
echo $query1;
echo $result1;
$parts = array();
$brandarray=array();
$discarray=array();
$limit = 10;
$offset = 0;
foreach( $query as $queryword ){
$brandarray[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
foreach( $query2 as $discword ){
$discarray[] = '`DPERCENT` < "'.$discword.'"';
}
"/>
I want to display 2 products of one brand first and then 2 from second one and then from next brands.But according to above code it displays all products from one brand and then from next brand....Please guide me on how to change above code product list brand by brand..
based on a quick overview of your code, you seem to be adding the first element from each product to the array and then the second and then the third etc.. until you reach the highest count.
try instead, first limiting the max to only 2 instead of the max (so in this case, $highest_number should =2)
and second, add 1 brand, then the next then the next, instead of all at once, as unless you are handling it some other way would interlace each of the brands. I dont know if thats what you want?
does this help?
I've spent a little time looking at your code and am not entirely sure how it works. It seems like there's got to be an easier way to do this. Can you start a counter and cut off your loops once it hits the counter?
$i = 0;
$all_products = array();
while($row = mysql_fetch_array($firstsql3)) {
if (++$i <= 2) {
// DO YOUR STUFF HERE
$product_name = $row['product_name']; // GET THE PRODUCT NAME FROM THE DB
$product_color = $row['product_color'];
$product_size = $row['product_size'];
$individual_product_array = array(); // CREATE A NEW ARRAY FOR THIS PRODUCT
$individual_product_array['color'] = $product_color;
$individual_product_array['size'] = $product_size;
$all_products[$product_name][] = $individual_product_array;
}
}
If you insert _POST vars in mysql queries like this you will be hacked immediately see :
'`BRAND` LIKE "%'.$queryword.'%"';

how to change ids and name of cloned elements?

i make a select box and i used clone to make dynamic select boxes but my cloned select boxes ids and names are the same how to change ids and name of cloned elements?here is my code:
<script type="text/javascript">
( function($) {
// we can now rely on $ within the safety of our "bodyguard" function
$(document).ready( function() {
$('#add_button').on('click', function() {
var selectClone = $('#event_2').clone(true); // make a copy of select
$('#some_target').append(selectClone); // append to clone select
});
});
}) ( jQuery );
</script>
<?
$strQuery1="SELECT event_id,event_name from events";
$result1 = $GLOBALS ['mysqli']->query ($strQuery1) or die ($GLOBALS ['mysqli']->error . __LINE__);
?>
<select id="event_2" name="event_2">
<? while($ors1 = $result1->fetch_assoc()) {
echo '<option value="'.$ors1['event_id'] .'" >' . $ors1['event_name'] . '</option>';
}
?>
</select>
<button type="button" value="Add" id="add_button">Add Events</button><br />
<div id="some_target">
</div>
i want next cloned element has id and name event_3 and so on how i do this?
This will take care of everything:
$('#secondevent').clone().attr('id', 'newid').attr('name', 'newname').appendTo( "#some_target" );
clone, assign new id, assign new name and apppend to element #some_target.
Fiddle
var selectClone = $('#event_2').clone(true);
selectClone.attr({ id: 'event_3', name: 'event_3'});
$('#some_target').append(selectClone);
This should work just fine:
selectClone.attr('id', 'newValue')
Right after appending it to the new location.

Categories

Resources