I have a table about products. It has id, productdmc, productcode columns.
In this select menu, productdmc is showing.
When one item was selected, label its gonna change with related rows. Thats what i need. But i cant figure out the solution.
productcode.
<select class="form-control" name="productdmc" id="productdmc">
<option disabled selected>DMC</option>
#foreach ($product as $products)
<option value="{{ $products->productdmc }}">{{ $products->productdmc }}</option>
#endforeach
</select>
Related input
<input type="text" name="productcode" id="productcode">
This is the js code. I dont know this is working. This is my actual problem.
<script type="text/javascript">
$(document).ready(function() {
$('select[name="productdmc"]').on('change', function() {
var tmp = $(this).val();
if(tmp) {
$.ajax({
url: '/products/create/'+tmp,
type: "GET",
dataType: "json",
success:function(data) {
$('productcode').empty();
$.each(data, function(key, value) {
$('productcode').innerHTML('<input value="'+ key +'">');
});
}
});
}else{
$('productcode').empty();
}
});
});
</script>
In my Controller:
$val = DB::table("products")->pluck("productdmc","productcode");
return json_encode($val);
I know, i messed up so much. But codes are so complicated than this. I write this code in here(shorter version). Not copy-paste. I stucked here in a while. I cant find what is the real solution is.
I am open for all kinda solution.
Sorry for my bad english.
innerHTML is a property of HTML elements, not a function of jQuery's representation.
Use html(content) instead, and I think it should work:
$('#productcode').html('<input value="'+ key +'">');
Your selector is wrong, you forgot the '#'.
var $productCode = $('#productcode');
Also, when the event 'change' is triggered, you need to fetch the selected option.
var selectedValue = $element.find('option:selected').val();
HTML
<select class="form-control" name="productdmc" id="productdmc">
<option disabled selected>DMC</option>
#foreach ($product as $products)
<option value="{{ $products->productdmc }}">{{ $products->productdmc }}</option>
#endforeach
</select>
<input type="text" name="productcode" id="productcode">
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$('body').on('change', 'select[name="productdmc"]', function(e) {
var $element = $(e.currentTarget); // $(this) is also fine.
// Get selected value
var selectedValue = $element.find('option:selected').val();
var $productCode = $('#productcode');
// No value selected
if (!selectedValue) {
$productCode.val('');
return;
}
$.ajax({
url: '/products/create/' + selectedValue,
type: 'GET',
dataType: 'json',
error: function() {
$productCode.val('');
},
success: function(res) {
$productCode.val('');
if (res.length < 1) return;
$productCode.val(res[0] || '');
// This will populate more than 1 field. So,
// I'm not sure about what you expect on the backend.
// If you want to populate more than 1,
// you should change the selector/field (do not use id in this case)
// $.each(res, function(key, value) {
// $productCode.val(key);
// });
}
})
});
});
</script>
PHP
<?php
$products = DB::table('products')->get();
return response(
$products->pluck('productdmc', 'productcode')->toArray()
);
You can read more about jQuery selectors here: https://api.jquery.com/category/selectors/
Related
I have dynamic add rows. Every row contains 2 dropdowns (select). They are for type and category selections. The category depends on the type.
The problem is when I change a select option, it also affects other rows, which is not my intention.
For example, when there are 3 rows. How can I improve this function so it only affects specific select options?
Here is my HTML code
<table id="dynamic_field">
<tr>
<td>
<label>Vehicle Type:</label>
<select name="vehicle_type[]" class="" id="" onchange="get_category(this.value)">
<option value="">Type</option>
<option value="Car">Car</option>
<option value="Bus">Bus</option>
</select>
</td>
<td>
<label>Vehicle Category</label>
<select name="vehicle_category[]" class="category" id="category" onchange="get_sub_category(this.value)" >
<option value="">Category</option>
</select>
</td>
<td>
<label>Vehicle Sub Category</label>
<select name="vehicle_sub_category" class="form-control subcategory">
<option value="">Sub Category</option>
</select>
</td>
</tr>
<tr>
<!--- etc. --->
</tr>
</table>
Here is my jquery code
function get_category(key){
$.ajax({
url: 'getCat',
type: "get",
data: {type:key},
success: function(data){ // What to do if we succeed
$('.category').empty();
$('.subcategory').empty();
$.each(data, function (i, d) {
$('.category').append($('<option>', {
value: d.id,
text : d.V_Category
}));
});
}
});
}
Remove the onchange HTML attributes:
onchange="get_category(this.value)"
Instead bind the event handling via code, and find the corrsponding category/subcategory. As your related select elements are in neighboring td elements, you need to first get the row where the current select is in, and then find the other, category element:
$("[name*=vehicle_type]").change(function () {
var $type = $(this); // get the current select element
var $row = $type.closest("tr"); // find the row that has the related select elements
var $cat = $("[name*=vehicle_category]", $row); // .. the category-select
var $subcat = $("[name*=vehicle_sub_category]", $row); // .. the subcategory-select
$.ajax({
url: 'getCat',
type: "get",
data: { type: $type.val() },
success: function(data) {
$cat.empty();
$subcat.empty();
$.each(data, function (i, d) {
$cat.append($('<option>', {
value: d.id,
text : d.V_Category
}));
});
}
});
});
I think you have to poit to te next element in the DOM, ot it will change all the DOM elements with class category. So you can use next jQuery method.
Description: Get the immediately following sibling of each element in
the set of matched elements. If a selector is provided, it retrieves
the next sibling only if it matches that selector.
Try change your code in:
function get_category(key){
$.ajax({
url: 'getCat',
type: "get",
data: {type:key},
success: function(data){ // What to do if we succeed
$(this).next('.category').empty();
$(this).next('.subcategory').empty();
$.each(data, function (i, d) {
$(this).next('.category').append($('<option>', {
value: d.id,
text : d.V_Category
}));
});
}
});
}
I'm fetching some data using ajax from my database, the problem is when I append an option to a select with a value containing these data, the append ends the first word with " thus the rest is left outside the value tag.
Here's the empty select:
<select name="Sender" id="SenderNames" class="form-control" style="width: 100%;"></select>
This is the jQuery code:
$('#SenderSelect').on('change', function() {
$.ajax({
type: "POST",
url: 'operations/inner-operations/getNamesByService.php',
data: { action :"getService", "serviceName" : $("#SenderSelect option:selected").val() },
success: function(data) {
var responseObj = jQuery.parseJSON(data);
console.log(responseObj);
$.each(responseObj, function(i, value) {
$("#SenderNames").append('<option value='+value+'>'+value+'</option>');
});
}
});
});
The appended option should look like this:
<option value="First Second">First Second</option>
However, it is appended like this:
<option value="First" second="">First Second</option>
I just realised that I'm not closing the string properly. The append should be like this:
$("#SenderNames").append('<option value="'+value+'">'+value+'</option>');
the value tag must be wrapped by "".
I have a previous question like this but it only applies to 2 select boxes so here I'm asking again if someone can help me with 3 select boxes. I have trouble displaying the price of an item based on the selection of a select box. I have 2 tables namely items and item_details. items table has columns item_id and item_name only. item_details table has columns item_details_id, item_id(fk from items table) item_size and price.
I can display the corresponding items_details on the second select box of the item based on the first select box.
HTML
<td>
<select name="item" class="form-control select2" id ="item">
<option value="0" selected="true" disabled="true">Select Item</option>
#foreach($items as $key => $i)
<option value="{!!$key!!}">{!!$i!!}</option>
#endforeach
</select>
</td>
<td>
<select name="item_details" class="form-control" id="item_details" >
</select>
</td>
<td>
<select name="price" class="form-control" id="price" >
</select>
</td>
ItemController
public function findItemDetails($id)
{
$details = DB::table("item_details")
->where("item_id",$id)
->lists("item_size","id");
return json_encode($details);
}
JS
$('select[name="item"]').on('change', function() {
var itemID = $(this).val();
if(itemID) {
$.ajax({
url: '/findItemDetails/ajax/'+itemID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="item_details"]').empty();
$.each(data, function(key, value) {
$('select[name="item_details"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error:function(){
}
});
}else{
$('select[name="item_details"]').empty();
}
});
Routes
Route::get('findItemDetails/ajax/{id}',array('as'=>'findItemDetails',
'uses'=>'ItemController#findItemDetails'));
I provided all the information needed to make 2 select boxes function but when i tried to search for topics about dynamic boxes that involves 3 select boxes i couldn't find any. I'm new to javascript and laravel, so i tried to duplicate my first code and changed the variables if by any chance i could display the price on the 3rd box but nothing works. Heres what i have.
ItemController
public function findPrice($id)
{
$itemdetails = DB::table("itemdetails")
->lists("price","id");
return json_encode($itemdetails);
}
JS
$('select[name="item_details"]').on('change', function() {
var itemdetailsID = $(this).val();
if(itemdetailsID) {
$.ajax({
url: '/findPrice/ajax/'+itemdetailsID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="price"]').empty();
$.each(data, function(key, value) {
$('select[name="price"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error:function(){
}
});
}else{
$('select[name="price"]').empty();
}
});
Routes
Route::get('findPrice/ajax/{id}',array('as'=>'findPrice',
'uses'=>'ItemController#findPrice'));
I want to create an autofill search box. it gets a JSON and sends them to an HTML5 <datalist> of <option>s.
It works fine but it cant use spaces in values! so it just returns the first word. for example, if the jresults.name is "lets go" - I get only "lets".
What is the best way doing this?
This part: $( "#prod_name_list" ).children().remove(); prevents me of choosing an option from the list. because it deletes everything in it when I "keyup" so I need a different solution for this.
The second part is after submitting the form I want to get the id chosen of the object. (jresults.id) and I'm not sure how to retrieve it with the submit.
MY CODE:
JS part:
$("#prod_name").bind("keyup", function(e) {
if (e.which <= 90 && e.which >= 48){
$( "#prod_name_list" ).children().remove();
var prod_name = $("#prod_name").val();
$.ajax({
method: "POST",
url: "<?php echo site_url('kas/search_prod_name'); ?>",
data: ({ "prod_name": prod_name }),
success: function (result){
var jresults = JSON.parse(result);
console.log("jresults: "+jresults);
var lng = jresults.length;
console.log("lng: "+lng);
for (var i=0; i<lng; i++) {
if (jresults.hasOwnProperty(i)) {
console.log("name: "+jresults[i].name);
$("#prod_name_list").append("<option name=\"prod_id\" id="+jresults[i].id+">"+jresults[i].name+"</option>");
}
}
}
});
}
});
HTML part(using codeigniter syntaxes for the form:
<?php
$attributes = array('class' => 'prod_name', 'id' => 'prod_name', 'name' => 'prod_name', 'list' => 'prod_name_list');
echo form_input('prod_name', 'prod Name', $attributes);
?>
<datalist id="prod_name_list">
</datalist>
A few things to work on here, but let's jump into a working example: https://jsfiddle.net/Twisty/a2z7e1yb/
The HTML I tested with:
Name: <input class="prod_name" id="prod_name" name="prod_name" list="prod_name_list" />
<datalist id="prod_name_list">
</datalist>
The JQuery I would advise using:
$(document).ready(function() {
$("#prod_name").keyup(function() {
$.ajax({
method: "POST",
url: "<?php echo site_url('kas/search_prod_name'); ?>",
data: {
"prod_name": $("#prod_name").val();
},
success: function(result) {
console.log(result);
var options = "";
$.each(result, function(k, v) {
console.log("name: " + v.name);
options += "<option value='" v.name + "'>\r\n";
});
console.log(options);
$("#prod_name_list").html(options);
}
});
});
});
As was mentioned, you can use onKeyPress versus onKeyUp. I leave that up to you.
I did testing with test data that looked like:
[
{
"name": "Lets Go"
}, {
"name": "Go More"
}
]
The $.each() works well for this. It will iterate over each array item and place it's Key into k and each object into v. We then generate a string of all the options and replace whatever is inside our datalist So if the result set is 15 options on the first character, it would be replaced ion the next keystroke with whatever result set we get.
Using .remove() and .append(), in my mind, becomes cumbersome for this type of application. You want to remove all the options, or replace them, with whatever new data you receive. In my working example, when a key is pressed, we see:
<datalist id="prod_name_list">
<option value="0">Lets Go</option>
<option value="1">Go More</option>
</datalist>
I hope this is clear and helps you out. If it's not, leave a comment and let me know.
Update
I think you may be using the <datalist> tag incorrectly. It should be fully populated when the page loads, not after text is entered. See more here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist
It should be used like so: https://jsfiddle.net/Twisty/a2z7e1yb/2/
<label>Name:
<input class="prod_name" id="prod_name" name="prod_name" list="prod_name_list" /></label>
<datalist id="prod_name_list">
<option value="Let's Go" />
<option value="No Go" />
<option value="Go Back to Bed" />
</datalist>
If you really want to make it like JQuery UI's Autocomplete, you would build a <ul> or <div> with the results as a list inside. This list would be populated when a key is pressed, showing just the relevant results. For example if "L" was pressed it would sen that value to your PHP which would show "Let's Go" and any other product Names that begin with "L". It's different than <datalist> which looks for anything in your List that contains "L".
I have a url like this:
index.php/home/lista_modelo_ajax?id="+$('#colecoes').val(),
The thing is that the: $('#colecoes').val() is always the first item of the select, not the one I choose.
Any ideas?
Thanks in advance.
EDIT
<script>
$(function() {
$( "#modelos" ).autocomplete({
source: "<?php echo base_url();?>index.php/home/lista_modelo_ajax?id="+$('#colecoes').val(),
minLength: 2
});
});
</script>
<label for="colecoes">Coleções</label>
<select name="colecoes" id="colecoes">
<option value="16">-</option>
<?php foreach($lista_colecao as $colecao){?>
<option value="<?php echo $colecao->idColecao;?>"><?php echo $colecao->nomeColecao;?></option>
<?php }?>
</select>
<label for="modelos">Modelo</label>
<input type="text" name="modelos" id="modelos" />
All php is working fine, generating the IDs on the value of options objects, the problem is only with JS
This will depend on where you are writing this code. If you are writing it directly in the document ready that would be normal as at the moment this code executes that's the selected value. On the other hand if you are writing it for example in the .change event of the dropdown list you will get the actual value:
$('#colecoes').change(function() {
var id = $(this).val(); // now you will get the actual selected value
$.ajax({
url: 'index.php/home/lista_modelo_ajax',
data: { id: id },
success: function(result) {
...
}
});
});
Just do:
$('#colecoes').val(); //assuming `colecoes` is the id of the select
Example with onchange:
$('#colecoes').change(function(){
alert(this.value); //alerts the selected option
});