How to add a bottom margin to the div on select the option with JavaScript

Viewed 43

I'm trying to add the margin of the select div when the value selected I'm not an expert in the javascript I found javascript on another blog but I think that does not work Help me to do that

Here is my code

<style>
.container{
border:2px solid black;
margin-top: 20px;}

</style>
<div class="html-code-output">
<div class="main">
    <p>Select an option to show the value and text of that option.</p>
    <select class="addon-select">
        <option value="">Select  a Option</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
    </select>
<div class="container">
<h4>Add a margin when we select the an option</h4>
</div>
</div>
</div>

<script>

jQuery('.addon-select').on('change', function () {
    let val = $(this).val();
    $(".main").css("margin-bottom", "1rem");
    $(".main('" + val + "') ").css("margin-bottom", "5rem");
});;

</script>
1 Answers

If you have one element which you want to change its margin-bottom depending on what is selected on the select:

HTML

<body>

<div class="item">
  Item 
</div>

<select onchange="selectFunction(this)">
  <option value="">Select option</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>
</body>

JS

function selectFunction(selected){
    var selectedOption = $(selected).val();
  
  $(".item").css("margin-bottom",selectedOption*3);
}

If you have many items, and you want to change the padding of one of them depending on which option is selected on the select:

HTML

<body>

<div class="item">
  Item  1
</div>
<div class="item">
  Item  2
</div>
<div class="item">
  Item  3
</div>
<div class="item">
  Item  4
</div>

<select onchange="selectFunction(this)">
  <option value="">Select option</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>
</body>

JS

function selectFunction(selected){
$(".item").css("margin-bottom",0);
    var selectedOption = $(selected).val();
  selectedOption --;
  
  
  
  $(".item").eq(selectedOption).css("margin-bottom",10);
}

Related