update database on dropdown list change event - javascript

I have a drop down list loaded on the page using a javascript (not originally on the page), it's loaded without problems, but then I want to update a database table once the selected value of the dropdown list changes, I'm using this script :
<select name = "categ" id="dropd1"><option> .... </option></select>
<script>
$( "#dropd1" )
.change(function () {
var value = this.val();
$.post('listener_updates.php', {categ: value});});
</script>
the listener_update.php contains the script for updating the database :
<?php
if($_POST && $_POST['categ']){
connectMaBase();
$sql ='UPDATE produit SET categorie = "'.$_POST['categ'].'" WHERE num_prod ='.$_SESSION['num_prod'];
$req = mysql_query ($sql) or die ('Erreur SQL !'.$sql.'<br />'.mysql_error());
mysql_close();
}
?>

you didn't ask a question.
anyway, this.val() will probably throw an exception.
try $(this).val()
UPDATE:
try
$(document).on('change', '#dropd1', function(){
var value = $(this).val();
$.post('listener_updates.php', {categ: value});});
});
this will create an event listener for dynamically added DOM elements.

Related

Why value of select isn't showing inside of modal like value of input everything else?

So, basically I have this modal which pop-ups when I click edit button, the thing is I am able to get values of every input, except of select value.
To get you a little bit familiar with situation here, the process of what's happening is following:
I have one table (which is dynamically populated by the data from database) - works fine and it basically shows value it should show inside of that table.
Now apart from that I have edit and delete button and when I click edit button modal pop-ups and let's say I've clicked EDIT button on first row of the table, <input> fields in modal pop-up are filled in with data from table (database) corresponding to row where edit button is clicked, except this select thing and what I am expecting that, that same value from table replicates inside of first <option value="" id="vlasnik" name="vlasnik" selected disabled hidden></option> value, so one doesn't have to remember what was initially selected, and here is how my <select> together with <option> looks like:
<div class="mb-3">
<select id="vlasnik" name="vlasnik" class="form-control form-control-lg" required>
<option value="" id="vlasnik" name="vlasnik" selected disabled hidden></option>
<?php foreach($users as $user): ?>
<option value="<?= $user['id']; ?>"><?= "[" . $user['id'] . "]" . $user['username']; ?></option>
<?php endforeach; ?>
</select>
</div>
And it gives me following:
Also, I must say that I am treating other input's differently, like this (actually):
// Edit User Ajax Request
tbody.addEventListener("click", (e) => {
if (e.target && e.target.matches("a.editLink")) {
e.preventDefault();
let id = e.target.getAttribute("id");
editUser(id);
}
});
const editUser = async (id) => {
const data = await fetch(`action.php?edit=1&id=${id}`, {
method: "GET",
});
const response = await data.json();
document.getElementById("id").value = response.id;
document.getElementById("make").value = response.make;
document.getElementById("model").value = response.model;
document.getElementById("godina").value = response.godina;
document.getElementById("boja").value = response.boja;
document.getElementById("vin").value = response.vin;
document.getElementById("engine").value = response.engine;
document.getElementById("tip").value = response.tip;
document.getElementById("vlasnik").value = response.vlasnik;
document.getElementById("regoz").value = response.regoz;
document.getElementById("istek").value = response.istek;
document.getElementById("odometer").value = response.odometer;
document.getElementById("napomena").value = response.napomena;
document.getElementById("carStatus").value = response.carStatus;
};
Inside of action.php I have this:
// Handle Edit User Ajax Request
if (isset($_GET['edit'])) {
$id = $_GET['id'];
$user = $db->readOne($id);
echo json_encode($user);
}
And inside of db, readOne method is:
public function readOne($id)
{
$sql = 'SELECT * FROM vozila WHERE id = :id';
$stmt = $this->conn->prepare($sql);
$stmt->execute(['id' => $id]);
$result = $stmt->fetch();
return $result;
}
As I said I get every other value except for option. Does anybody know what is the problem and how can I achieve what I want?
document.getElementById("vlasnik").options[document.getElementById("vlasnik").selectedIndex].value
see selectedIndex

JQuery-Get value from select option to use in PHP

I would like to generate a query that contains the value selected from a drop down menu the value would be saved into a PHP variable
<script>
$(document).ready( function ()
{
/* we are assigning change event handler for select box */
/* it will run when selectbox options are changed */
$('#dropdown_selector').change(function()
{
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
$('$showoption').val(option);
});
});
</script>
<?
mysql_query("Select unit_price From products where id= '" . $id_value . "'");
while ($row = mysql_fetch_array($qquery)){
$unit = $row['unit_price'];
}
?>
<select class="form-control" name="model" id="dropdown_selector" >
<option value="1">1001</option>
</select>
One option could be to get the value of the select and submit it using a form on the same page. Then you can access the GET/POST parameters in PHP.
Another option could be to get the value of the select on change and make a request to a php page which does what you want with that data. It can also return back any data you want too.

option onChange on currentpage using database information

