Get values of dynamically add select dropdown multiple values in Laravel 9 - php

I have 2 Select options which are as follow:
<select name="attribute[]" id="attribute" data-id="1" >
<option value="1">Size</option>
<option value="2">Color</option>
</select>
<select name="attribute_value[]" id="attribute_value1" multiple>
<option value="0">Please Select</option>
<select>
and attribute value popup with ajax when change option on attribute
$(document).on('change','.attribute', function() {
let attr_id = $(this).val();
let rowId = $(this).data('id');
$.ajax({
url:"{{ route('admin.getAttributeValue')}}",
type:"post",
data:{
_token:'{{ csrf_token() }}',
id:attr_id,
},
success:function(response){
if(response)
{
var data = JSON.parse(response);
$('#attribute_value'+rowId).empty().append('<option value="0">Please Select value</option>');
for (var key in data) {
$('#attribute_value'+rowId).append('<option value="'+key+'" >'+data[key]+'</option>');
}
}else{
$('#attribute_value'+rowId).empty().append('<option value="0">Please Select value</option>');
}
}
});
});
and in controller
public function getAttributeValue(Request $request)
{
$values = AttributeValue::where('attribute_id',$request->id)->get();
if(count($values))
{
$v=[];
foreach($values as $val)
{
$v[$val->id]=$val->value;
}
return json_encode($v);
}
}
and on button click its add Row
<a href='#' onclick="add_more()">Add Row<a/>
x=1;
function add_more()
{
var wrapper = $('#product_attribute');
var html = '<div class="card " id="c'+x+'"><div class="card-body"><div class="row">';
var attribute = $('#attribute').html();
attribute = attribute.replace("selected","");
var attr = '<div class="col-2"><select name="attribute[]" id="attribute" data-id="'+x+'" class="attribute form-control">'+attribute+'</select></div>';
html += attr;
var val = '<div class="col-3"><select multiple name="attribute_value[]" id="attribute_value'+x+'" class="form-control"><option value="0">Please Select</option></select></div>';
html += val;
html += '</div></div></div>';
wrapper.append(html);
x++;
}
My problem is that
when the form submit the data shows me in this format
Attribute Array
$request->attribute = Array
(
[0] => 1
[1] => 2
)
Attribute value Array
$request->attribute_value = Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 5
[4] => 6
)
In above example I select 2 Values for Size and 3 values for Color
I want to data like in this format
like for each attribute has a array of attribute values
$arr = [];
arr[1] = [1,2],
arr[2] = [4,5,6]
Can any body help me in this matter. Thanx

Related

Optgroup issue in jquery

Actually I have main categories under main categories I have list of products. For first main category I have subcategory and subcategory related products. whichever main category is not having subcategories I am splitting array with comma separator and appending that products to select dropdown. But if main category is having subcategory means I need to do optgroup with options. In optgroup subcatname and related products.
For example, subcatname1=> p1,p2,p3, subcatname2=> p1,p2,p3.
How we can resolve this please help somebody.
Below is HTML,
<select name="category" id="category" />
<option selected ="selected">Select category</option>
<?php foreach($decode as $key => $value) { ?>
<option value="<?php echo $value['category_id']; ?>"><?php echo $value['name']; ?></option>
<?php } ?>
</select>
<select name="category12" class="category12" /></select>
Below is Jquery,
$(document).ready(function(){
$('#category').change(function(){
var category_id=$('#category').val();
$.ajax({
type: "get",
url: 'data_product.php?category_id='+category_id,
success: function(data) {
var products = data.split(",");
state_html = '';
state_html = '<option>Please Select product</option>'
$.each(products, function (index, productName) {
state_html += "<option value='"+productName+"'>"+productName+"</option>";
//var gain=
});
$('.category12').html(state_html);
},
$.each(data, function (index, sub_cat_name) {
state_html += "<optgroup label='"+sub_cat_name+"'>"+sub_cat_name+"
<option value="+products_name+">"+products_name+"</option>
</optgroup>";
//var gain=
});
$('.category12').html(state_html);
},
});
})
});
You should iterate only once for your data and split the productnames from it.
Try the below code,
$(document).ready(function() {
$('#category').change(function() {
var category_id = this.value; // use simply this.value here
$.ajax({
type: "get",
url: 'data_product.php?category_id=' + category_id,
dataType:'json',
success: function(data) {
state_html = '<option>Please Select product</option>'
$.each(data, function(sub_cat_name, product) {
// split all products here
var products = product.split(",");
make optgroup from sub_cat_name key
state_html += "<optgroup label='" + sub_cat_name + "'>" + sub_cat_name;
// loop for all product options
for (var i = , l = products.length; i < l; i++) {
state_html += "<option value='" + products[i] + "'>" + products[i] + "</option>";
}
state_html += "</optgroup>"; // close optgroup here
});
// finally append all options
$('.category12').html(state_html);
}
});
})
});

