On any select option display only last inserted record - javascript

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);
}
}

Related

Extract multiple values from a MySQL table into HTML

I want to get three values from a MYSQL table, and display them in a text area. I can get only one value. If it possible, I want to save this selector, because it is critical to my program.
JavaScript:
function getsteel() {
var material = document.getElementsByName("option");
if (material[3].checked == true) {
var g = document.getElementById("selector1");
var str = g.options[g.selectedIndex].value;
document.getElementById('kr').value = str;
}
}
HTML:
<td>k<sub>r</td></sub>
<td>
<input type="text" id="kr" disabled style="width:50px;">
</td>
<td>[MPa]</td>
PHP:
<?php
mysql_connect("localhost","root","");
mysql_select_db("db-user22777");
//query
$sql=mysql_query("SELECT * FROM steels ORDER BY id ASC");
if(mysql_num_rows($sql)){
$select= '<select id="selector1" disabled size="12">';
while($r=mysql_fetch_array($sql)){
$select.='<option value="'.$r['kr'].'">'.$r['Steelname'].' | '.$r['kr'].' [MPa]</option>';
}
}
$select.='</select>';
echo $select;
?>
Thanks for any help provided!

Populate select box from database query based on another select box using only 1 table

Hi guys I am currently creating a website with the main function of booking cars. Therefore the user would be first able to select a car category from the database query which will output the selected car category names. After selecting the car category name, the second select box would then by dynamically updated with a new set of of car names that are associated with the category.
There may have been many similar questions to this however for the website NO jQuery or AJAX can be utilized. And other questions and examples often utilize 2 or more tables however I am using only 1 table for this function.
The example below should show how the Select box should be updated:
Dynamically updated select box.
The table utilized is this:
Table Utilized
My codes are as such:
<?php
session_start();
include "dbconn.php";
$query = "SELECT carid, brand FROM cars";
$result = $dbcnx->query($query);
while($row = $result->fetch_assoc()){
$subcats[] = array("id" => $row['carid'], "val" => $row['brand']);
}
$jsonSubCats = json_encode($subcats);
?>
<!docytpe html>
<html>
<head>
<script type='text/javascript'>
<?php
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
</head>
<body onload='loadCategories()'>
Car Category:<br />
<select size="1" name="categoriesSelect" id="categoriesSelect">
<option> Select Car Category </option>
<option value="sedan"> Sedan </option>
<option value="mpv"> MPV </option>
<option value="hatch"> Hatchback </option>
</select><br /><br />
Car Brand:<br />
<select id='subcatsSelect'>
</select>
</body>
</html>
I may have identified the error to the php statement:
while($row = $result->fetch_assoc()){
$subcats[] = array("id" => $row['carid'], "val" => $row['brand']);
As I can only see the first select box query correctly consisting of the 3 car category of MPV, Sedan and Hatchback.
Currently the all the Car Brand name appears however the results do not correspond with the car category as shown in the database.
Thank You.
As both arrays in PHP follow the same pattern when created the json data will be similar also thus the method to traverse the data should follow that in loadCategories function - so perhaps this:
function updateSubCats(){
var oSelect = document.getElementById("subcatsSelect");
oSelect.options.length = 0;
for( var i in subcats ){
oSelect.options[ i ]=new Option( subcats[ i ].val, subcats[ i ].id );
}
}
Without using Ajax or over complicating things with complex json iteration you could try along these lines. It should be noted that embedding the $_GET variable directly in the sql is not the best option - prepared statements would be better but should give the idea.
<?php
session_start();
include "dbconn.php";
?>
<!docytpe html>
<html>
<head>
<title>Chained select</title>
<script type='text/javascript'>
function bindEvents(){
document.getElementById('categories').addEventListener( 'change', getSubcategories, false );
}
function getSubcategories(e){
var el=e.target ? e.target : e.srcElement;
var value=el.options[ el.options.selectedIndex ].value;
location.search='?category='+value;
}
document.addEventListener( 'DOMContentLoaded', bindEvents, false );
</script>
</head>
<body>
<form>
<select id='categories'>
<?php
$query = "SELECT carcat FROM cars";
$result = $dbcnx->query($query);
while( $row = $result->fetch_assoc() ){
echo "<option value='{$cat['carcat']}'>{$cat['carcat']}";
}
?>
</select>
<select id='subcategories'>
<?php
if( !empty( $_GET['category'] ) ){
$sql = "SELECT carid, brand FROM cars where carcat='{$_GET['category']}';";
$result = $dbcnx->query( $sql );
if( $result ){
while( $row = $result->fetch_assoc() ){
echo "<option value='{$row['carid']}'>{$row['brand']}";
}
}
}
?>
</select>
</form>
</body>
</html>
Of course it won't, you're accessing your arrays wrong:
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
^^^^^ ^^^^^
Your subcats array is only 2-dimensional, yet you're accessing it as a 3-dimentional array here.

Creating multiple select populated by js array

Ok this is a bit complicated. Basically I populate a select with an array. Then, I want to create another select, and populate it with the same array again. I believe that the populate function is not called properly when a new select is created, but I cannot find when to call it, to populate the created select.
1st: I query my db to get some member names, and use json_encode my resulting array, to create a json array.
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
$json_array = json_encode($result_array);
then I echo that array to a javascript array, and populate a select tag with the result. All this happens on window load.
<script>
var members = <?php echo $json_array; ?>;
function populate()
{
var sel = document.getElementById('members');
var fragment = document.createDocumentFragment();
members.forEach(function(member, index) {
var opt = document.createElement('option');
opt.innerHTML = member;
opt.value = member;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
}
window.onload = populate;
</script>
The html div containing the select:
<div id="Members">
<select id="members"></select>
</div>
<input type="button" value="+" onClick="addInput('Members'); populate();">
and then I use another script to create more divs
<script>
var counter = 1;
var limit = 3;
function addInput(divName)
{
if (counter == limit)
{
var message = document.getElementById("linkLimit");
message.innerHTML = "Maximum amount of links reached";
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML = "<select id='members'></select>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
However, the resulting selects are never actually populated. I believe that the populate function is not called properly, but I cannot find when to call it, to populate the created select.
Alternatively, for a static amount of select inputs, I tried doing
<div id="Members">
<select id="members" name="members"></select>
<select id="members1" name="members"></select>
<select id="members2" name="members"></select>
</div>
but again, only the first select is populated
By using a for loop and giving members, members1, members2 through an array, all three lists are populated, however, this is not so functional, since I can't know how many members the user will want to select

Create a custom selected list

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>

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.'%"';

Categories

Resources