Display data after choose product name using ajax - javascript

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>

Related

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

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

appended select option is viewable in HTML but not detectable

I have a button that will update my select. Here is the code:
$("#add_row").on('click', function(){
var table = $("#ingredients_info_table");
var count_table_tbody_tr = $("#ingredients_info_table tbody tr").length;
var row_id = count_table_tbody_tr + (Math.floor(Math.random()*1000));
var html = '<tr id="row_'+row_id+'"><td><select class="form-control" data-row-id="row_'+row_id+'" id="ingredient_'+row_id+'" name="ingredient[]" onchange="getIngredientAmount(\''+row_id+'\')" style="width:100%;" required><option value="" selected disabled hidden></option>'
html += '</select>'+'</td><td><label for="amount"><i id="amount_unit_'+row_id+'" >Amount Unit</i> x</label><input type="number" name="amount[]" id="amount_'+row_id+'" class="form-control" required style="display: inline-block;"></td>'+
'<td><button type="button" class="btn btn-primary" onclick="removeRow(\''+row_id+'\')"><i class="fa fa-times"></i></button></td>'+
'</tr>';
$.ajax({
url: "../api/ajax/getInventory.php",
type: "post",
dataType: "json",
success: function(response2){
// console.log(response2["data"]);
// console.log(Object.keys(response2["data"][0]).length);
for (var i = 0; i < response2["data"].length; i++) {
$("select#ingredient_"+row_id).append('<option value="'+response2['data'][i][0]+'">'+response2['data'][i][1]+'</option>');
$("select#ingredient_"+row_id).trigger('chosen:updated').change();
}
}
});
if(count_table_tbody_tr >= 1) {
$("#ingredients_info_table tbody tr:last").after(html);
}
else {
$("#ingredients_info_table tbody").html(html);
}
});
It is working properly. The dropdown list is updated.
The problem here is whenever I tried to console.log() the selector for the option, it appears as if the selector is empty, but based on the link, the dropdown menu is updated.
Here is the console.log():
console.log($('#ingredients_info_table tbody tr[id^="row_"]:last td select').html());
And here is the output for the console.log():
<option value="" selected="" disabled="" hidden=""></option>
//this empty option is statically inserted, not dynamic.
My question is, how should I display or find the updated set of options after it is dynamically updated (after the .append() is used) so that I could use those updated elements.
The reason it is empty because you are calling it before the data is populated through ajax. You have to get your html inside success callback then call the other ajax block.
Also you don't have to count the number of rows before insertion. You can use .append() which will always insert after all children.
See this example:
$("#add_row").on('click', function() {
var table = $("#ingredients_info_table");
var count_table_tbody_tr = $("#ingredients_info_table tbody tr").length;
var row_id = count_table_tbody_tr + (Math.floor(Math.random() * 1000));
var html = `
<tr id="row_${row_id}">
<td><select class="form-control" data-row-id="row_${row_id}" id="ingredient_${row_id}" name="ingredient[]" onchange="getIngredientAmount(${row_id})" style="width:100%;" required>
<option value="" selected disabled hidden></option>
</select>
</td>
<td>
<label for="amount"><i id="amount_unit_${row_id}">Amount Unit</i> x</label>
<input type="number" name="amount[]" id="amount_${row_id}" class="form-control" required style="display: inline-block;">
</td>
<td>
<button type="button" class="btn btn-primary" onclick="removeRow(${row_id})"><i class="fa fa-times"></i></button>
</td>
</tr>
`;
$("#ingredients_info_table tbody").append(html);
$.ajax({
url: "https://jsonplaceholder.typicode.com/todos/",
type: "get",
dataType: "json",
success: function(response2) {
console.log(response2.length);
// console.log(response2["data"]);
// console.log(Object.keys(response2["data"][0]).length);
for (var i = 0; i < response2.length; i++) {
$("select#ingredient_" + row_id).append('<option value="' + response2[i]['id'] + '">' + response2[i]['title'] + '</option>');
//$("select#ingredient_" + row_id).trigger('chosen:updated').change();
}
console.log($('#ingredients_info_table tbody tr[id^="row_"]:last td select').html());
}
});
// no need for this code
/* if (count_table_tbody_tr >= 1) {
$("#ingredients_info_table tbody tr:last").after(html);
} else {
$("#ingredients_info_table tbody").html(html);
}*/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='ingredients_info_table'>
<tbody></tbody>
</table>
<div id='add_row'>
Add Row
</div>

How to Set id for each row of a column

This is one of the rows in my table.
<td>
<select id="itemcodeid" name="itemcode[]" class="form-control itemcode">
<option></option>
#foreach($productsdata as $d)
<option>{{$d->itemcode}}</option>
#endforeach
</select>
</td>
I am using Select2 to fill data.
<script type="text/javascript">
$("#itemcodeid").select2
({
placeholder: "Select Itemcode",
allowClear: true
});
</script>
But when i add rows to table how to refer the upcoming rows with id. Because this works only on first row.
Below is image of first row.
But in Other rows i am unable to type and select(second image) because id reference is not done so kindly tell how to refer id of the rows added.
Help or suggestion will be highly useful.Thank You.
This is the code which gets executed when i press the plus button(verify image).
<script type="text/javascript">
$('.addrow').on('click',function()
{ addrowfn();
});
function addrowfn()
{
var tr = '<tr>'+
'<td>'+
'<select id="itemcodeid" name="itemcode[]" class="form-control itemcode">'+
'<option></option>'+
'#foreach($productsdata as $d)'+
'<option>{{$d->itemcode}}</option>'+
'#endforeach'+
'</select>'+
'</td>'+
'<td><input type="text" name="proname[]" class="form-control proname"></td>'+
'<td><input type="text" name="actualprice[]" class="form-control actualprice"></td>'+
'<td><input type="text" name="discount[]" class="form-control discount"></td>'+
'<td><input type="text" name="gst[]" class="form-control gst"></td>'+
'<td><input type="text" name="quantity[]" class="form-control quantity"></td>'+
'<td><input type="text" name="finalprorate[]" class="form-control finalprorate"></td>'+
'<td><input type="text" name="finalbillrate[]" class="form-control finalbillrate"></td>'+
'<td>'+
'<a href="#" class="remove btn btn-danger">'+
'<center>'+
'<i class="glyphicon glyphicon-remove"></i>'+
'</center>'+
'</a>'+
'</td>'+
'</tr>';
$('tbody').append(tr);
}
$('body').on('click','.remove',function()
{ var l=$('tbody tr').length;
console.log(l);
if(l==1)
{ alert('You Cannot Remove all Rows!!!');
}
else
$(this).parent().parent().remove();
});
</script>
Kindly Tell me if there are any corrections.
I'm not sure if this code works, as I haven't tested it, but I would, at minimum, make these two changes:
Listen for the appended node using a MutationObserver, then turn
the regular select into a select2();
Create a variable to keep track of the rows, and make each select's ID dynamic, e.g. 'itemcodeid_3' and 'itemcodeid_5' etc. Do the same for 'name' attribute
var target = document.getElementById('<INSERT_ID_HERE>');
var rows = 1;
if (target) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation && mutation.addedNodes) {
mutation.addedNodes.forEach(function(el) {
if (el && el.nodeName === "SELECT") {
$(el).select2();
}
});
}
});
});
observer.observe(target, {
childList: true
});
} // end if
$('.addrow').on('click',function()
{
addrowfn();
});
function addrowfn()
{
rows++;
var tr = '<tr>'+
'<td>'+
'<select id="itemcodeid_" ' + rows + ' name="itemcode_' + rows + '[]" class="form-control itemcode">'+
'<option></option>'+
'#foreach($productsdata as $d)'+
'<option>{{$d->itemcode}}</option>'+
'#endforeach'+
'</select>'+
'</td>'+
'<td><input type="text" name="proname[]" class="form-control proname"></td>'+
'<td><input type="text" name="actualprice[]" class="form-control actualprice"></td>'+
'<td><input type="text" name="discount[]" class="form-control discount"></td>'+
'<td><input type="text" name="gst[]" class="form-control gst"></td>'+
'<td><input type="text" name="quantity[]" class="form-control quantity"></td>'+
'<td><input type="text" name="finalprorate[]" class="form-control finalprorate"></td>'+
'<td><input type="text" name="finalbillrate[]" class="form-control finalbillrate"></td>'+
'<td>'+
'<a href="#" class="remove btn btn-danger">'+
'<center>'+
'<i class="glyphicon glyphicon-remove"></i>'+
'</center>'+
'</a>'+
'</td>'+
'</tr>';
$('tbody').append(tr);
}
$('body').on('click','.remove',function()
{
var l=$('tbody tr').length;
console.log(l);
if(l==1)
{
alert('You Cannot Remove all Rows!!!');
}
else {
$(this).parent().parent().remove();
}
});
It may not work because it sees the appended node as instead of ...have to test
Additionally, you may wish to look at using a template engine for this, such as John Resig's jQuery solution or Mustache.js,
Handlebars.js

