1

Hi I am new to jquery and ajax I had a dropdown where I will get the data from database using ajax but I am getting issue while populating that data into an dropdown here is the fiddle here I had taken the response in an variable and populated

//Store in array()
$(document).ready(function () {
    addOne();
       $('.drop').select2();
   
});

var uids = [];

//Select option function
$(document).on("change", ".drop", function() {
  $('#seedoc').data().enabled = 1; //set data-enabled to true instead of disabled = false


  //Find option selected
  var data = $(this).find("option:selected").attr('data-id')

  //Push selected data-id
  uids.push(data)

  //Enable button on selection
  $('#seedoc').prop('disabled', false)
  $('#seedoc').css('color', 'green');



})
$(document).on("click", "#seedoc", function(e) {

  const count = $('.drop').length;
  let sum = 0;

  $('.drop').each(function(e, elem) {
    sum += (parseInt($(elem).val()) > 0);
  });

  if (sum == count) addOne();

});

//Send
function send() {
  console.log(uids)
}

//response
var res = {
  "users": ["<p style='margin:0px;display:none;'data-id='755'>amilham</p>",
    "<p style='margin:0px;display:none;'data-id='706'>a_sarabi</p>"
  ]
}


function getEmails() {
  res.users.forEach(function(option) {
    $('.drop').append('<option value="' + $(option).attr('data-id') + '"" data-id=' + $(option).attr('data-id') + '>' + option + '</option>');
  });
}

function addOne() {
$('#seedoc').css('color', 'gray');


  $('#email-list-container').append("<div class='form-group' style='display:flex'><select class='drop form-control' name='option' id='option'> <option value='0' disabled selected>Select your option</option> </select><select class='form-control'  style='margin-left:1rem' name='cars' id='permissions'><option value='1'>edit</option><option value='2'>view only</option></select>");
  getEmails();

}
getEmails();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" type='text/css' rel='stylesheet' />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.3.1/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.3.1/select2.min.css" type='text/css' rel='stylesheet' />

<div id="email-list-container" class=""></div>
<i class="fa fa-plus-square fa-2x" aria-hidden="true" id="seedoc" style="float: right; margin-right: 10px;" data-enabled="0"></i>

Here the problem is I am getting the same data for every dropdown on click of add button but here in the firstdropdown I am getting two names and when I click add and check the first dropdown again I am getting the two names doubled i.e 4 options but I want to show only two options in every dropdown whenever I check

Please help me

swith
  • 85
  • 8
  • Inside function `getEmails()` you are appending to `$('.drop')` every time `+` button is clicked, which means items are added to already existing. You need to do a `$('.drop').empty()` if you like to use `.append()` but replace the items. You can also do `.html()` that will replace current items – Alwaysa Learner Aug 03 '20 at 06:51

2 Answers2

1

Try to change this line:

$('.drop').append('<option value="' + $(option).attr('data-id') + '"" data-id=' + $(option).attr('data-id') + '>' + option + '</option>');
  });

To this line, which will ensure that only the last dropdown gets the options added to it:

$('.drop').last().append('<option value="' + $(option).attr('data-id') + '"" data-id=' + $(option).attr('data-id') + '>' + option + '</option>');
  });
Andrew Arthur
  • 1,563
  • 2
  • 11
  • 17
  • Not an ideal solution Because => `:last` Selector pseudo-class is deprecated since jQuery 3.4 - Its not recemended to offer solution based on deprecated function. – Always Helping Aug 03 '20 at 06:54
0

You can simply use .last function in your getEmails - append function to make sure that you are not appending to the new option to every drop down as you have same classes .drop.

This will ensure you are not appending the option to all the dropdowns but only the last one.

Demo

//Store in array()
$(document).ready(function() {
  addOne();
});

var uids = [];

//Select option function
$(document).on("change", ".drop", function() {
  $('#seedoc').data().enabled = 1; //set data-enabled to true instead of disabled = false

  //Find option selected
  var data = $(this).find("option:selected").attr('data-id')

  //Push selected data-id
  uids.push(data)

  //Enable button on selection
  $('#seedoc').prop('disabled', false)
  $('#seedoc').css('color', 'green');
})

$(document).on("click", "#seedoc", function(e) {

  const count = $('.drop').length;
  let sum = 0;

  $('.drop').each(function(e, elem) {
    sum += (parseInt($(elem).val()) > 0);
  });

  if (sum == count) addOne();

});

//Send
function send() {
  console.log(uids)
}

//response
var res = {
  "users": ["<p style='margin:0px;display:none;'data-id='755'>amilham</p>",
    "<p style='margin:0px;display:none;'data-id='706'>a_sarabi</p>"
  ]
}


function getEmails() {
  res.users.forEach(function(option) {
    $('.drop').last().append('<option value="' + $(option).attr('data-id') + '"" data-id=' + $(option).attr('data-id') + '>' + option + '</option>');
  });
}

function addOne() {
  $('#seedoc').css('color', 'gray');
  $('#email-list-container').append("<div class='form-group' style='display:flex'><select class='drop form-control' name='option' id='option'> <option value='0' disabled selected>Select your option</option> </select><select class='form-control'  style='margin-left:1rem' name='cars' id='permissions'><option value='1'>edit</option><option value='2'>view only</option></select>");
  getEmails();

}
getEmails();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" type='text/css' rel='stylesheet' />

<div id="email-list-container" class=""></div>
<i class="fa fa-plus-square fa-2x" aria-hidden="true" id="seedoc" style="float: right; margin-right: 10px;" data-enabled="0"></i>
Always Helping
  • 14,316
  • 4
  • 13
  • 29
  • a small help I had used select2 plugin for implementing search option for dropdown for first dropdown it is working but from second dropdown it is not working can you please help me @AlwaysHelping – swith Aug 03 '20 at 09:26
  • @swith You need to use event delegation for your dynamically created elements to be able to use select2 on those elements. This is how events are deletegated => `$(document).on("click", "#seedoc", function(e) {})` this – Always Helping Aug 03 '20 at 09:32
  • I didnt got it can you edit in your answer if you dont mind – swith Aug 03 '20 at 09:33
  • @swith Check here [Its a very detailed answer.](https://stackoverflow.com/questions/29972399/initialising-select2-created-dynamically) and show exactly what you are trying to do. – Always Helping Aug 03 '20 at 09:45
  • how can I use this answer in my case here – swith Aug 03 '20 at 09:51
  • 1
    Try this => `$('.drop').last().select2()` add this code after the append function in `getEmails()` – Always Helping Aug 03 '20 at 09:54
  • ya an easy answer its working thank you man great! :) – swith Aug 03 '20 at 09:57
  • @swith Happy to help always. Happy coding. – Always Helping Aug 03 '20 at 09:57