jquery dynamicaly add new row

I need to dynamically add new rows each time click on add button.i tried to do it as below.i'm using php codeigniter and jquery.i'm new to jquery and i'm struggling on how to append new row in jquery. But this jquery function is not working.pls help me to sole this problem.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p table class="datatable <tr><td width="200">').size() + 1;
$('#addNew').live('click', function() {
alert('ok');
alert(i);
$('<p>
<label for="trainer">Trainer: </label>
<td><select name="state_' + i +'"">
<option></option>
</select>
<select>
<option></option>
</select></td></tr></table>
Remove </p>').appendTo(addDiv);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
echo '<div id="addinput">';
echo '<p>';
echo '<table class="datatable">';
echo '<tr><td width="200">'.form_label('Trainer: ', 'trainer').'</td>';
$options4 = array(
0 => 'Select state',
1 => 'QLD',
2 => 'NSW',
3 => 'VIC',
4 => 'WA',
5 => 'ACT',
6 => 'NT',
7 => 'SA',
8 => 'TAS'
);
$options5[0] = 'Select below';
foreach ($trainers as $row) {
$name = $row->first_name.' '.$row->last_name;
$options5[$row->id] = $name;
}
echo '<td>'.form_dropdown('state', $options4, '', 'class="update_state" id="state"').' '.form_dropdown('trainers[]', $options5, 0).'Add</td></tr>';
echo '</table>';
echo '</p';
echo '</div>';
Hope this example here can help you:
http://fiddle.jshell.net/GxhSR/
The problem may be in your #addnew.click declaration. You are placing the html on separate lines. This can cause problems in some browsers (if not all). Javascript Strings cannot have literal line breaks. If you must separate the string across multiple lines, it is best practice to use concatenation. Your code:
$('#addNew').live('click', function() {
alert('ok');
alert(i);
$('<p>
<label for="trainer">Trainer: </label>
<td><select name="state_' + i +'"">
<option></option>
</select>
<select>
<option></option>
</select></td></tr></table>
Remove </p>').appendTo(addDiv);
Should be written as:
$('#addNew').live('click', function() {
alert('ok');
alert(i);
$('<p>' +
'<label for="trainer">Trainer: </label>' +
'<td><select name="state_' + i +'"">' +
'<option></option>' +
'</select>' +
'<select>' +
'<option></option>' +
'</select></td></tr></table>' +
'Remove </p>').appendTo(addDiv);
See How do I break a string across more than one line of code in JavaScript? for more information on this.
Note that I don't know if this will fix your problem but it is a place to start. Also, Always check the developer's console in your browser. It will give you hints on where your javascript is broken,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p>'+
'<table id="datatable"><tr><td width="200"></td><td>'+
'<select name="state_' + i +'" id="state">'+
'<option value="0">Select State</option>'+
'<option value="1">QLD</option>'+
'<option value="2">NSW</option>'+
'<option value="3">VIC</option>'+
'<option value="4">WA</option>'+
'<option value="5">ACT</option>'+
'<option value="6">NT</option>'+
'<option value="7">SA</option>'+
'<option value="8">TAS</option>'+
'</select><select name="trainer_' + i +'" id="trainer"><option></option></select>'+
'Remove</td></tr></table></p>').appendTo(addDiv)
i++;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
});
});
</script>

jQuery/PHP Select checkboxes from $_SESSION variable

I'm not sure if I'm doing this completely wrong, but I'm hoping what I'm trying to do is possible.
I have an existing ajax jquery function that saves the "selected" checkboxes from a user and stores them in $_SESSION['order_items'][index]['cheeseids'][]; When a user goes to recall this "item", I'd like to have the same checkboxes "selected" as before. See example below:
[order_items] => Array
(
[1] => Array
(
[cheeseids] => Array
(
[0] => 1
[1] => 2
[2] => 4
)
My "change/restore" jquery function uses the following variables to get the index number:
var productIDValSplitter = (this.id).split("_");
var productIDVal = productIDValSplitter[1];
The function I'm trying to use to "re-select" boxes 1, 2, 4 (from cheeseids array) is not working (it is inside my jQuery function). It actually causes the entire jQuery code to not work:
<?php
foreach($_SESSION['order_items'] as $key => $value)
{
?>
var idnum = <?php echo $value['<script type="text/javascript">productIDVal</script>']['cheeseids'] ?>;
$("div.cheesebox input[type=checkbox]").eq(" + idnum + ").attr("checked", "checked");
<?php
}
?>
JS Output:
var idnum = ;
$("div.cheesebox input[type=checkbox]").eq(" + idnum + ").attr("checked", "checked");
var idnum = ;
$("div.cheesebox input[type=checkbox]").eq(" + idnum + ").attr("checked", "checked");
Entire JS/jQuery function that I'm adding the PHP too:
$("#basketItemsWrap li img.change").live("click", function(event) {
var productIDValSplitter = (this.id).split("_");
var productIDVal = productIDValSplitter[1];
$("#notificationsLoader").show();
$.ajax({
type: "POST",
url: "includes/ajax/functions.php",
data: { productID: productIDVal, action: "deleteFromBasket"},
success: function(theResponse) {
$("div#order_qty input").attr('value', $("#order_" + productIDVal + " #order_qty").text());
$("div#order_listprice input#price1").attr('value', $("#order_" + productIDVal + " #order_listprice").text().replace("$", ""));
$("div#order_price input#discprice1").attr('value', $("#order_" + productIDVal + " #order_price").text().replace("$", ""));
$("div#order_price input#itemprice1").attr('value', $("#order_" + productIDVal + " #order_itemprice").text().replace("$", ""));
//The following functions restore the order details in the select menus, checkboxes, and radio buttons
//Restores the item selected
for(var i = 0; i < $("#item1 option").size(); i++)
{
if($("#order_" + productIDVal + " #order_item").text() == $("#item1 option:eq("+i+")").text())
{
$("#item1 option:eq("+i+")").attr("selected", "selected");
//$("#item1").val(i);
CalcPrice(1);
}
}
//Restores the promotion selected
for(var i = 0; i < $("#promo1 option").size(); i++)
{
if($("#order_" + productIDVal + " #order_promo").text() == $("#promo1 option:eq("+i+")").text())
{
$("#promo1 option:eq("+i+")").attr("selected", "selected");
//$("#promo1").val(i);
CalcPromo(1);
}
}
<?php foreach($_SESSION['order_items'][1]['cheeseids'] as $id): ?>
$("div.cheesebox input[type=checkbox]#<?php echo $id;?>").attr("checked", "checked");
<?php endforeach; ?>
//Restores the cheese options selected
// $('div.cheesebox input[type=checkbox]').size(); i++)
//$('div.cheesebox input[type=checkbox]').eq(1).attr('checked', 'checked');
$("#order_" + productIDVal).hide("slow", function() {$(this).remove();Calc();});
$("#notificationsLoader").hide();
}
});
});
PHP/HTML code to generate the checkboxes:
<?php
//Display all "cheese" options in a checkbox group
foreach($_SESSION['ingr_cheese'] as $key => $value)
{
echo "<div class=\"cheesebox\" style=\"float:left; width:175px; margin-bottom:7px;\">";
echo "<input type=\"checkbox\" name=\"cheese1\" id=\"cheese1\" class=\"cheeseCheck\" value=\"".$key."\"> <label for=\"cheese1\">".$value['cheese']."</label></br>";
echo "</div>";
}
?>
If the array you listed is already is an accurate representation of what's in the $_SESSION array, then this code should do what you're looking for.
<?php foreach($_SESSION['order_items'][1]['cheeseids'] as $id): ?>
$("div.cheesebox input[type=checkbox]#<?php echo $id;?>").attr("checked", "checked");
<?php endfor; ?>
This should generate javascript that looks like this:
$("div.cheesebox input[type=checkbox]#1").attr("checked", "checked");
$("div.cheesebox input[type=checkbox]#2").attr("checked", "checked");
$("div.cheesebox input[type=checkbox]#4").attr("checked", "checked");
This code assumes your markup for the checkboxes looks (somewhat) like this:
<div class=".cheesebox">
<input type="checkbox" id="1">
<input type="checkbox" id="2">
<input type="checkbox" id="3">
<input type="checkbox" id="4">
</div>
I verified the selector syntax, but if that doesn't work, then I probably made a bad assumption about the markup of your checkboxes. Paste in some more of your html if this isn't enough to point you in the right direction and I'll take another swing at it.

How to call/activate the 2nd select list only after 1st select list was selected?

I have the following select list:
SELECT LIST 1:
<select name="productcolor" id="productcolor" onChange="GetAvailProductSizes();">
<option value=""><? echo $langdata['oneprodpage_selectcolor']; ?>...</option>
<? foreach ($thisproduct['availcolors'] as $color) { ?>
<option value="<? echo $color['id']; ?>"><? echo $color['name']; ?></option>
<? }; ?>
</select>
SELECT LIST 2:
<select name="productsize" id="productsize" style="width: 120px;">
<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>
</select>
If in LIST 1 no options where selected, LIST 2 will be empty. It's like LIST 2 depends of LIST 1.
This is made with this function:
<script type="text/javascript"><!--
function GetAvailProductSizes() {
$('select#productsize option').remove();
$('select#productsize').append('<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>');
var color = $('#productcolor').val();
if (color > 0) {
var availsizes;
var http_request = new XMLHttpRequest();
http_request.open( "GET", '<? echo ROOT; ?>/autocompleteavailsizes/?productid=<? echo $thisproduct['id']; ?>&color=' + color, true );
http_request.send(null);
http_request.onreadystatechange = function () {
if ( http_request.readyState == 4 ) {
if ( http_request.status == 200 ) {
availsizes = eval( "(" + http_request.responseText + ")" );
for (var i = 0; i < availsizes.length; i++) {
$('select#productsize').append('<option value="' + availsizes[i].id + '">' + availsizes[i].name + '</option>');
};
} else {
alert( "There was a problem with the URL." );
}
http_request = null;
}
};
};
}
//-->
</script>
Now, I want the SELECT LIST 2 to be hidden until SELECT LIST 1 was not touched. Any help please with PHP or jQuery. Thank you!
Simply add display:none to the style attribute of the second list and use $('select#productsize').show(); inside your function to let it appear,

How to pass values of form input fields to a script using AJAX/jQuery?

My current code is like this.
index.php
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<select id="dropdown_id">
<option value="one.php">One</option>
<option value="two.php">Two</option>
</select>
<div id="workspace">workspace</div>
one.php
$arr = array ( "workspace" => "One" );
echo json_encode( $arr );
two.php
$arr = array( 'workspace' => "Two" );
echo json_encode( $arr );
JS
jQuery('#dropdown_id').live('change', function(event) {
jQuery.getJSON($(this).val(), function(snippets) {
for(var id in snippets) {
// updated to deal with any type of HTML
jQuery('#' + id).html(snippets[id]);
}
});
});
Above code is working perfectly. When I select One from dropdown then one.php is loaded in workspace DIV using JSON. When I select Two then two.php is loaded in workspace DIV.
What I want to do next:
Now I want to add another dropdown in index.php:
<select id="myinput" name="alpha">
<option value="a">a</option>
<option value="b">b</option>
<option value="a">c</option>
<option value="b">d</option>
</select>
When user select any option from first dropdown then that script(value) should be loaded with the value of second dropdown in workspace DIV.
For example:
When I select One from first dropdown then:
one.php
$arr = array ( "workspace" => $_GET['alpha'] ); // Should load 'a'
echo json_encode( $arr );
Now When I select b from second dropdown then:
one.php
$arr = array ( "workspace" => $_GET['alpha'] ); // Should load 'b'
echo json_encode( $arr );
I hope it can help you :
one.php
$arr = array ( 'workspace' => 'One');
if(isset($_GET['myinput_val']))
{
$arr['workspace'] = $_GET['myinput_val'];
}
echo json_encode( $arr );
JS
$('#myinput').live('change', function(event) {
$.getJSON("one.php", { myinput_val: $(this).val() } , function (snippets) {
for(var id in snippets) {
// updated to deal with any type of HTML
$('#' + id).html(snippets[id]);
}
});
});
How about something like:
$('#mypage').bind('change', function () {
var self = $(this);
$('#workspace').load('/' + self.val(), {
input: $('#myinput').val();
});
});
Then your PHP files will look at the $_POST['input'] value to output the value.
<?php echo $_POST['input']; ?>

Categories