I want the select option to be 'selected' with the value returned from ajax response.
array
$array=array("Price 1","Price 2","Price 3","Price 4","Price 5");
All I can thinking of is to loop until the option is matched with the given value.
echo "<select id='option'>";
foreach($array as $key=>$val){
if(data.option==$key){$selected="selected";}//compare with json from ajax
echo "<option value='$key' $selected>$val</option>"
}
echo "</select>";
And I have a json response from ajax data.option
= 1. So, is there anyway to achieve this or alternative method to do so?
This is what you want (do inside ajax success
):-
success: function (data) {
$("#option").val(data.option);//this is what you want
}
A demo example:-
$(document).ready(function(){ $("#option").val(2); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id='option'> <option value="0" selected>Price 1</option> <option value="1">Price 2</option> <option value="2">Price 3</option> <option value="3">Price 4</option> <option value="4">Price 5</option> </select>
$(document).ready(function(){ $("#option").val(2); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id='option'> <option value="0" selected>Price 1</option> <option value="1">Price 2</option> <option value="2">Price 3</option> <option value="3">Price 4</option> <option value="4">Price 5</option> </select>
$(document).ready(function(){ $("#option").val(2); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id='option'> <option value="0" selected>Price 1</option> <option value="1">Price 2</option> <option value="2">Price 3</option> <option value="3">Price 4</option> <option value="4">Price 5</option> </select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.