Append Dropdown Form using javascript - Laravel - javascript

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

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

how to add items to dynamic drop down list in laravel using ajax JQuery

friends, I am facing an issue in Ajax actually. My code is working fine when the page is loaded. But When I click on the add button to add a new row for second entry it doesn't work. When Page loaded, it's working perfect When I click on Add ButtonAfter clicking on Add Button, It add duplicate text in drop-down box
Here is my code
$(document).ready(function(){
var experienceCount = 1;
experience_field(experienceCount);
function experience_field(number)
{
html = '<div class="row">'
html += '<div class="col-3"><div class="form-group"><label for="PreviousHospital">Previous Hospital</label><select class="form-control select2" name="PreviousHospital[]" id="PreviousHospital" style="width: 100%;"><option selected="selected">Select Previous Hospital</option></select></div></div>';
$.ajax({
url: "{{ route('previousHospital') }}",
method:'get',
data:$(this).serialize(),
dataType:'json',
success:function(data)
{
$.each(data, function(value, text){
$("#PreviousHospital").append('<option value="' + text.Hospital + '">' + text.Hospital + '</option>');
});
}
});
html += '<div class="col-2"><div class="form-group"><label for="Experience">Experience</label><input type="text" class="form-control" name="Experience[]" id="Experience" required></div></div>';
html += '<div class="col-3"><div class="form-group"><label for="WorkCountry">Country</label><select class="form-control select2" name="WorkCountry[]" id="WorkCountry" style="width: 100%;"><option selected="selected">Select Country</option></select></div></div>';
html += '<div class="col-3"><div class="form-group"><label for="WorkCity">City</label><select class="form-control select2" name="WorkCity[]" id="WorkCity" style="width: 100%;"><option selected="selected">Select City</option></select></div></div>';
if(number > 1)
{
html += '<div class="col-1"><div class="form-group"><label style="color: white;">Button</label><button type="button" name="experienceRemove" id="" class="btn btn-block btn-outline-danger btn-sm experienceRemove form-control" >Remove</button></div></div></div>';
$('.experience').append(html);
}
else
{
html += '<div class="col-1"><div class="form-group"><label style="color: white;">Button</label><button type="button" name="experienceAdd" id="experienceAdd" class="btn btn-block btn-outline-success btn-sm form-control">Add</button></div></div></div>';
$('.experience').html(html);
}
}
$(document).on('click', '#experienceAdd', function(){
experienceCount++;
experience_field(experienceCount);
});
$(document).on('click', '.experienceRemove', function(){
experienceCount--;
$(this).closest(".row").remove();
});
});
You can check all images, in the first image, when I load the page. It works fine and populates the data to the dropdown list too. But if I click on the add button to add more dynamic fields so the Ajax doesn't work, it adds data in first loaded Dropdown list not in second dropdown list.
What i need, i need it should add data in all dropdowns lists but not duplicate as you can see duplicate items in images. if user click add button.
I solved the problem, I was using the ID instead of Class name
$.ajax({
url: "{{ route('previousHospital') }}",
method:'get',
data:$(this).serialize(),
dataType:'json',
success:function(data)
{
$('.PreviousHospital').find('option').remove();
$(".PreviousHospital").append('<option selected="selected">Select Previous Hospital</option>');
$.each(data, function(value, text){
$(".PreviousHospital").append('<option value="' + text.Hospital + '">' + text.Hospital + '</option>');
});
}
});
Add this before appened with eaxh
$('#PreviousHospital').find('option').remove();

Display data after choose product name using ajax

