Cascading Select Boxes - Jquery - php

Having a problem with dynamically populated select boxes using jQuery.
Basically, my code calls a php script which populates the select box (utilityMainChart). Let's say it brings back two options for the the select box utilityMainChart, I want the next select box (parameterMainChart) to be populated with the options for whichever option is first in the utilityMainChart select box.
As it is right now, the select boxes get populate properly initially, but the line var building = $('#utilityMainChart').val(); never returns the value of the select box. This means that any change to a select box result in the ones below it becoming blank, since no value is picked up.
My code for the javascript is shown below:
var data = "1" + "_" + building + "_";
var url = "/charts/data/utilityManagerMenuPopulate.php?data=" + data;
$('#utilityMainChart').load(url);
var building = $('#utilityMainChart').val();
var data = "2" + "_" + building + "_" + utility;
var url = "/charts/data/utilityManagerMenuPopulate.php?data=" + data;
$('#parameterMainChart').load(url);
My php code returns data in the form:
<select id="utilityMainChart" name="utilityMainChart">
<option selected value=1>Electricity</option>
<option value=3>Water</option>
</select>
Any advice would be awesome. I've been playing around with this for hours and just can't get it to work

Try changing
var building = $('#utilityMainChart').val();
to
var building = $('#utilityMainChart :selected').val();
EDIT: Your #utilityMainChart is not a unique id it is on both the select and the selects containing div. So you when you run the above code it gets the div. If you try this will it help.
var building = $('select#utilityMainChart').val();

Related

Live filter in Laravel

I have a form that looks like below.
I have three "white" dropdowns to filter the value for the Equipment Registration Tag dropdown ( The values of the dropdown input field that has the Equipment Registration Tag label will only come out after the user selects values for the three "white" dropdowns). So the Equipment Registration Tag values will differ based on the "white" dropdowns value.
I want it to be a live filter, the dropdown options will change immediately every time user selects the "white" dropdown value. Currently, my approach is to use the onchange=" this.form.submit()" attribute on the "white" dropdowns and return the values after the filter, but I realize this method has a disadvantage which is a user might accidentally submit the form when changing the value of "white" dropdowns. How can I prevent this and only allow users to submit the form by clicking the save button?
$this->Calibration_Location = $request->get('selected_location');
$this->Calibration_Category = $request->get('selected_category');
$this->categories = Equipment::select('Category')->distinct()->get()->toArray();
$this->locations = Equipment::select('Location')->distinct()->get()->toArray();
$matchThese = ['Category' => $this->Calibration_Category, 'Location' => $this->Calibration_Location];
$this->Registration_Select_Tags = Equipment::select('Registration Tag')->distinct()->where($matchThese)->get();
I have also tried jQuery, but I can only trigger by a specified dropdown field, not any one of them.
<script type="text/javascript">
$(document).ready(function() {
var location, category
$('#selected_transfer_location').change(function() {
location = $(this).val();
console.log(location);
$('#selected_transfer_category').change(function() {
category = $(this).val();
console.log(category);
});
// $('#transfer_registration_tag').find('option').not(':first').remove();
$.ajax({
url: 'Transaction/' + location + '/' + category,
type: 'get',
dataType: 'json',
success: function(response) {
var len = 0;
if (response.data != null) {
len = response.data.length;
}
if (len > 0) {
for (var i = 0; i < len; i++) {
var id = response.data[i]['Registration Tag'];
var name = response.data[i]['Registration Tag'];
var option = "<option value='" + id + "'>" + name +
"</option>";
$("#transfer_registration_tag").append(option);
}
}
}
})
});
});
</script>
I hope my question is clear, still new to Laravel and I hope could receive some hints from you.
First approach could be that, you use call ajax Query on change of each on of them and fetch filtered results. Something like this:
$('#dropdown1, #dropdown2, #dropdown3').change(function(){
var val1 = $('#dropdown1').val();
var val2 = $('#dropdown2').val();
var val3 = $('#dropdown3').val();
//And then your ajax call here to fetch filtered results.
});
Only issue is this Ajax call will occur min 3 times, one for each of them.
Second approach could be you give small button below those dropdowns, something like FetchTags. When user selects all the 3 values, will click on that button and you call your ajax onClick of that btn. So that your Ajax will be called only once.
You can use livewire to do that. It easy.
To install it, you have to use composer by taping the fowllowing command:
composer req livewire/livewire
Please check this tutorial to see how to how to do what you want to do using the framework.

If first drop down changes to auto change of second drop down using php

