John Davidson

php - Get First Option Text on Button Click Jquery

0 comments
Message:


I am having a select field in which I am trying to achieve something like when the dropdown is selected, datatable will be sorted accordingly. Once the user is done with sorting, There is a button to clear all values of dropdown and get the general value to show all rows without sorting. The values are taken fine except the text of the value remains the same.


//dropdown
<select value='Deliver To' name="_location" id="_location" class="SlectBox form-control">
<?php echo location(); ?>
</select>

//PHP to get results to dropdown
function location(){
global $con;
$output.= '<option value="_allCity">All Results</option>';
$_selectquery= "SELECT * FROM _tableone";
$result = mysqli_query($con, $_selectquery);
while($row = mysqli_fetch_array($result)){
$output.= '<option value = "'.$row["name"].'">'.$row["name"].'</option>';
}
return $output;
}

//Button to reset dropdown
$('#reset').click(function(){
$('#_location').val('_allCity').change();
$('#_location').text('All Results').change();
});

When I reset the value is taken correctly but the text is still the manually selected one.



My Answer:
To get the first option text on button click in jQuery, you can use the following code:

javascript
$('#reset').click(function(){
$('#_location').val('_allCity').change();
$('#_location option:first').prop('selected', true).change();
});


This code will set the selected option to the first option in the dropdown list when the button with id "reset" is clicked.

Rate this post

5 of 5 based on 7167 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us