I'm trying to create a dynamic funktion in jQuery, which handles onchange event for a select (dropdown) and updates to other text fields with some calculated values.
But I'm having some trouble with.
My select is like this
<select name="r514b" id="r514b" size="1" class="listform" style="width: 155px;"> <option value="0">Vælg overfladebehandling</option> <?php while($farverow = mysql_fetch_array($farvequery, MYSQL_ASSOC)) { if ($res['r514b'] == $farverow['id']) {
$r514bselected = "selected";
} else {
$r514bselected = "";
}?> <option value="<?php echo $farverow['id']; ?>" <?php echo $r514bselected; ?> data-nypris="<?php echo $farverow['pris']; ?>" data-grundpris="<?php echo $farvegrundrow['pris']; ?>" data-sumvaegt="<?php echo $res['r477']; ?>" data-db="<?php echo $res['r502']; ?>"><?php echo $farverow['navn']; ?></option> <?php } ?> </select>
and the jQuery is like:
$('#r514b').change(function(){
var ny_pris = $(this).find(':selected').data('nypris');
var grundpris = $(this).find(':selected').data('grundpris');
var sumVaegt = $(this).find(':selected').data('sumvaegt');
var db = $(this).find(':selected').data('db')
var overflade_forskel = ny_pris - grundpris;
// alert(ny_pris);
// alert(grundpris);
// alert(sumVaegt); // * overflade_forskel);
var pris_forskel = (sumVaegt * overflade_forskel)/(1-(ds.r502.value/100));
// alert(pris_forskel);
ds.id514d.value = Math.round(pris_forskel);
ds.r514d.value = Math.round(pris_forskel);
});
The reason I want to make it dynamical is that I need to have multiple selects, which basically does the same thing. Only difference is which text fields they update.
So I was hoping that I somehow to make the function catch the selects dynamic, and update the fields dynamic maybe from some extra data attributes on the selects.
But how do I do that?
Related
The result of dropdownlist is did not match what I wanted the data that has been selected. I would like to know how to pass the jquery or javascript variable to php or that is another to way to match the dropdownlist data?
function editbtn(id){
$('#employee_id_edit').val(id);
var invoice_id = $('#user-user-list').find("#row_"+id).find("td:eq(1)").text();
var payment_id = $('#user-user-list').find("#row_"+id).find("td:eq(2)").text();
var category = $('#user-user-list').find("#row_"+id).find("td:eq(3)").text();
var sale_person = $('#user-user-list').find("#row_"+id).find("td:eq(4)").text();
var amount = $('#user-user-list').find("#row_"+id).find("td:eq(5)").text();
$('#invoice_id_edit').val(invoice_id);
$('#payment_id_edit').val(payment_id);
$('#product_type_edit').val(category);
$('#employee_edit').val(sale_person);
$('#amount_edit').val(amount);
}
<label for="employee">Sale Person</label>
<select id="employee_edit" name="employee_edit" class="form-control" autocomplete="off">
<?php
$employee_model = $registry->get('loader')->model('user');
$employee = $employee_model->getEmployee();
if(null !== $employee) {
foreach ($employee as $employee) {
?>
<option value="<?php echo $employee['username'];?>" selected><?php echo $employee['username']; ?></option>
<?php
}
} else {
?>
<option>No Employee Available</option>
<?php
}
?>
</select>
I think you should use jquery plugins like 'jquery select2'(https://select2.org/) or create some custom ajax request to send data from js to PHP backend and then get and handle a response from js part.
I'm trying to dynamically generate radio buttons with data in front of them. The data that is to be displayed in front of the radio button is based on a drop down selection, which also displays some data in a text box using javascript.
I tried taking the selected option in a string and use it in the next query, but I know I am doing it wrong.
Database Connection
$db = pg_connect("");
$query = "select account_name,account_code,address1,address2,address3 FROM
customers";
$result = pg_query($db,$query);
//NEW QUERY
$sql1= "select name from conferences";
$result1= pg_query($db, $sql1);
//END
//New Code
<select class="form-control" id="conference" name="conference">
<option value="">Select Conference...</option>
<?php while($rows1 = pg_fetch_assoc($result1)) { ?>
<option value="<?= $rows1['code']; ?>"><?= $rows1['name']; ?></option>
<?php } ?>
</select>
<br>
// END OF NEW CODE
Dropdown to select the data.
<select onchange="ChooseContact(this)" class="form-control"
id="account_name" name="account_name" >
<?php
while($rows= pg_fetch_assoc($result)){
echo '<option value=" '.$rows['address1'].' '.$rows['address2'].'
'.$rows['address3'].''.$rows['account_code'].'">'.$rows['account_name'].'
'.$_POST[$rows['account_code']].'
</option>';
}?>
</select>
Displaying data in the text area based on the selcted value using javascript. (The code works fine till here)
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;"value=""placeholder="Address...">
</textarea>
<script>
function ChooseContact(data) {
document.getElementById ("comment").value = data.value;
}
</script>
Displaying data in front of the radio buttons based on the selected option(This code works if I use some random value in the query, but not if I use the selected value 'account_code' from the previous query. I'm using POST GET method to carry the selected value)
<?php
//NEW CODE
$sql = "select order_number, order_date from orders where
customer_account_code = '3000614' and conference_code='DS19-'"; <-Data
gets displayed when put random value like this.
$code = $_GET[$rows['account_code']];
$conf = $_GET[$rows1['conference_code']];
$sql = "select order_number, order_date from orders where
customer_account_code = '$code' and conference_code= '$conf']"; <- But I
want to display the data against the selected value, i.e, the 'account_code'
in the variable $code from the dropdown select
//END
$res = pg_query($db,$sql);
while($value = pg_fetch_assoc($res) ){
echo "<input type='radio' name='answer'
value='".$value['order_number']." ".$value['order_date']."'>"
.$value['order_number'].$value['order_date']." </input><br />";
}
?>
I need to help to find a way to put the selected 'account_code' in a variable and use it in the $sql query.
Please try with this code : (It's work for me)
1- Add this line to your HTML <head>:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
2- Edit your CODE to this:
Dropdown to select the data:
<select class="form-control" id="account_name" name="account_name">
<option value=""></option>
<?php while($rows = pg_fetch_assoc($result)) { ?>
<option value="<?= $rows['address1'].' '.$rows['address2'].' '.$rows['address3'].'-'.$rows['account_code']; ?>"><?= $rows['account_name']; ?></option>
<? } ?>
</select>
Displaying data in the text area based on the selected value using jQuery:
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;" value="" placeholder="Address..."></textarea>
jQuery Code:
<script type="text/javascript">
$('#comment').val($('#account_name').val()); // MAKE A DEFAULT VALUE
(function($) {
$('#account_name').change(function() {
$('#results').html(''); // REMOVE THE OLD RESULTS
var option = $(this).val();
$('#comment').val(option);
// EDIT RADIO WITH AJAX
$.ajax({
type: "POST",
url: "path/test.php",
dataType:'JSON',
data: $('#account_name').serialize()
}).done(function(data) {
for (var i = 0; i < data.length; i++) {
// ADD RADIO TO DIV RESULTS
$('#results').append('<input type="radio" name="answer" value="'+data[i].order_number+'">'+data[i].order_date+'</input><br>');
}
});
});
})(jQuery);
</script>
after that, add this HTML to your page, to show RESULTS FROM AJAX DATA
<!-- RADIOs -->
<div id="results"></div>
3- Create a new file like path/test.php
in this file, use this CODE to return values with JSON :)
<?php
header('Content-type: application/json');
// CONNECT (JUST USE YOUR CUSTOM CONNECTION METHOD & REQUIRE CONFIG FILE IF YOU WANT)
$db = pg_connect("");
$value = explode('-', $_POST['account_name']);
// EXPLODE AND GET LAST NUMBER AFTER < - >
$code = (int) end($value);
$sql = "select order_number, order_date from orders where customer_account_code = '$code'";
$res = pg_query($db, $sql);
// CREATE JSON RESULTS
$is = '';
while($data = pg_fetch_assoc($res)) {
$is .= json_encode($data).', ';
}
// AND GET ALL
echo '['.substr($is, 0, -2).']';
?>
<select>
<?php foreach($result as $city) { ?>
<option value="<?php echo $city->city_name; ?>" <?php if( strtolower($this->session->city) == strtolower($city->city_name) ) { echo "selected"; } ?>
> <?php echo $city->city_name; ?> </option>
<?php } ?>
</select>
Hi i am trying to auto select drop down box with the help of session but i am not able to select please some one help me out how could i auto select drop down box.
First of all. You should always provide the whole code, eg. in format of PHPFiddle.
Secondly, you should not mix HTML and PHP.
Also your problem cannot be deciphered from your question, because there might be several reasons. Like the city name could be in uppercase or capitalized in your session variable.
Your session variable might not be initialized with your session in the class constructor.
Also you might even not have a class at all, so the reference to $this would be obsolete.
But those aside, here's a code that might help you:
<?php
class MockSession {
function __construct() {
}
}
class Foo {
function __construct() {
$this->session = new MockSession();
$this->session->city = "Helsinki";
}
function printSelect() {
$result = array("London","New York","Helsinki");
echo '<select>';
foreach ($result as $city) {
$sel = '';
echo $city." ".$this->session->city;
if (strtolower($city)==strtolower($this->session->city)) {
$sel = ' selected="selected" ';
}
echo '<option value="'.$city.'" '.$sel.'>'.$city.'</option>';
}
echo '</select>';
}
}
$foo = new Foo();
$foo->printSelect();
?>
If you got value of your session on the page then you have to just modify your code as selected="selected". See updated code:
<select>
<?php
foreach ($result as $city) {
?>
<option
value="<?php echo $city->city_name; ?>"
<?php if (strtolower($this->session->city) == strtolower($city->city_name)) {
echo 'selected="selected"';
}
?>>
<?php echo $city->city_name; ?>
</option>
<?php
}
?>
</select>
But you should have to confirm first that you got value of $this->session->city.
I am trying to create a filter for a gallery that I've created. The gallery has 5 filters using dropdown menu's. When a item is selected from one of the 5 filters it has to filter the images. When a second filter is selected it has to filter the results of the first filter and so on.
I am using the onchange='this.form.submit()' script but I don't know how to assign a certain action to it when an item is selected. This is my code at the moment of writing:
<td>
Kleur:
<form method="POST">
<select name="kleur" onchange='this.form.submit()'>
<option> -- Geen optie -- </option>
<?php while ($line1 = mysqli_fetch_array($result1, MYSQLI_ASSOC)) { ?>
<option value="<?php echo $line1['kleur']; ?>"> <?php echo $line1['kleur']; ?>
</option>
<?php } ?>
</select>
</form>
<?php
if (isset($_POST['submit'])) {
$kleur = $_POST['kleur'];
$SQL = "SELECT * FROM `rozen` WHERE `kleur` LIKE '$kleur'";
$result = mysqli_query($connection, $sql);
echo $result;
}
?>
</br>
</td>
The following part doesn't seem to work:
<?php
if (isset($_POST['submit'])) {
$kleur = $_POST['kleur'];
$SQL = "SELECT * FROM `rozen` WHERE `kleur` LIKE '$kleur'";
$result = mysqli_query($connection, $sql);
echo $result;
}
?>
Does anyone know how to use this script? and perhaps explain how to save the selected item in the dropdown menu too?
You can add an attribute with all the information you need to filter to your images
<img filterInfo="Kleur|Geur|Bloemvorm|Gezondheid|Type|Zoeken">
then set a class for all your filters to catch the changes
$(".filters").on("change",function(){
var kleur = $('[name=Kleur]').val();
var Geur = $('[name=Geur]').val();
...
...
...
$.each($('#gallery img'),function(i,v){
var attrs = $(v).attr("filterInfo").slice("|");
if((kleur == "" || kleur == attrs[0]) && (Geur == "" || == attrs[1]) .... other filters)
$(this).show(); //or fadeIn();
else
$(this).hide(); //or fadeOut();
});
});
I am stuck on a code where I want to fetch data from MySQL into an array.. I have a form containing color and size select boxes, an onclick javascript function is triggered and it created two more select boxes like above, I have managed to get data into the javascript code where the code for creating new select boxes is written.
But I am only getting the last inserted record from both the tables. Although I have used a while loop.
Can someone help me out and I am also getting name of all select boxes likes name="color[]" , I want to insert records into a bridge table containing ids of color and size. below is my code please help ..
I will clear it up , each time I click add more button it should create 2 new dropdown lists, one for color and 2nd for size, both dropdowns should have the distinct data from database. so the ids for each record would be same in every dropdown list, I want to add more than 1 records in bridge table which contains product_id,color_id and size_id, so if I go for 3 dropwdown boxes , and i select blue color and small size in the first, then for second dropdown i again select blue color and size medium, as for the last dropdown which was also generated by the javascript function . i choose black color and large size. so from the dropdown it will get ids of size,color and it would be inserted accordingly.. so when i display the product and color blue is selected i would only see the sizes which were added to the color blue at the time of adding the product.. i hope this clears everything :)
$result=mysql_query("SELECT * FROM color,size");
while($row=mysql_fetch_array($result)) {
?>
<script>
var room = 1;
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '<div class="label">Room ' + room + ':</div><div class="content"><span>Color: <select name="color[]"><option value="<?php echo $row['color_id']; ?>"><?php echo $row['color']; ?></option></select></span><span>Size: <select><option value="<?php echo $row['size_id']; ?>"><?php echo $row['size']; ?></option></select></span></div>';
objTo.appendChild(divtest)
}
</script>
<?php
}
HTML code
<div id="room_fileds">
<div>
<div class='label'></div>
<div class="content">
<input type="button" class="btn btn-success" id="more_fields" onclick="add_fields();" value="Add More" /> <br /><br />
<select name="color[]" class="form-control">
<option value="0">Select Color</option>
<?php
$result=mysql_query("SELECT * FROM color");
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['color_id'] ?>"><?php echo $row['color']; ?></option>
<?php } ?>
</select>
<select name="size[]" class="form-control">
<option value="0">Select Size</option>
<?php
$result=mysql_query("SELECT * FROM size");
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['size_id'] ?>"><?php echo $row['size']; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
Replace your first code with the following:
<script>
var colors = [];
var sizes = [];
var room = 1;
<?php
$result = mysql_query("SELECT * FROM color");
while ($row = mysql_fetch_array($result)) { ?>
colors.push(['<?php echo $row['color_id'] ?>', '<?php echo $row['color'] ?>']);
<?php }
$result = mysql_query("SELECT * FROM size");
while ($row = mysql_fetch_array($result)) { ?>
sizes.push(['<?php echo $row['size_id'] ?>', '<?php echo $row['size'] ?>']);
<?php } ?>
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds');
var divtest = document.createElement("div");
var html = '<div class="label">Room ' + room + ':</div><div class="content"><span>Color: <select name="color[]" class="form-control">';
for (i = 0; i < colors.length; i++) {
html += '<option value="' + colors[i][0] + '">' + colors[i][1] + '</option>';
}
html += '</select></span><span>Size: <select name="size[]" class="form-control">';
for (i = 0; i < sizes.length; i++) {
html += '<option value="' + sizes[i][0] + '">' + sizes[i][1] + '</option>';
}
html += '</select></span></div>';
divtest.innerHTML = html;
objTo.appendChild(divtest);
room++;
}
</script>
$divs='';
$result=mysql_query("SELECT * FROM color,size");
$room=1;
while($row=mysql_fetch_array($result)) {
$divs.='<div><div class="label">Room ' . $room . ':</div><div class="content"><span>Color: <select name="color[]"><option value="'.$row['color_id'].'">'.$row['color'].'</option></select></span><span>Size: <select><option value="'.$row['size_id'].'">'.$row['size'].'</option></select></span></div></div>';
$room++;
} ?>
<script>
function add_fields() {
var objTo = document.getElementById('room_fileds');
objTo.appendChild(<?php echo $divs; ?>);
}
</script>
Try this code hope it works for you
<script>
var room = 1;
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds');
var divtest = document.createElement("div");
<?php
$div_start='<div class="label">Room '."'+ room +'".' :</div><div class="content">';
$color='<span>Color: <select name="color[]">';
$size='<span>Size: <select>'
$result=mysql_query("SELECT * FROM color,size");
while($row=mysql_fetch_array($result)) {
$color.='<option value="'.$row['color_id'].'">'.$row['color'].'</option>';
$size.='<option value="'.$row['size_id'].'">'.$row['size']'.</option>';
}
$color.='</select> </span>';
$size.='</select> </span>';
$div_close='</div>';
$innerHTML=$div_start.$color.$size.$div_close;
?>
divtest.innerHTML ='<?php echo $innerHTML; ?>';
objTo.appendChild(divtest);
}
</script>
This is the final code , it would help if anyone wants to code a similar thing.. just change values and it would work as per your need... and i would like to thank all people who replied to the thread and specially Mohammad Anini .. it wouldnt have been possible without his help !!!
$query = mysql_query("INSERT INTO products (product_name,product_description, product_pic1, product_pic2, product_pic3,product_price,category_id,subcategory_id,product_status,color,size,product_slug, meta_keywords,entrydate)
VALUES ('$product', '$description' , '$image', '$image2', '$image3', '$product_price', '$category', '$subcategory', '$product_status', '$capture_field_vals', '$size', '$product_slug1', '$meta_keywords', Now() )") or die(mysql_error());
if ($query === TRUE) {
$lastid = mysql_insert_id();
$color["color"]=array();
$size["size"]=array();
foreach ($_POST['color'] as $key => $colorvalue) {
}
foreach ($_POST['size'] as $key => $sizevalue) {
}
$cid=array();
foreach($color as $rec){
$cid[]=$rec;
}
$sz=array();
foreach($size as $rec){
$sz[]=$rec;
}
$length=sizeof($color);
for($i=0;$i<$length-1;$i++){
$query2 = mysql_query("INSERT INTO bridge (product_id,color_id, size_id)
VALUES ('$lastid', '$cid[$i]' , '$sz[$i]')") or die(mysql_error());
// echo "<script>alert('New Product successfully Addedd');windows.location.replace('addedit_product.php');</script>";
}