I have two drop downs, one is repositories list where lists not get from database
another one drop down is their branchs
if I select "a" repo option another drop down should show their branches and user change his mind select "b" option second drop down should show their branches
how can done this using php without using database ?
If I understand your question properly, you want to create something like this:
I assume that you are aware of all consequences from not using DB for this, so I skip this part.
You will have to use some Javascript, and to make it easier - jQuery, that makes two things:
Shows the second dropdown after user selects an option from the first one,
Updates options in 2nd dropdown when value of the 1st dropdown changes.
So here's your HTML:
<select id='dropdown1' name='branch'>
<option value='it'>IT</option>
<option value='entertainment'>Entertainment</option>
</select>
<select id='dropdown2' name='branch-sub' style='display:none;'></select>
And here's your jQuery / javascript:
var options = {
'it': ["Programming", "Software", "Hardware", "..."],
'entertainment': ["PC Games", "Movies", "Music", "..."]
// And so on
}
$(document).ready(function(){
$('#dropdown1').change(function(){
$('#dropdown2').show();
$('#dropdown2').html('');
var opts = options[$('#dropdown1').val()];
for(var a = 0; a < opts.length; a++)
$('#dropdown2').append("<option value='" + opts[a] + "'>" + opts[a] + "</option>");
});
});
Edit (15-03-2018): I updated the JS code, so it's working now.

Need to access <input> data from a <form>, that has been appended with Javascript