I try to use ajax output data from database I pass data product_name and product weight How can i display product weight out of
Now my Output
<select>category</select> //after select category It will display product name
<select>productname</select> //after select productname How can i display my product weight outof select tag
i want to display <span>product_weight</span> after I choose product_name
Here is my AJAX call . i try to console my data i get product_weight in my data already.
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findProductName')!!}',
data:{'id':cat_id},
success:function(data){
// console.log('success');
console.log(data);
// console.log(data.length);
op+='<option value="0" selected disabled>chose product</option>';
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].id_p+'" name="id_p">'+data[i].product_name+data[i].product_weight+'</option>';
}
div.find('.productname').html(" ");
div.find('.productname').append(op);
// console.log(data.length);
},
error:function(){
}
});
here is my html
<select style="width:50%;" class="productcategory" id="prod_cat_id" name="id_c[]">
<option value="0" disabled="true" selected="true">category</option>
#foreach($category as $c)
<option value="{{$c->id_c}}" name="id_c" id="id_c">{{$c->category_name}}</option>
#endforeach
</select>
<select style="width:48%;" class="productname" name="id_p[]">
<option value="0" disabled="true" selected="true"> productname</option>
</select>
here is my append jeavescript
<script type="text/javascript">
var i = 0;
$(document).ready(function() {
$('#add-form').click(function() {
i++;
$('#add-me').append(
'<tbody id="row'+i+'"><tr>'+
'<td class="col-md-7">'+
'<select style="width:50%;" class="productcategory" id="prod_cat_id" name="id_c['+ i +']"><option value="0" disabled="true" selected="true">category</option>#foreach($category as $c)<option value="{{$c->id_c}}" name="id_c[]" id="id_c[]">{{$c->category_name}}</option>#endforeach</select><select style="width:48%;" class="productname" name="id_p['+ i +']"><option value="0" disabled="true" selected="true"> product name</option></select>'
+'</td>'
+'<td class="col-md-1">'
+'<div id="target_div_where_to_display_weight['+i+']" name="target_div_where_to_display_weight['+i+']">'
+'</div>'
+'<td class="col-md-1">'
+'<input id="quantity" type="text" name="quantity_box[]" class="form-control"/>'
+'</td>'
+'<td class="col-md-1">'
+'<input id="unit_price" type="text" name="unit_price[]" class="form-control"/>'
+'</td>'
+'<td class="col-md-1">'
+'<input id="price" type="text" name="price[]" class="form-control"/>'
+'</td>'
+'<td class="col-md-2">'
+'<button id="'+i+'" type="button" class="btn btn-danger delegated-btn">Delete</button>'
+'</td>'
+'</tr></tbody>'
);
$('button.btn.btn-danger').click(function() {
var whichtr = $(this).closest("tr");
whichtr.remove();
});
});
});
</script>
here is my output look like
update
You can store product_weight in a new tag attribute inside each option tag, like "data-weight". In order to display the corresponding weight you would just need to do this:
$("select.productname").on("change",function(){
var weight = $(this).find(":selected").data("weight"); // .attr("data-weight");
var span = "<span>"+weight+"</span>";
$("#target_div_where_to_display_weight").html(span);
});
UPDATE
In your ajax request replace:
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].id_p+'" name="id_p">'+data[i].product_name+data[i].product_weight+'</option>';
}
by
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].id_p+'" name="id_p" data-product_weight="'+data[i].product_weight+'">'+data[i].product_name+data[i].product_weight+'</option>';
}
and in the code i wrote before replace the first instruction by:
var weight = $(this).find(":selected").data("product_weight"); // or .attr("data-product_weight");
UPDATE 2
If you want to append to a div the weight of each product you choose, the should look like this:
First, change your "#target_div_where_to_display_weight" div by a "<div id='weights_wrapper'></div>", then change the first function (on change) by:
<pre>$("select.productname").on("change",function(){
var prod = $(this).find(":selected"); // .attr("data-weight");
var weight = prod.data("product_weight");
var id_p = prod.val();
var added_content = "";
var content = "<div class='weight' data-ip_p='"+id_p+"'><span>"+weight+"</span>"+added_content+"</div>";
$("#weights_wrapper").append(content);
});</pre>
In this way you can add anchor tags to manage every weight's block. For example, if you want to delete a weight after adding it, you could set added_content = ''; and then createthe following function:
<pre>$("#weights_wrapper").on("click",".close_weight",function(){
$(this).parent().remove();
});</pre>

