JQuery - Select options are not appended on change event - javascript

I'm having trouble adding select options to a select element. I have two select elements and I want to generate the second elements options based on the first's value.
First I add elements to the first box upon loading every element
The user chooses an option in the first box and based on that the second select box gets select options to choose from
The below code is not working for me, because after selecting an option in the first select box, no options are added to the 2nd.
I'm using Bootstrap-Select jQuery plugin
Does anyone have any suggestions? :/
Thank you.
JQuery:
$(window).bind("load", function () {
var connection = {wifi: 'Wifi', ethernet: 'Ethernet'};
for (var c in connection) {
$("#connection").append('<option value="' + connection[c] + '">' + connection[c] + '</option>');
}
});
$("#connection").on('change', function () {
var wifi_devices = {smartphone: 'Smartphone', tablet: 'Tablet', notebook: 'Notebook', desktop: 'Desktop'};
var ethernet_devices = {notebook: 'Notebook', desktop: 'Desktop'};
conn_type = $('#connection').find(":selected").text();
if (conn_type == 'Ethernet') {
for (var e in ethernet_devices) {
$('#device').append('<option value="' + ethernet_devices[e] + '">' + ethernet_devices[e] + '</option>')
}
} else {
for (var w in wifi_devices) {
$('#device').append('<option value="' + wifi_devices[w] + '">' + wifi_devices[w] + '</option>')
}
}
});
HTML:
<div class="jumbotron margin-top-25 fade in" id="testinput">
<div class="row">
<!--connection type input-->
<div class="col-lg-3">
<div class="input-group">
<select class="form-control selectpicker" id="connection" data-size="5" data-live-search="true" title="Connection"></select>
</div>
</div>
<!--device type input-->
<div class="col-lg-3">
<div class="input-group">
<select class="form-control selectpicker" id="device" data-size="5" data-live-search="true" title="Device"></select>
</div>
</div>
</div>
</div>

