Populating the data from ajax response into an dropdown - javascript

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

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>');
});

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>

Related

Show value of select option in html

I have a list with the tag, the item values ​​are obtained through an online spreadsheet. When selecting an option, the value does not appear in the html in real time. can anybody help me? I'm trying to solve it, but I can't find the error.
CODEPEN LINK EXAMPLE
$(document).ready(function() {
var sheetURL =
"https://spreadsheets.google.com/feeds/list/1J0qyxUCCkvcFGZ6EIy9nDOgEuTlpI5ICVG3ZsBd_H-I/1/public/values?alt=json";
$.getJSON(sheetURL, function(data) {
var entryData = data.feed.entry;
console.log(data);
jQuery.each(entryData, function() {
$("#divTax").append(
'<option hidden="hidden" selected="selected" value="0">CHOISE</option><option value="' + this.gsx$values.$t + '">' + this.gsx$names.$t + ' $' + this.gsx$values.$t + '</option>'
);
});
});
});
var totalWithTax = $('#divTax :selected').val();
$('.total').html(totalWithTax);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select style="width: 80%;" id="divTax"></select>
<br>
Total:<div class="total"></div>
You to put the code that displays the selection in an event listener.
$(document).ready(function() {
var sheetURL =
"https://spreadsheets.google.com/feeds/list/1J0qyxUCCkvcFGZ6EIy9nDOgEuTlpI5ICVG3ZsBd_H-I/1/public/values?alt=json";
$.getJSON(sheetURL, function(data) {
var entryData = data.feed.entry;
jQuery.each(entryData, function() {
$("#divTax").append(
'<option hidden="hidden" selected="selected" value="0">CHOISE</option><option value="' + this.gsx$values.$t + '">' + this.gsx$names.$t + ' $' + this.gsx$values.$t + '</option>'
);
});
});
$("#divTax").change(function() {
var totalWithTax = $(this).val();
$('.total').text(totalWithTax);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select style="width: 80%;" id="divTax"></select>
<br> Total:
<div class="total"></div>

How to get data from dynamic elements that added to the html page?

In below I write form part of my html page.
<form method="post" enctype="multipart/form-data">
<div>
<label>Brand Name:</label>
<input type="text" asp-for="#Model.Name">
</div>
<div id="divCategory">
</div>
<button type="button" id="btnAddCategory">Add Category</button>
<button>Create new Brand</button>
</form>
and I have two js and jquery function that add a select to divCategory. Whith this select I can add some categories.
function countMyCategories() {
if (typeof countMyCategories.counter == 'undefined') {
countMyCategories.counter = -1;
}
return ++countMyCategories.counter;
}
$(document).ready(function () {
$('#btnAddCategory').on('click', function () {
var catId = countMyCategories();
$('#divCategory').append(
'<select id="selectCategory' + catId + '" asp
for="##Model.CatBrands[' + catId + '].CatId" class="mt-3 form-control
form-control-sm">' +
'<option>---Select---</option>' +
'</select>'
);
$.ajax('/API/GetCats')
.done(function (categories) {
for (var i = 0; i < categories.length; i++) {
$('#selectCategory' + catId).append(
'<option value="' + categories[i].id + '">' +
categories[i].name + '</option>'
)
}
});
});
});
When I click the "Add Category" button one select tag added to the div by id="divCategory", but problem is that when I click "Create New Brand" button, I don't get data from these selects in server, actually CatBrands is null but I got name. I get something like that:
{name = "LG", catBrands = null}
CatBrands is null because you can't dynamically add data from the server in this manner. When the page renders, you need everything you want rendered by asp in the html.
<form method="post" enctype="multipart/form-data">
<div>
<label>Brand Name:</label>
<input type="text" asp-for="#Model.Name">
</div>
<div id="divCategory">
<select id="selectCategory asp-code-goes-here>
<option>---Select---</option>
</select>
</div>
<button type="button" id="btnAddCategory">Add Category</button>
<button>Create new Brand</button>
</form>
I've made a terible mistake. I should change my function like this
$(document).ready(function () {
$('#btnAddCategory').on('click', function () {
var catId = countMyCategories();
$('#divCategory').append(
'<select id="selectCategory' + catId + '"
name = "CatBrands[' + catId + '].CatId" class="mt-3 form-control
form-control-sm">' +
'<option>---Select---</option>' +
'</select>'
);
$.ajax('/API/GetCats')
.done(function (categories) {
for (var i = 0; i < categories.length; i++) {
$('#selectCategory' + catId).append(
'<option value="' + categories[i].id + '">' +
categories[i].name + '</option>'
)
}
});
});
});

How to remove a dynamically added div?

This is my HTML
<div class="form-group">
<label>Categories</label>
<button type="button" onclick="createContainer(availableCategories,'','.categoriesWrapper','Categories')" class="btn btn-default">+</button>
<div class="categoriesWrapper">
</div>
</div>
Inside I'm adding more divs with 'child' class with this function:
function createContainer(datasource, selectedItem, wrapper, name) {
var maxFields = 10;
var $container = $('<div style="margin-top:5px;" class="child" />');
var $select = $("<select class='form-control littleSpace' name='" + name + "'/>");
var $button = $("<button type='button' class='delete btn btn-default ' '>-</button>");
if ($(wrapper).children().length < maxFields) {
for (var itemId in datasource) {
//check to see if the option is the selected one
var isItemSelected = selectedItem && selectedItem === itemId;
var $option = null;
//create each option
if (isItemSelected == true) {
$option = $('<option value="' + itemId + '" selected>' + datasource[itemId] + '</option>');
}
else {
$option = $("<option value='" + itemId + "'>" + datasource[itemId] + "</option>");
}
//append option to select
$select.append($option);
}
$container.append($select);
$container.append($button);
$(wrapper).append($container);
}
};
Everything works great until now, but when I try to delete one o those divs and div content...it won't work. This is what I've tried:
$('.categoriesWrapper').on('click', 'delete', function () {
$(this).parent.remove();
});
Please help me
Pass class with . to make it work .delete inside click function as well as per #Rayon noticed change parent to parent()
$('.categoriesWrapper').on('click', '.delete', function () {
$(this).parent().remove();
});

Dynamically delete each row while append row index

I'm kind of confused on how to dynamically delete each row while also updating all row index accordingly, instead of row 1,2,3, while deleting 2, the rows should be append into 1,2, not remained 1,3..
jQuery(function(){
jQuery('a.add-author').click(function(event){
var number=document.getElementById("noofinputs").value;
event.preventDefault();
number++;
var newRow = jQuery(
'<tr>'+
'<td><textarea class="txtsize" name="item' +number + '" id="item' +number + '" rows="5" cols="32"></textarea></td>'+
'<td><select name="category' +number + '" id="category' +number + '" style="width:202px;" >'+
<?php
$q3=mysqli_query($con,"select * from categories ORDER BY category ASC");
while ($row3 = mysqli_fetch_assoc($q3)){
?>
'<option value="<?php echo $row3['no']; ?>"><?php echo $row3['category']; ?></option>'+
<?php
}
?>
+'</select></td>'+
'<td>$<input type="text" size="10" name="amount' +number + '" id="amount' +number + '" /></td>'+
'<td><img style="cursor: pointer;" height="24px" width="24px;" src="http://../images/Cancel.png" /> </td>'+
'</tr>');
jQuery('table.authors-list').append(newRow);
$('#noofinputs').val(number);
});
});
$(document).ready(function () {
$(".remove-author").click(function () {
removeRow(this);
});
});
function removeRow(elem){
var i = 0;
var ii = 0;
var iii = 0;
$(elem).closest('tr').remove();
$("table.authors-list tr").not(':first').each(function (){
$('td', this).not(':last').each(function() {
$(this).find('textarea').each(function(){
$(this).attr('name', 'item' + ( i+1 ));
i++;
});
$(this).find('select').each(function(){
$(this).attr('name', 'category' + ( ii+1 ));
ii++;
});
$(this).find('input').each(function(){
$(this).attr('name', 'amount' + ( iii+1 ));
iii++;
});
});
});
var a=document.getElementById("noofinputs").value;
var b = (a - 1);
$('#noofinputs').val(b);
}
I edited the code yet I can't even delete a single row...
I tried to follow this renumber appended table row in javascript after deleting
but it's not working at all...
EDITED: FINALLY it can be deleted and renumber its "number" name attribute after some changes!
Edit: Looks like you need to remove the number from <a href="#" title="" class="remove-author'+number+'">. Just leave it as <a href="#" title="" class="remove-author">.
You also you want to remove the $('.remove-author').each(function(){
jQuery doesn't act on elements that are created dynamically. So you'll want to create a new function and inject it into the <a> element (not the best solution, but it will work without heavily modifying your code)
So your code should be
$(document).ready(function () {
$(".remove-author").click(function () {
removeRow(this);
});
});
function removeRow(elem){
$(elem).closest('tr').remove();
$("table.authors-list tr").each(function (i){
var txt = $(this).find('textarea').attr('name');
$(this).find('textarea').attr('name', txt.replace(/\d+/, i+1));
var sel = $(this).find('select').attr('name');
$(this).find('select').attr('name', sel.replace(/\d+/, i+1));
var amt = $(this).find('input').attr('name');
$(this).find('input').attr('name', amt.replace(/\d+/, i+1));
});
}
now you will want to add this to the <a> element
<a href="#" title="" class="remove-author" click="removeRow(this);">

How to Add Handler Id to Options value loaded by jQuery

I am trying to load a select options by using jQuery from 3 arrays to one select list on click which so far works fine for me at here
But I have an issue here.if you look at the values I have same value on three list so I have to upgrade them by adding also the id of the clicked button to the value some thing like this:
<option value="regi1NNN">NNN</option>
instead of
<option value="NNN">NNN</option>
depends on what button clicked.
Here is my code:
$(document).ready(function () {
var opt1 = ["AAAA", "BBBB", "NNN", "JJJJJ"];
var opt2 = ["KKKK", "FFFF", "NNN", "TTTTT"];
var opt3 = ["MMM", "NNN", "OOOO", "PPPPP"];
$("#regi1").click(function () {
$('#items option').remove();
var option = '';
for (i = 0; i < opt1.length; i++) {
option += '<option value="' + opt1[i] + '">' + opt1[i] + '</option>';
}
$('#items').append(option);
});
$("#regi2").click(function () {
$('#items option').remove();
var option = '';
for (i = 0; i < opt2.length; i++) {
option += '<option value="' + opt2[i] + '">' + opt2[i] + '</option>';
}
$('#items').append(option);
});
$("#regi3").click(function () {
$('#items option').remove();
var option = '';
for (i = 0; i < opt3.length; i++) {
option += '<option value="' + opt3[i] + '">' + opt3[i] + '</option>';
}
$('#items').append(option);
});
});
When you create your options like so:
option += '<option value="' + opt1[i] + '">' + opt1[i] + '</option>';
Simply add the id of the clicked element as a prefix:
option += '<option value="' + this.id + opt1[i] + '">' + opt1[i] + '</option>';
Working example: http://jsfiddle.net/g8euy/ This way when you combine all your click handlers into one function (which you should, since you have three functions that do the same thing) you'll be all set.
UPDATE: I rewrote your code to only use a single funciton. Example here: http://jsfiddle.net/n2tBC/1/
I added a class and a data attribute to your buttons:
<div class="container">
<div class="well">
<div class="btn-group">
<button type="button" class="btn btn-default listy" id="regi1" data-vals="opt1">Left</button>
<button type="button" class="btn btn-default listy" id="regi2" data-vals="opt2">Middle</button>
<button type="button" class="btn btn-default listy" id="regi3" data-vals="opt3">Right</button>
</div>
<br />
<br />
<select id="items"></select>
</div>
</div>
And then the script combines your value lists into an object, and there's a single function that gets the data based on the data-val of the clicked button:
$(document).ready(function () {
var myVals = {
opt1: ["AAAA", "BBBB", "NNN", "JJJJJ"],
opt2: ["KKKK", "FFFF", "NNN", "TTTTT"],
opt3: ["MMM", "NNN", "OOOO", "PPPPP"]
}
$(".listy").click(function () {
$('#items option').remove();
var clickedButton = $(this);
var valueList = myVals[clickedButton.data('vals')];
var option = '';
for (i = 0; i < valueList.length; i++) {
option += '<option value="' + this.id + valueList[i] + '">' + valueList[i] + '</option>';
}
$('#items').append(option);
});
});
Now when you add more buttons, you don't add more code.

Categories