Index-Id always has the same value for every input

So I have dynamically created form that I would like to get index-id of certain inputs with names like championSpell[] I need to know which one is which so i thought of using index-id but it changes every inputs index to the same value when pressing add spell button. You can test the problem here http://89.69.172.125/test.php
$(function() {
$('body').on('click', '#addSpell',function() {
$(
'<p><select name="change[]" id="change[]" onchange="val(this)"><option value="Passive">Passive</option><option value="Q" selected>Q</option><option value="W">W</option><option value="E">E</option><option value="R">R</option></select><label for="var"><input type="text" id="championSpell[]" name="championSpell[]" data-id="" readOnly="true"><br><textarea type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> Add Change Remove Spell</p>').appendTo($(this).next());
$('input[name="championSpell[]"]').attr('data-id', y);
y++;
return false;
});
});
Bad practice aside
(as in, using label as a block element)
(using jquery to create such a template file)
(etc)
(etc)
The problem resides with the variable y not being initialized, and changing all data-id values in the end. Try this updated (and a bit more readable) bit
$(function () {
var y = 0;
$('#addSpell').on('click', function(){
$(['<p>',
'<select name="change[]" id="change[]" onchange="val(this)">',
'<option value="Passive">Passive</option>',
'<option value="Q" selected>Q</option>',
'<option value="W">W</option>',
'<option value="E">E</option>',
'<option value="R">R</option>',
'</select>',
'<label for="var">',
'<input type="text" id="championSpell[]" name="championSpell[]" data-id="' + y +'" readOnly="true">',
'<br>',
'<textarea type="text" id="p_scnt" size="20" name="p_scnt_' + y + '" value="" placeholder="Enter Description">',
'<select>','' +
'<option value="buff">Buff</option>',
'<option value="nerf">Nerf</option>',
'<option value="new">New</option>',
'<option value="change">Change</option>',
'<option value="bugfix">Bugfix</option>',
'</select>',
'</label>',
'Add Change',
'Remove Spell',
'</p>'].join('')).appendTo($(this).next());
y++;
return false;
});
});
In you code $('input[name="championSpell[]"]').attr('data-id', y); this will change all inputs data-id. So instead of that directly add its data-id.
Like data-id="'+y+'"
I HAVE UPDATE YOUR CODE.
PLEASE TRY THIS CODE
$(function() {
$('body').on('click', '#addSpell',function() {
var championdataid = $('input[id="champion[]"]').attr('data-id');
$(
'<p><select name="change[]" id="change[]" onchange="val(this)"><option value="Passive">Passive</option><option value="Q" selected>Q</option><option value="W">W</option><option value="E">E</option><option value="R">R</option></select><label for="var"><input type="text" id="championSpell[]" name="championSpell[]" data-id="'+y+championdataid +'" readOnly="true"><br><textarea type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> Add Change Remove Spell</p>').appendTo($(this).next());
//$('input[name="championSpell[]"]').attr('data-id', y);
y++;
return false;
});
});

Categories