add input type select with options in Javascript

I am creating a order form and i am new programming. the idea is that the customer can add new box to order a new product with the quantity. with this code i can create a box with products but i didn't get to put a quantity box beside of the product box. I would like to create one for the products and another one for quantity and when the customer click on New Product create a new product list and a quantity list or a quantity field to enter the value.
I tryed copie the document.create... and change the div, but i don`t know how to direct to another choices. I appreciate if you guys can help-me. Thank you.
JavaScript
var choices = [
"Product1",
"Product2",
"Product3"];
function addInput(divName) {
var newDiv = document.createElement('div');
var selectHTML = "";
selectHTML="<select>";
for(i = 0; i < choices.length; i = i + 1) {
selectHTML += "<option value='" + choices[i] + "'>" + choices[i] + "</option>";}
selectHTML += "</select>";
newDiv.innerHTML = selectHTML;
document.getElementById(divName).appendChild(newDiv);
var Div = document.createElement('div');
var selectHTML = "";
selectHTML="<select>";
for(i = 0; i < choices.length; i = i + 1) {
selectHTML += "<option value='" + choices[i] + "'>" + choices[i] + "</option>";}
selectHTML += "</select>";
Div.innerHTML = selectHTML;
document.getElementById(divName).appendChild(Div);
HTML
<form class="new" method="post" action="phppage">
<fieldset id="products"> <legend> PRODUCTS </legend>
<select name="tProduct" id="cProduct">
<optgroup label="GALLON BAG">
<option>Product1</option>
<option>Product2</option>
<option>Product3</option>
</optgroup>
</select>
<label for="cQuantity">Quantity:<span style="color:red">*</span></label> <input type="number" name="tQuantity" id="cQuantity" placeholder="Qnt" min="0" max="9999" required/>
<div id="dynamicInput"></div>
<input type="button" value="New Product" onclick="addInput('dynamicInput');" />
My suggest is that you wrap the element you wanna clone in a div, and clone it when user click the button then put it under dynamicInput
function addInput(divName) {
var copy = document.getElementById('forclone').cloneNode(true);
document.getElementById(divName).appendChild(copy);
}
document.getElementById('button').onclick = function(){
addInput('dynamicInput');
}
<form class="new" method="post" action="phppage">
<fieldset id="products"> <legend> PRODUCTS </legend>
<div id = 'forclone'>
<select name="tProduct" id="cProduct">
<optgroup label="GALLON BAG">
<option>Product1</option>
<option>Product2</option>
<option>Product3</option>
</optgroup>
</select>
<label for="cQuantity">Quantity:<span style="color:red">*</span></label> <input type="number" name="tQuantity" id="cQuantity" placeholder="Qnt" min="0" max="9999" required/>
</div>
<div id="dynamicInput"></div>
<input type="button" value="New Product" id = 'button' />
i would like to say thank you to Z.better because i used the idea that he posted so solve this problem i only made some changes. Follow below the script that worked with me. I am using now. I am sharing this because if someone have this doubt this is the solution.
<script>
function addInput(divName) {
var copy = document.getElementById('forclone').cloneNode(true);
document.getElementById(divName).appendChild(copy);
}
</script>
and
<form class="new" method="post" action="phppage">
<fieldset id="products"> <legend> PRODUCTS </legend>
<div id = 'forclone'>
<select name="tProduct" id="cProduct">
<optgroup label="GALLON BAG">
<option>Product1</option>
<option>Product2</option>
<option>Product3</option>
</optgroup>
</select>
<label for="cQuantity">Quantity:<span style="color:red">*</span></label> <input type="number" name="tQuantity" id="cQuantity" placeholder="Qnt" min="0" max="9999" required/>
</div>
<div id="dynamicInput"></div>
<input type="button" value="New Product" onclick="addInput('dynamicInput');" />
Thank you guys, this website is amazing.

JQuery - Select options are not appended on change event

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>

Categories