I have an admin page where I add and delete table rows on the fly.
The page comes loaded with the existent data in the database (mostly consisting in a sku_code and 5 different prices) but when I add rows on the fly, and fill them with the corresponding skus and prices, I want to save them as well in the database.
The problem is that what I do on the client-side with Javascript (add table rows on the fly) with innerHTML = '<input type="text"> is not accesible via $_POST variables of the main <form>
So basically i add via Javascript 's so i can fill them and save them as well in the database. But the $_POST values are empty.
Javascript code works fine. I have no clue where should i start debugging.
here's some Javascript code i'm using
function insert_record(){
var my_table = document.getElementById('my_table')
var tr = my_table.insertRow(my_table.rows.length-1)
//id-ul curent, numar toate row-urile - 1 (care este butonul OK)
var c_id = my_table.rows.length-2
tr.id = 'row_' + c_id + ''
var tr_td_1 = tr.insertCell(0)
tr_td_1.className = 'text2'
tr_td_1.align = 'center'
tr_td_1.innerHTML = 'SKU'
var tr_td_2 = tr.insertCell(1)
tr_td_2.className = 'text3'
tr_td_2.width = '63'
tr_td_2.innerHTML = '<input name="sku_' + c_id + '" type="text" id="sku_' + c_id + '" size="33" value="">'
....this addes a inside the table just before the last which contains the submit button, after which there's the
You need to assign a label to element. Then you can grab it in next page.
Instead of innerHTML = <input type="text"> try to use
<script>
function addElement(tag_type, target, parameters) {
//Create element
var newElement = document.createElement(tag_type);
//Add parameters
if (typeof parameters != 'undefined') {
for (parameter_name in parameters) {
newElement.setAttribute(parameter_name, parameters[parameter_name]);
}
}
//Append element to target
document.getElementById(target).appendChild(newElement);
}
</script>
You can call this function below either click of even or manually addElement('INPUT','targetTag',{id:'my_input_tag', name:'my_input_tag', type:'text', size:'5'});
you should give the name attribute. if you are worried about the unlimited numbers of fields just go for the array of the input variables,
like this
<input type="text" name="field1[]">
Now you can access them in post like this:
$_POST['field1'] //this is an array of fields
EDIT:
First thing is that you should use some library like jquery which eases the work.
I suggest you make sure your all your fields are inside the form and that you have named all of them instead of trying ajax or functions like #shail suggested.
In my opinion they are not solving the problem, just avoiding it.

Get values from multiple select boxes with same name? Including its value with jquery and php

I have looked for answers on here and have not found anything that directly can help me so I am going to ask here. I have a form with multiple select boxes:
<select name="acabados[]">
<option value="1">ABC</option>
<option value="2">DEF</option>
<option value="3">GHI</option>
</select>
<select name="acabados[]">
<option value="1">ABC</option>
<option value="2">DEF</option>
<option value="3">GHI</option>
</select>
As you can see they are the exact same select box. I have told the client to use select multiple but he wants it this way. The user can add as many as these select boxes as they desire (so it could be up to 20 select boxes at a time) and I need to get the value (1 or 2 or 3) and the text inside the option. It is then an array that I need to break down cause I need to add the total values of the select boxes in php. I could either use jquery for collecting the values or php, which ever is easier. Thank you in advance for any help!!
Try this, it will work for dynamically created select elements too.
$(document).on('change', 'select[name="acabados[]"]', function(){
var total = 0;
$('select[name="acabados[]"]').each(function(){
total += parseInt($(this).val());
});
});
total var will contain the total of all the select elements selected value.
If you want to retrieve the values in PHP, you can just use $_POST['acabados'] and it will contain all the values selected in each menu. See a demo. As long as you include the [] after the name, it will compound all the values for any element with that name into a single array. You can even mix select menus, inputs, and textareas together!
$(function () {
var $select = $('select');
$select.on('change', function () {
var output = 0;
for (var i = 0, len = $select.length; i < len; i++) {
output += parseInt($select.eq(i).val());
}
//the `output` variable now contains the addition of all the values from the `acabados[]` select elements
});
});
Here is a demo: http://jsfiddle.net/aPXXA/1/
You can change var $select = $('select'); to var $select = $('[name="acabados[]"]'); to only select the select elements with the acabados[] name attribute.
Why not just give them different id's and do the count in jquery/javascript. Alternatively give them all the same class, and do .each() to grab the values in all of them.

how to implement a dynamic combo box selection system

I'm implementing a system these days, i want to implement a combo box selection process but i don't know how to implement it, so asking you guys favor?
my scenario is this, let's say we have two combo box selection lists, left one and right one, left one is the main one and the right one is the child of the left one.
when i select a item from the left combo box the right combo box's content should be changed according to the selection of the left one,
Ex: let's think about mobile phones, if i select the brand
Nokia
from the left combo box right combo box's content should be changed to
C6-01
E7-00
5232
X3-02
C1-01
C7-00
5228
C5-03
5250
6120ci
E5-00
E73
like wise. please help me to implement a this kind of scenario!
any tutorial links, sample codes to understand the scenario is better!
regards,
Rangana
The trick is do subscribe to the change event and reset the contents of the second box accordingly.
HTML:
<select id="brand">
<option value="">- select -</option>
<option value="nokia">Nokia</option>
<option value="apple">Apple</option>
</select>
<select id="type"></select>
JavaScript (on ready):
var selectBrand = $("#brand");
var selectType = $("#type");
var optionsList = {
nokia: [
"C6-01",
"E7-00"
],
apple: [
"iPhone 3",
"iPhone 3G",
"iPhone 4"
]
};
selectBrand.change(function() {
var brand = selectBrand.val();
var options = optionsList[brand];
var html;
if (options) {
html = '<option value="">- select -</option>';
$.each(options, function(index, value) {
html += '<option value="' + value + '">' + value + '</option>';
});
} else {
html = '<option value="">Select a brand</option>';
}
selectType.html(html);
}).change();
Full example at See http://www.jsfiddle.net/TJJ8f/
This works by having two things. Firstly, a server that will return JSON for the category you need and, secondly, the code for the front end.
<?php
// Do what you need to
$modelsArray = getModelsForBrand($_REQUEST['brand']);
echo json_encode($modelsArray);
?>
This uses the json_encode function to get the JSON on the array returned by whatever you use to get the models. I haven't used this function myself but it looks pretty simple.
Then your jQuery would look like this:
$("#brandCombo").change(function(){
var chosenBrand = $(this).val(); // Get the value
$.getJSON('/your-php-file.php', { "brand" : chosenBrand }, function(request){
// Successful return from your PHP file
$("#modelCombo").empty();
// For each item returned, add it to your models combo box
$.each(request, function(i,item){
$("#modelCombo").append("<option value='" + item.value + "'>"+ item.name + "</option>");
});
});
});
In this example, brandCombo is the ID of the list with the brands and modelCombo is the ID of the list the models should appear. When the value of brandCombo is changed, it makes the request to your PHP file to get the array of models in JSON. Then it goes through each one and adds a new option to your modelCombo list.
A similar question I answered is here, where I mentioned how to do it with all the data already on the page and in listboxes (hiding/showing them) or by AJAX requests (as the example above).
The other option, as shown in dyve's answer is to have all the information you need on the page already, in the form of a JavaScript object. If you wanted to do this, then then PHP json_encode function could still be of use (although you just call it once with all your data and plop it onto the page).
A number of previous SO posts cover this topic, have a look at this for example: Using javascript and jquery, to populate related select boxes with array structure

Categories