Home > Back-end >  How can I add paragraph text as select options?
How can I add paragraph text as select options?

Time:06-01

I need to change the first option in the select options and put the first paragraph text inside it, so the first paragraph will be the first option text in the first select element, and the second paragraph to be the first option in the next select element. I know my approach is not at all correct but I tried and couldn't find the right way to do it. Do I need to loop? Or is there another way of doing that? I'm trying using jQuery.

$('.select-container p').each(function(index) {
  let textPar = $(this).text();
  
  $('.select-container select option:first-child').each(function(index) {
    $(this).text(textPar);
  });
});
select {
  width: 200px;
  padding: 5px 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div >
  <div >
    <p>First paragraph</p>
    <select>
      <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>
    </select>
  </div>
  <div >
    <p>Second paragraph</p>
    <select>
      <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>
    </select>
  </div>
</div>

CodePudding user response:

You just need to think through your selectors a bit better. You were updating the text of all select elements, so you need to be more specific. Then, you don't need to loop over one element after selecting it.

$('.select-container p').each(function() {
  const par = $(this);
  const parText = par.text();

  par.next('select').find('option:first-child').text(parText);
});
select {
  width: 200px;
  padding: 5px 8px;
}
<div >
  <div >
    <p>First paragraph</p>

    <select>
      <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>
    </select>
  </div>

  <div >
    <p>Second paragraph</p>

    <select>
      <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>
    </select>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related