I don't know JS at all, but I need some js features in my django project. I would be very grateful if you help me. I would like to change the style for option tags of the tag select with id="id_car_model". It should to check the value attributes for each option tags and to match with the "pk", which it gets from JSON.
The condition: if value != pk add style="display:none". Each value should be matched with each pk. For this example the list should be with 1 and 2 pk.
And this select input should be inactive until it receives this JSON.
I have tried to find the solution, but I don't know to apply it.
html
<select name="car_model" id="id_car_model">
<options value selected>----------</option>
<options value="1">520</option>
<options value="2">720</option>
<options value="3">301</option>
<options value="4">308</option>
</select>
It gets JSON from django back-end.
main.js
$.ajax({
type: 'POST',
url: 'car-model-ajax/',
data: model_data,
dataType: 'json',
success: function (response) {
console.log(response)
console.log(response.car_models)
var jsonModels = response.car_models
var models = JSON.parse(jsonModels)
console.log(models)
models.map(el => console.log(el.pk))
},
error: function (response) {
console.log(response)
},
})
It is in the console
{car_models: '[{"model": "adapp.carmodel", "pk": 1, "fields": {"…pk": 2, "fields": {"brand": 12, "model": "720"}}]'}
main.js:263 [{"model": "adapp.carmodel", "pk": 1, "fields": {"brand": 12, "model": "520"}}, {"model": "adapp.carmodel", "pk": 2, "fields": {"brand": 12, "model": "720"}}]
main.js:266 (2) [{…}, {…}]
main.js:267 1
main.js:267 2
If I understood the task correctly - here the fixed version of your function (with comments in needed places):
$.ajax({
type: 'POST',
url: 'car-model-ajax/',
data: model_data,
dataType: 'json',
success: function (response) {
// show all items (activate previously disabled)
$("#id_car_model option:disabled").removeAttr('disabled');
const models = JSON.parse(response.car_models).map((el) => el.pk);
// hide all that we don't have in the models array
$("#id_car_model option").each(function(val){
if(!models.includes(val)){
$(this).attr('disabled', 'disabled');
}
});
},
error: function (response) {
console.log(response)
},
})
Here's a code snippet you can play with:
const idsToShow = [1,2];
$("#id_car_model option").each(function(val){
if(!idsToShow.includes(val)){
$(this).attr('disabled', 'disabled');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<select name="car_model" id="id_car_model">
<option value="0" selected>----------</option>
<option value="1">520</option>
<option value="2">720</option>
<option value="3">301</option>
<option value="4">308</option>
</select>
</body>