If you don't want to have the second select options available on load, add the click event handler so if you choose your selected option from first select, second select options get added. Also remove previous options on second select on every event.
$(window).bind("load", function () {
var connection = {wifi: 'Wifi', ethernet: 'Ethernet'};
for (var c in connection) {
$("#connection").append('<option value="' + connection[c] + '">' + connection[c] + '</option>');
}
});
$("#connection").on('change click', function () {
var wifi_devices = {smartphone: 'Smartphone', tablet: 'Tablet', notebook: 'Notebook', desktop: 'Desktop'};
var ethernet_devices = {notebook: 'Notebook', desktop: 'Desktop'};
conn_type = $('#connection').find(":selected").text();
// Removing previous options
$('#device').find('option').remove();
if (conn_type == 'Ethernet') {
for (var e in ethernet_devices) {
$('#device').append('<option value="' + ethernet_devices[e] + '">' + ethernet_devices[e] + '</option>')
}
} else {
for (var w in wifi_devices) {
$('#device').append('<option value="' + wifi_devices[w] + '">' + wifi_devices[w] + '</option>')
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="jumbotron margin-top-25 fade in" id="testinput">
<div class="row">
<!--connection type input-->
<div class="col-lg-3">
<div class="input-group">
<select class="form-control selectpicker" id="connection" data-size="5" data-live-search="true" title="Connection"></select>
</div>
</div>
<!--device type input-->
<div class="col-lg-3">
<div class="input-group">
<select class="form-control selectpicker" id="device" data-size="5" data-live-search="true" title="Device"></select>
</div>
</div>
</div>
</div>

Related

How to append options to dynamically created select elements with jquery in Laravel blade file

Good day. I have a form in which I can dynamically add groups on input elements. I have select elements among them.
In my controller, I returned the data to populate the select element to the blade file.
After this, I then append the data to the select element using Jquery.
The problem is that, this works for the initial form group (elements), but it does not work for the dynamically generated one.
What could be the cause please? Or is there a better way of doing this?
This are my blade (html) and jquery codes
Blade file
<button id="add_counsel_button" type="button">Add</button>
<h5>Step 3: Case Counsels</h5>
<div id="dynamic_wrapper">
<div class="field_wrapper" id="row1">
<input type="text" style="width:50%!important;display: inline!important;"
name="counsels[]" id="name1" data-number=1 class="form-control counsel-name">
<input type="hidden" name="counsel_id[]" id="id1">
<div class="counsel-list" id="counsel-list1"></div>
<select name="roles[]" style="width:21%!important;display: inline!important;"
class="form-control roles-list">
<option value="#">Select Role</option>
</select>
<select name="representations[]"
style="width:21%!important;display: inline!important;"
class="form-control reps-list">
<option value="#">Select Representation</option>
</select>
</div>
</div>
Jquery:
$(document).ready(function() {
//Setting the value from the controller
var roles = {!! json_encode($roles->toArray()) !!};
var reps = {!! json_encode($representations->toArray()) !!};
$.each(roles, function(i, item) {
$('.roles-list').append($('<option>', {
value: item.id,
text: item.role
}));
}); //want this to be appended to all 'roles-list' classes
$.each(reps, function(i, item) {
$('.reps-list').append($ '<option>', {
value: item.id,
text: item.type
});
});
$(document).on('click', '#add_counsel_button', function() {
i++;
$('#dynamic_wrapper').append('<div class="field_wrapper" id="row' + i +
'"><input type="text" id="name' + i + '" data-number="' + i +
'" style="width:50%!important;display: inline!important;" name="counsels[]" class="form-control counsel-name"><input type="hidden" name="counsel_id[]" id="id' +
i + '"><div class="counsel-list" id="counsel-list' +
i +
'"></div> <select name="roles[]" style="width:21%!important;display: inline!important;" class="form-control roles-list"> <option value="#">Select Role</option></select><select name="representations[]" style="width:21%!important;display: inline!important;"class="form-control reps-list"><option value="#">Select Representation</option></select><a href="javascript:void(0);" class="remove_button" id="' +
i +
'" style="display: inline!important;"title="Remove field"> <span class="fa fa-trash"></span></a></div>'
);
});
});
You are appending the options before appending the select tag. Change the code like below
$(document).ready(function() {
//Setting the value from the controller
var roles = {!! json_encode($roles->toArray()) !!};
var reps = {!! json_encode($representations->toArray()) !!};
roles_str = '';
reps_str = '';
$.each(roles, function(i, item) {
roles_str += '<option value="'+item.id+'">'+item.role+'</option>';
}); //want this to be appended to all 'roles-list' classes
$.each(reps, function(i, item) {
reps_str += '<option value="'+item.id+'">'+item.type+'</option>';
});
$(document).on('click', '#add_counsel_button', function() {
i++;
$('#dynamic_wrapper').append('<div class="field_wrapper" id="row' + i +
'"><input type="text" id="name' + i + '" data-number="' + i +
'" style="width:50%!important;display: inline!important;" name="counsels[]" class="form-control counsel-name"><input type="hidden" name="counsel_id[]" id="id' +
i + '"><div class="counsel-list" id="counsel-list' +
i +
'"></div> <select name="roles[]" style="width:21%!important;display: inline!important;" class="form-control roles-list"> <option value="#">Select Role</option>'+roles_str+'</select><select name="representations[]" style="width:21%!important;display: inline!important;"class="form-control reps-list"><option value="#">Select Representation</option>'+reps_str+'</select><a href="javascript:void(0);" class="remove_button" id="' +
i +
'" style="display: inline!important;"title="Remove field"> <span class="fa fa-trash"></span></a></div>'
);
});
});

Append Dropdown Form using javascript - Laravel

I have a form with a dropdown. I want to make the dropdown to appear multiple times on click of a button. Like picture below:
If I click "add more student" button, another student's dropdown should appear.
Here is my code
<form_answer id = "more_student" >
<div id ="student_id" class="form-group">
<label class="form-control-label" for="student_id">{{ __('Student') }}</label>
<select type="text" name="student_profile_id" id="student_id" class="form-control">
<option disabled selected> -- select an option -- </option>
#if($student)
#foreach($student as $data)
<option value="{{$data->id}}"> {{$data->student_name}}</option>
#endforeach
#endif
</select>
</div>
<div class = "text-right">
<a class="btn btn-success mt-4" id = "btn_add">Add More Student</a>
</div>
And the script:
<script>
$(document).ready(function(){
$('#btn_add').click(function(){
add_row();
});
});
var id = 0;
function add_row(){
id++;
var html = '<div id ="student_id" class="form-group">' +
'<label class="form-control-label" for="student_id">{{ __("Student") }}</label>' +
'<select type="text" name="student_profile_id" id="student_id" class="form-control">' +
'<option disabled selected> -- select an option -- </option>' +
'#if($student)' +
'#foreach($student as $data)' +
'<option value="{{$data->id}}"> {{$data->student_name}}</option>' +
'#endforeach' +
'#endif' +
'</select>' +
'</div>' ;
$("more_student").append(html);
}
</script>
This code is not working. When I click the button, nothing happens.Can anyone help me with this?
First you forgot # before $("#more_student").append(html); and if you have multiple student_profile_id then you have to make it array like name="student_profile_id[]" and every control has unique id
try this one
<script>
var students = eval({!! $student !!});
$(document).ready(function(){
$('#btn_add').click(function(){
add_row();
});
});
function add_row(){
var index = $('input[name="student_profile_id[]"]').length+1;
var html = `<div id="student_div_id`+index+`" class="form-group">
<label class="form-control-label" for="student_id">{{ __("Student") }}</label>'
<select type="text" name="student_profile_id[]" id="student_id`+index+`" class="form-control">
<option disabled selected> -- select an option -- </option>`;
$.each(students,function(ind,el)){
html+=`<option value="`+el.id+`"> `+el.student_name+`</option>`;
});
html+=`</select>
</div>`;
$("#more_student").append(html);
}
</script>
You are trying to inject Blade template after rendering inside your Javascript which is not possible. You should generate your var html outside of your add_row function and then insert it upon button click:
var html = '<div id ="student_id" class="form-group">' +
'<label class="form-control-label" for="student_id">{{ __("Student") }}</label>' +
'<select type="text" name="student_profile_id" id="student_id" class="form-control">' +
'<option disabled selected> -- select an option -- </option>'
#if($student)
#foreach($student as $data)
+'<option value="{{$data->id}}"> {{$data->student_name}}</option>'
#endforeach
#endif
+'</select>' +
'</div>';
function add_row() {
id++;
$("#more_student").append(html);
}

Append items to a list from API in Javascript

Im trying to display currencies in a dropdown list by setting it's html property of all the items(currencies) I retrieve.
Here is my code:
var currencyDropdownData = "";
currencyDropdownData.length = 0;
if (confirmationData != null)
{
currencyDropdownData = confirmationData.Currencies;
console.log(currencyDropdownData)
var BudgetSelectData = "";
//BudgetSelectData += '<option selected value="-1">Please Select</option>'
for (var currency = 0; currency < currencyDropdownData.length; currency++) {
console.log(currencyDropdownData[currency].Name);
BudgetSelectData += '<option value="' + currencyDropdownData[currency].Id + '">' + currencyDropdownData[currency].CurrencyText + currencyDropdownData[currency].Name + '</option>'
}
console.log(BudgetSelectData);
$('#budgetCurrency').html(BudgetSelectData);
}
Here is the html:
<div class="row rowSpace">
<div class="col-md-12">
<div class="col-md-3">
<label>Budget (Optional)</label>
</div>
<div class="col-md-6">
<div class="col-md-10 col-sm-10 col-xs-11 noPadding">
<select validateme="true" class="form-control fullWidth" id="budgetCurrency" placeholder="€ (Euro)" data-validation="length alphanumeric" data-validation-length="min1">
</select>
</div>
<div class="col-md-2 col-sm-2 col-xs-1 noPadding" linkedval="budgetCurrency"></div>
</div>
</div>
In the console I can see the html is being created correctly and each of the currencies are coming back, however nothing is being displayed in the dropdown list
maybe this is what you looking for
for (var currency = 0; currency < currencyDropdownData.length; currency++) {
console.log(currencyDropdownData[currency].Name);
var option = $("option").attr("value", currencyDropdownData[currency].Id)
.val(currencyDropdownData[currency].CurrencyText + currencyDropdownData[currency].Name);
$('#budgetCurrency').append(option);
}

Jquery add and remove DIV tag row based on select value

I found this great stackoverflow post that does what I need: add and remove rows based on a select value, but the only difference is that in my case, I don't have a table but blocks of divs. In the table example it works fine, but with divs it fails.
I've been using the console to try to fix it to no avail. It seems there are problems with the index value and the increment, but I don't undertand why with a table row works but with divs it doesnot. Could anyone take a look?
Here's a jsfiddle that shows the issue: http://jsfiddle.net/njes3w1a/1/
This is my script:
if ($('#returnRequest').length) {
var row_i = 0;
function emptyRow() {
row_i++;
this.obj = $('<div class="return-row control-group row"></div>');
this.obj.append('<div class="col-md-6"><label class="control-label">Serial number</label><input type="text" class="form-control" value=""/></div><div class="col-md-4"><label class="control-label">Item is</label><select class="form-control"><option value="">Select</option><option value="1">New and unopened</option><option value="2">Defective</option></select></div>');
}
function refresh(new_count) {
//how many applications we have drawed now ?
console.log("New count= " + new_count);
if (new_count > 0) {
$("#noa_header").show();
} else {
$("#noa_header").hide();
}
var old_count = parseInt($('#productRowWrapper').children().length);
console.log("Old count= " + old_count);
//the difference, we need to add or remove ?
var rows_difference = parseInt(new_count) - old_count;
console.log("Rows diff= " + rows_difference);
//if we have rows to add
if (rows_difference > 0) {
console.log('enetered a');
for (var i = 0; i < rows_difference; i++)
$('#productRowWrapper').append((new emptyRow()).obj);
} else if (rows_difference < 0) //we need to remove rows ..
{
console.log('enetered b');
var index_start = old_count + rows_difference + 1;
console.log("Index start= " + index_start);
$('.return-row:gt(' + index_start + ')').remove();
console.log(row_i);
console.log(rows_difference);
row_i += rows_difference;
console.log(row_i);
}
}
$('#quantityReturn').change(function () {
refresh($(this).val());
});
}
I would use this code:
if ($('#returnRequest').length) {
function emptyRow() {
this.obj = $('<div class="return-row control-group row"></div>');
this.obj.append(
'<input type="text" class="form-control" value=""/>' +
'<select class="form-control">' +
'<option value="">Select</option>' +
'<option value="1">New and unopened</option>' +
'<option value="2">Defective</option>' +
'</select>');
}
function refresh(count) {
if (count > 0) {
$("#noa_header").show();
} else {
$("#noa_header").hide();
}
var wrapper = $('#productRowWrapper');
while (wrapper.children().length > count)
wrapper.children().last().remove();
while (wrapper.children().length < count)
wrapper.append((new emptyRow()).obj);
}
$('#quantityReturn').change(function () {
refresh(parseInt($(this).val()));
});
}
It does not introduce unnecessary variables and it a bit shorter. Updated fiddle at http://jsfiddle.net/njes3w1a/6/.
you were calculating your strt index wrong add this
var index_start =old_count- Math.abs(rows_difference)-1 ;
Code
if ($('#returnRequest').length) {
var row_i = 0;
function emptyRow() {
row_i++;
this.obj = $('<div class="return-row control-group row"></div>');
this.obj.append('<input type="text" class="form-control" value=""/><select class="form-control"><option value="">Select</option><option value="1">New and unopened</option><option value="2">Defective</option></select>');
}
function refresh(new_count) {
//how many applications we have drawed now ?
console.log("New count= " + new_count);
if (new_count > 0) {
$("#noa_header").show();
} else {
$("#noa_header").hide();
}
var old_count = parseInt($('#productRowWrapper').children().length);
console.log("Old count= " + old_count);
//the difference, we need to add or remove ?
var rows_difference = parseInt(new_count) - old_count;
console.log("Rows diff= " + rows_difference);
//if we have rows to add
if (rows_difference > 0) {
console.log('enetered a');
for (var i = 0; i < rows_difference; i++)
$('#productRowWrapper').append((new emptyRow()).obj);
} else if (rows_difference < 0) //we need to remove rows ..
{
console.log('enetered b');
var index_start =old_count- Math.abs(rows_difference)-1 ;
console.log("Index start= " + index_start);
console.log('.return-row:gt(' + index_start + ')');
$('.return-row:gt(' + index_start + ')').remove();
console.log(row_i);
console.log(rows_difference);
row_i += rows_difference;
console.log(row_i);
}
}
$('#quantityReturn').change(function () {
refresh($(this).val());
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="" id="returnRequest">
<div class="form-group row">
<p class="col-sm-3 control-label">* Quantity to return</p>
<div class="col-sm-9">
<div class="row control-group">
<div class="col-sm-6 control-item" id="signupForename">
<select class="form-control" id="quantityReturn">
<option value="0">Please select</option>
<option value="1">1 item</option>
<option value="2">2 items</option>
<option value="3">3 items</option>
<option value="4">4 items</option>
</select>
</div>
</div>
</div>
</div>
<div class="panel panel-info">
<div class="pane-body">
<div class="form-group row">
<div class="col-sm-9">
<div id="noa_header" style="display: none;">Header</div>
<div id="productRowWrapper"></div>
</div>
</div>
</div>
</div>
</div>

Attempting to print out user input using jQuery

I have a section in my system that allows users to enter ingredients and then when they click 'live preview' each ingredient is printed out in plain text so they can check spelling using jQuery. However it will only print out the first element and not the ones after. Can anyone see why? Here is the fiddle http://jsfiddle.net/X94At/
HTML
<div class="recipe-ingredients pure-u-1 pad8bottom clearfix">
<span class="heading">Ingredients</span>
<div class="ingredients pure-u-1 clearfix">
<div class="ingredient pure-u-1 clearfix">
<p>
<input type="text" id="ingredient_1" name="ingredient[]" placeholder="Ingredient" class="element pure-u-6-24" />
<input type="text" id="quantity_1" name="quantity[]" value="" placeholder="Quantity" class="element pure-u-4-24" />
<select id="selectQuantity_1" name="quantityType[]" class="element pure-u-3-24">
<option value="grams">Grams</option>
<option value="ounces">Ounces</option>
<option value="Pounds">Pounds</option>
</select>
<input type="text" id="alternative_1" name="alternative[]" value="" placeholder="Alternative Ingredient" class="element pure-u-6-24" />
<input type="text" id="addedQuantiy_1" name="addedQuantity[]" value="" placeholder="Quantity per extra person" class="element pure-u-4-24" />
</p>
</div>
</div>
Add Ingredient
</div>
HTML For the Live Preview
<div id="toPopup">
<div class="close">×</div> <span class="ecs_tooltip">End Preview<span class="arrow"></span></span>
<div id="live-preview-display">
<div id="lp-name"></div>
<div id="lp-ingredientslist">
<h3>Ingredients</h3>
</div>
<div id="lp-step">
<h3>Method</h3>
</div>
</div>
</div>
<div class="loader"></div>
<div id="backgroundPopup"></div>
jQuery
$(".ingredient").on('blur change focus', function () {
$('.ingredient p').each(function () {
var i = $('.ingredient p').size(),
el = $(this);
if ($('#lp-ingredientslist .ingredient_' + i).length == 0) {
$("#lp-ingredientslist").append('<span class="ingredient_' + i + '"></span>');
}
var ingredient = el.find('input[name="ingredient[]"]').val(),
quantity = el.find('input[name="quantity[]"]').val(),
quantityType = el.find('select[name="quantityType[]"]').val(),
alternative = el.find('input[name="alternative[]"]').val();
if (!quantity || !ingredient)
return;
var alt = '';
if (alternative.length >= 0) {
alt = ' (you can also use ' + alternative + ')';
}
$('#lp-ingredientslist .ingredient_' + i).html(i + '. ' + quantity + ' ' + quantityType + ' of ' + ingredient + alt + '</br></br> ');
});
});
jQuery to add an ingredient
$('.recipe-ingredients #addNewIngredient').on('click', function () {
var i = $('.recipe-ingredients .ingredient').size() + 1;
$('<div class="ingredient pure-u-1 clearfix"><input type="text" id="ingredient_' + i + '" name="ingredient[]" placeholder="Chocolate" class="element pure-u-6-24" /><input type="text" id="quantity_' + i + '" name="quantity[]" value="" placeholder="Quantity" class="element pure-u-4-24" /><select id="selectQuantity_1" name="quantityType[]" class="element pure-u-3-24"><option value="grams">Grams</option><option value="ounces">Ounces</option><option value="Pounds">Pounds</option></select><input type="text" id="alternative_' + i + '" name="alternative[]" value="" placeholder="Alternative Ingredient" class="element pure-u-6-24" /><input type="text" id="addedQuantiy_' + i + '" name="addedQuantity[]" value="" placeholder="Quantity per extra person" class="element pure-u-4-24" />×</div>').appendTo($('.recipe-ingredients .ingredients'));
Thanks!
Not perfect needs improvement
Working Fiddle
$(".ingredient").on('blur change focus', function () {
this line needs to be replaced by
$('.ingredients').on('blur change focus', function () {
as you dynamically are adding the .ingredient class so the changes would appear at .ingredients....
Update
Fiddle with a new look Credit goes to #WASasquatch for pointing it out...
Hope it helps....!!

Categories