Vinay Vinay - 13 days ago 7
PHP Question

How to retrieve selected value from the dropdown list without refreshing the page or form submitting?

I am making a drop down menu about brands in a ecommerce website form where i have to enter products. Is there a possible way to retrieve the selected value of the dropdown without using the submit button. Better still, can i use the select option without an enclosing element.
If this is possible, how can i retrieve the value of the dropdown by using jquery.

function getbrands_add_products(){
global $con;
try{
$query = "select * from brands";
$stmt = $con->prepare($query);

$stmt->execute();
$result = $stmt->fetchAll();

echo "<option>Select Brand</option>";

foreach ($result as $rows) {
$brand_id = $rows['brand_id'];
$brand_title = $rows['brand_title'];
echo "<option value='$brand_id'>$brand_title</option>";
}
} catch(PDOException $e){
echo "Error: ".$e->getMessage();
}
}


This is the function in which i am querying the database and displaying them as a dropdown list for the user to select. How can i access the selected value without using the form submit. Best if it is jquery.

Answer

yes you can use it without <form> tag.

in fact you can use any form related element without the <form> tag.

if you want to use the <select> elemet selected value you can use select.onchange event.

the element value is selected option value.

html Code:

<select id='select'>
    <option value='11'>
        testOption
    </option>
</select>

js Code:

var select = document.getElementById('select');
select.onchange = function () {
    var value = this.value;
    alert(value);
}