mrmcg mrmcg - 10 months ago 45
Ajax Question

Ajax return value match the value of the dropdown and show the SELECTED value. Php

What I am doing is passing data via Ajax and putting that data into a Dropdown. So when the data gets passed it should match the selected value in the dropdown and then appear on top with SELECTED on the option so we can see the data right away. So if the data being returned is Product2 then Product2 should be SELECTED and visable.

<script type="text/javascript">
function myFunction() {
var skuvalue=document.my_form.modlistbox.value;
$.ajax({ url: 'modify.php',
data: {sku: skuvalue},
type: 'post',
dataType: "html",
error: function (request, error) {
alert("ERROR: " + error);
success: function(data) {
var jsonvalue = $.parseJSON(data);
$("#modproduct").val(jsonvalue[1]).prop('selected', true); // I tried this and not working. Nothing is being SELECTED.

<input type="text" name="modsku" id="modsku" maxlength="10">
<select name="modproduct" id="modproduct">
<option value="Product1">Product1</option>
<option value="Product2">Product2</option>
<option value="Product3">Product3</option>

For what I am looking to have done is something like this.

<select name="modproduct" id="modproduct">
<option value="Product1">Product1</option>
<option value="Product2" selected>Product2</option>
<option value="Product3">Product3</option>

Answer Source

The chained function call here is superfluous (and doesn't really make much sense in the context, trying to set a selected property on a select element):

$("#modproduct").val(jsonvalue[1]).prop('selected', true);

You can set the selected option in a select simply by setting the value with jQuery:


Note: There are other things in this code which don't make any sense. For example, this:


It doesn't do anything, and is really just an opportunity for an error. So there may very well be other problems in your code which prevent the overall result from happening.