I've written a query that takes the usernames from the database and puts them in s like this:
<?php
$username_set = get_all_usernames();
while ($username = mysql_fetch_array($username_set)){
echo "<option>" . $username['username'] . "" . "</option>";
}
?>
That works fine but now I want to add a onchange function to my tags. I've done it like this:
<select name="user_result" onChange="top.location.href = this.form.user_result.options[this.form.user_result.selectedIndex].value,'_self';">
That works fine too, it is redirecting to the selected option. But I want to select a option and stay at the same page and display the (coming) information that username contains. But for now printing the username below the would be good enough.
If you want to execute code on change of a select, it's easy to include this in a javascript function. Not sure if you want the javascript or the jquery solution, so I'll include them both.
Plain javascript:
function show_user(data) {
var el = document.getElementById("show_username").innerHTML = data;
}
jQuery solution:
function show_user(data) {
$("#show_username").html(data);
}
Then you call this function on the select change:
<select name="user_result" onchange="show_user(this.options[this.selectedIndex].value);">
<option>--select a user--</option>
<option>username</option>
<option>username 2</option>
</select>
<div id="show_username">this will update to the selected user name</div>
jsfiddle for plain javascript: http://jsfiddle.net/CwFs5/
jsfiddle for jquery: http://jsfiddle.net/5PuX3/

How to show dropdown selected data in textbox

I want to show the drop down selected value in textbox.
This is my design.
This is my php code for drop downlist...
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("storedb", $con);
$s=mysql_query("select * from dealerdetail order by Dealer asc ");
?>
Select Dealer Name:
<select name="dealer" id="dealer">
<option value="">---- select Dealer -----</option>
<?php
while($dd=mysql_fetch_array($s))
{
?>
<option value="<?php echo $dd['D_id'] ?>"><?php echo $dd['Dealer'] ?></option>
<?php
}
?>
</select>
Please help.
I think you are looking for
$('#dealer').val(); //return selected value
$( "#dealer option:selected" ).text() // return selected options text
Use the change event and text property of select box to access the value
$('#dealer').change(function () {
$("#idOfTextBox").val($("#dealer option:selected").text());
});
use jquery:
Live demo : http://jsfiddle.net/t6YHK/25/
$('#dealer').change(function () {
$("#your_input_id").val($(this).val());
});
Use this:
$("#dealer").change(function(){
$("textarea").val( $(this).val() );
});
AngularJS
http://angularjs.org/
Scroll down to below the black area.
Seems like you're taking your first steps in web development, and for this, i strictly recommend that you stop using DreamWeaver to learn more about the code and how things go.
Each element in your web page is in the DOM (see HTML Document Object Model). So using native javascript all of your elements using :
document.getElementById("elementId")
And this is ALL what you need. All other solutions using frameworks will use this line of code whether you see this or not.
so for your specific question we will create a javascript function to be used in the event of value change of your dropdown list (assuming your text field's id is myText)
function updateMyText()
{
var dd = document.getElementById("myDropDown");
var ddtext = dd.options[dd.selectedIndex].text;
document.getElementById("myText").value = ddtext;
}
to call it when a dropdown list item is selected you need the attribute onchange
<select name="dealer" id="dealer" onchange='updateMyText()'>

Filter one HTML select dropdown based on another select dropdown

I have a simple PHP script with a form that has two select fields, both of which are simply numerical values. The script also has a maximum for the sum of the two fields. I'm trying to dynamically filter the second drop down, so that a user cannot select more than the maximum. E.g., if my maximum is 10, the first select dropdown would have 1-10 in it. A user selecting 6 would then only be able to select 0-4 in the second select dropdown.
I know this should be reasonably straightforward, but I'm a total JavaScript/jQuery novice. I have searched SO and Google, but I don't understand enough of the examples I've seen to know where to start, let alone figure out how to customise them to my needs. I've provided the code I have already, which clearly doesn't have any of the filtering I need.
Some sample code (assume $maximum defined already):
<script type="text/javascript">
var max = <?php echo $maximum; ?>;
</script>
<select name="dropdown1" id="dropdown1">
<?php
for ($i = 1; $i <= $maximum; $i++)
{
echo '<option value="'.$i.'">'.$i.'</option>';
}
?>
</select>
<select name="dropdown2" id="dropdown2">
<?php
for ($i = 0; $i <= $maximum; $i++)
{
echo '<option value="'.$i.'">'.$i.'</option>';
}
?>
</select>
Thanks in advance.
I now have the following piece of jquery in it's own .js file:
$(document).ready(function() {
// var max ??
$("#dropdown1").change(function() {
var selectedVal = $(this).find("option:selected").val();
$("#dropdown2 option").removeAttr("disabled").removeAttr("selected");
$("#dropdown2 option").each(function() {
if($(this).val() > max - selectedVal*1)
$(this).attr("disabled", "disabled");
});
});
});
However, I'm a bit stuck getting $maximum from my PHP script into the jQuery. I figure I have to create a JavaScript variable, but not quite sure how to pass it to the jQuery. I can figure out how to do it if I had the jQuery embedded in the same PHP script, just by echoing it out, but not quite so sure about passing it as a parameter.
Here is a working fiddle. And, the relevant jQuery code:
$(document).ready(function() {
$("#select1").change(function() {
var selectedVal = $(this).find("option:selected").val();
$("#select2 option").each(function() {
if($(this).val() >= selectedVal)
$(this).attr("disabled", "disabled");
});
});
});
I update code of legendofawesomeness for your case

Categories