How to Change Options Based on Another Select Option in a Table

How to change options based on another select option in a table?

As you are using $('.details option') so it will get all details options and loop for all. So instead of using $('.details option') use this $(this).closest('tr').find('.details option')

The closest will only return selected category details options and loop only for that not for all.

DEMO

$('.category').on('change', function() {  switch ($(this).val()) {    case 'low':      $(this).closest('tr').find('.details option').each(function() {        if (+$(this).val() < 3) {          $(this).show();          $(this).find('option:first').prop('selected', true);        } else $(this).hide();      });      break;    case 'mid':      $(this).closest('tr').find('.details option').each(function() {        if (+$(this).val() < 5 && +$(this).val() > 2) {          $(this).show();          $(this).find('option:first').prop('selected', true);        } else $(this).hide();      });      break;    case 'high':      $(this).closest('tr').find('.details option').each(function() {        if (+$(this).val() > 4) {          $(this).show();          $(this).find('option:first').prop('selected', true);        } else $(this).hide();      });      break;    case '':      $(this).closest('tr').find('.details option').show();      $(this).closest('tr').find('.details option:first').prop('selected', true);      break;  }});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table>  <tbody>    <tr>      <td>        <select class="category">          <option value="low">Low</option>          <option value="mid">Mid</option>          <option value="high">High</option>        </select>      </td>      <td>        <select class="details">          <option value="1">1</option>          <option value="2">2</option>          <option value="3">3</option>          <option value="4">4</option>          <option value="5">5</option>          <option value="6">6</option>        </select>      </td>    </tr>    <tr>      <td>        <select class="category">          <option value="low">Low</option>          <option value="mid">Mid</option>          <option value="high">High</option>        </select>      </td>      <td>        <select class="details">          <option value="1">1</option>          <option value="2">2</option>          <option value="3">3</option>          <option value="4">4</option>          <option value="5">5</option>          <option value="6">6</option>        </select>      </td>    </tr>  </tbody></table>

how to change value of select options based on another select option selected?

Successfully Done...

Ajax function =>

$(document).ready(function () {
$('#location').on('change', function () {
var location_id = $(this).val();

if (location_id == '') {
$('#fees').prop('disabled', true);
} else {
$('#fees').prop('disabled', false);
$.ajax({
url: "<?php echo $base_url;?>welcome/getFeePeriod",
type: 'POST',
data: {location: location_id},
dataType: 'json',
success: function (data) {
//alert("Ok");
$('#fees').html(data);
},
error: function () {
alert("Error Accured...");
}
});
}
});
});

Controller function =>

public function getFeePeriod()
{
$location_id = $this->input->post('location');
$FeesPeriod = $this->admin_model->getFeePeriod($location_id);
if (count($FeesPeriod)>0) {
$fee_select_box = '';
$fee_select_box .= '<option id="">Select Fee Period</option>';
foreach ($FeesPeriod as $fees) {
$fee_select_box .= '<option id="' . $fees->admission_fee_1 . '">Monthly</option>+
<option id="' . $fees->admission_fee_3 . '">Quarterly</option>+
<option id="' . $fees->admission_fee_6 . '">Half Yearly</option>+
<option id="' . $fees->admission_fee_12 . '">Yearly</option>';
}
echo json_encode($fee_select_box);
}
}

model function =>

function getFeePeriod($location_id){
$query = $this->db->get_where('location', array('id'=>$location_id));
return $query->result();
}

Thanks everyone for their response...

Select option value based on another select option in dynamic table

The easiest way is to make just two selects and add some classes on it.
Then filter by classes or attributes. I've done by class on this example.

document.getElementById("main_select").onchange = function(){    let selector = document.getElementById('main_select');  let value = selector[selector.selectedIndex].value;      let nodeList = document.getElementById("sub_select").querySelectorAll("option");    nodeList.forEach(function(option){      if(option.classList.contains(value)){      option.style.display="block";    }else{      option.style.display="none";    }      });  }
<html>    <head>    <title>no Title</title>    </head><body><table id="animal">    <tr>        <td>            <select id="main_select">                <option selected>Please select</option>                <option value="land">Land</option>                <option value="air">Air</option>                <option value="water">Water</option>            </select>        </td>        <td>            <select id="sub_select">                  <option selected>Please select</option>                  <option class="land" value="cat">cat</option>                  <option class="land" value="dog">dog</option>                  <option class="land" value="chicken">chicken</option>                  <option class="water" value="fish">fish</option>                  <option class="water" value="octopus">octopus</option>            </select>        </td>    </tr></table>

Set the option available for select based on another select php

Like it was said, you can use ajax.
There is a static non-ajax way of doing it, but this way it is better in the long run.

Basically, what you do with that jQuery is listen for a change in the continent select box, and when a change happens, you make a request to the server asking: "give me all the countries within this continent". You should have a database for this or you can map them in static objects just to test it out.

$('.continent').change(function() {
var id = $(this).val(); //get the current value's option
$.ajax({
type:'POST',
url:'<path>/getCountries',
data:{'id':id},
success:function(data){
//in here, for simplicity, you can substitue the HTML for a brand new select box for countries
//1.
$(".countries_container").html(data);

//2.
// iterate through objects and build HTML here
}
});
});

This would of course make you add the countries_container in the HTML like and inside it you would render the select:

<div class="countries_container"></div>

Now in the actual PHP code server side (getCountries) you could do something like:

$id = $_POST['id'];
if(isset($id) && <other validations>)){

// 1. your query to get countries from a given continent
// and for each result you can build the HTML itself

// 2. OR, a better solution is to return an Object and then in the
// success:function(data){ } iterate through it
}

This code can most defiantly be improved, but I tried to explain it in a understandable way.

Also, you should check:

Jquery ajax populate dropdown with json response data

Demo of linked drop down list by using Ajax & PHP

Keep on mind, these were the first results from a google search therefore, next time, try to search within stack overflow itself to avoid duplicate questions.

Show drop down values of a select based on another select

You can add an event listener for the onChange event of the select box.
On the change event get the value of the select box and send its value to the server using an ajax request and fetch the value you want to show in the second select box based on the first one's value and show it in the second select box.
Example Code for state selection based on country selection:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Populate City Dropdown Using jQuery Ajax</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "process-request.php",
data: { country : selectedCountry }
}).done(function(data){
$("#response").html(data);
});
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td>
<label>Country:</label>
<select class="country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
</select>
</td>
<td id="response">
<!--Response will be inserted here-->
</td>
</tr>
</table>
</form>
</body>
</html>

Backend:

<?php
if(isset($_POST["country"])){
// Capture selected country
$country = $_POST["country"];

// Define country and city array
$countryArr = array(
"usa" => array("New Yourk", "Los Angeles", "California"),
"india" => array("Mumbai", "New Delhi", "Bangalore"),
"uk" => array("London", "Manchester", "Liverpool")
);

// Display city dropdown based on country name
if($country !== 'Select'){
echo "<label>City:</label>";
echo "<select>";
foreach($countryArr[$country] as $value){
echo "<option>". $value . "</option>";
}
echo "</select>";
}
}
?>


Related Topics



Leave a reply



Submit