repopulate child dropdow when parent dropdown changed - php

TL;DR
How to make jQuery request from parent dropdown ( using .change() ) to working url that outputs JSON and repopulate child dropdown.
END TL;DR
I'm using Laravel 5.1 so my code will be a bit Laravel specific but not much since this is beginner level jQuery problem.
I have two dropdowns. One is for categories (parent) and other is for subcategories (child).
My parent dropdown:
<div class="form-group">
{!! Form::label('category_id', '*Categories') !!}
{!! Form::select('category_id', $categories, null) !!}
</div>
which generates
<div>
<label for="category_id">Categories</label>
<select id="category_id" name="category_id">
<option value="1">Category 1</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
</div>
My child dropdown:
<div sytle="display:none;">
{!! Form::label('subcategory_id', 'Subcategory') !!}
{!! Form::select('subcategory_id', [], null) !!}
</div>
which generates
<div sytle="display:none;">
<label for="subcategory_id">Subcategories</label>
<select id="subcategory_id" name="subcategory_id">
</select>
</div>
I have defined route: subcategoriesfordropdown/{i} to which I send i and it gives me JSON with the children of parent category. For example if I use URL subcategoriesfordropdown/2 I get:
{"3":"Subcategory 1 title","4":"Subcategory 2 title"}
Numbers in "" are subcategories IDs. This is all working properly.
Now I want to repopulate child dropdown with these id/title pairs so that I get:
<div sytle="display:none;">
<label for="subcategory_id">Subcategories</label>
<select id="subcategory_id" name="subcategory_id">
<option value="3">Subcategory 1 title</option>
<option value="4">Subcategory 2 title</option>
</select>
</div>
I made this jQuery script:
<script>
$(document).ready(function(){
$("#category_id").change(function (){
var category = $(this).val();
alert( "Category: " + category );
});
});
</script>
And it pops an alert box with category ID as I change the parent dropdown values. However, instead of alert function I want it to run POST request (I believe POST is the right one here but GET is OK too) to get the JSON data and create options values from it. Also change the display:none; but that shouldn't be a problem.
I tried replacing alert(); with:
$.post( "/subcategoriesfordropdown/" + category, , function( data ){
alert( "Data: " + data );
});
to receive the data given by subcategoriesfordropdown/{i} but I'm failing here.
So here is my TODO list:
run POST request
get JSON data
populate child dropdown with JSON data
remove display:none; attribute
I hope I ain't missing something elese here. Thank you all in advance!

You're definitely on the right tracks.
The only issue I see with your $.post is the extra , after category. I'd also suggest using the "json" tag - it just prevents you have to use json_decode within the function.
To update the select box you can use Javascript along these lines.
(Untested, but theoretically correct barring typos)
$.post( "/subcategoriesfordropdown/" + category, function( data ){
var $select = $('#subcategory_id');
$select.empty();
$.each(data, function(value, text){
$select.append($("<option></option>")
.attr("value", value).text(text));
});
$select.show();
}, "json");

Related

Dynamically Set Value in seletpiker using jquery and Ajax

I am getting City List From Database and I Want to Show the Selected City Selected While Edit Operation.
I am Using Ajax for Getting a value from Database.
That's Work Nicely. I get the Response Data From My Controller.
Now The Problem is I am not Able to set a value on selectpiker.
I get City Name In Ajax Response.
I have tried Some Example but did not work.
Here is the Ajax Code.
$.ajax({
type: "GET",
url: urlForGetCityList,
dataType: 'Json',
success: function(response){
console.log(response.cityName);
// This is What i Tried For getting SeletBox Selected.
var $select = $('#city');
$select.val(response.city).trigger('change');
// I have also Tried Some Selct2 Option for it. But it didn't work.
$("#city").select2("val", response.city);
// And at Last I have tried for like simple select box.
$("#city").val(response.city);
});
None of this work properly.
Here is the HTML Code of Selectpiker.
<div class="col-md-4">
<div class="form-group">
<label for="field-3" class="control-label">City *</label>
<select class="selectpicker" data-live-search="true" data-style="btn-white" name="city" id="city"
title="Select City">
<option value="city1">City 1</option>
<option value="city2">City 2</option>
</select>
</div>
</div>
You Already Reach to the half you're a problem is just this select piker is not showing the selected value because it's that way you should check this.
So Try This.
$('select[name=city]').val(response.city);
$('.selectpicker').selectpicker('refresh');

PHP - Retrieving $_GET variable after submitting form and change URL

I have the following form I want to use to filter through products on my website:
<div class="top-filter-select-container">
<form method="GET" action="" id="sort-filter-pick">
<select class="selectpicker" id="sort-filter">
<option value="popularity">Sort by Popularity</option>
<option value="ratings">Sort by Ratings</option>
<option value="newest">Sort by Newest</option>
<option value="lowest">Sort by Lowest Price</option>
</select>
</form>
</div>
I am trying to reload my page when an option is selected using jQuery form.submit() and retrieve the selected option to be used for filtering with a SQL query. I would eventually want to use this value along with other filtering values for a more complex filtering.
$(function(){
$('#sort-filter').on('change', function() {
var action = $(this).val();
$("#sort-filter-pick").attr("action", "?sort=" + action);
this.form.submit();
});
});
To test my code, I am just trying to echo isset($_GET['sort']) ? $_GET['sort'] : null;
The code works if I change form method to POST instead of GET but doesn't work with GET. On websites such as Amazon, the GET form method is used when applying filters from a select option but I also notice that the ?sort=... is added to the page URL after the form is submitted, which is not the case for me if I use GET. I was wondering what would be the right approach to do the same thing.
If you add a "name" to your form-elements you don't need to manually add the sort-criteria with jQuery.
HTML:
<div class="top-filter-select-container">
<form method="GET" action="" id="sort-filter-pick">
<select class="selectpicker" name="sort" id="sort-filter">
<option value="popularity">Sort by Popularity</option>
<option value="ratings">Sort by Ratings</option>
<option value="newest">Sort by Newest</option>
<option value="lowest">Sort by Lowest Price</option>
</select>
</form>
</div>
Javascript:
$(function(){
$('#sort-filter').on('change', function() {
this.form.submit();
});
});
Or you could just use location.href = url rather than posting the form.

dropdown show right value

ve two values in my combo box. Car and bicycle when the user selects one of them it will be stored in the database with 1 or 2. But how do I make sure that when the user edits it the chosen values shows up.
For example I've saved bicycle in the database than when the user wants to edit it it must show bicycle and not car!
I'm working with laravel.
EDIT
<div class="form-group">
<label for="content" class="col-lg-2 control-label">Standaard route</label>
<div class="col-lg-10">
#if($standaardroute->isEmpty())
<label>U heeft nog geen standaardroutes. Maak deze hier aan.</label>
#else
<select class="form-control input-sm" name="standaardroute" id="standaardroute">
#foreach($standaardroute as $route)
<option value="{!! $route->id !!}">{!! $route->van !!} - {!! $route->naar !!}</option>
#endforeach
</select>
</div>
</div>
#endif
EDIT
I've 2 dropdown menus. When one dropdown is selected the other one should receive a number from the database and show the right value for example bicycle. When the first dropdown menu is selected it post a request and receives the values back. When I receive information back for a text box I say:
$("#van").val(result.van);
But how do I have to do this with a dropdown menu?
<script>
$(document).ready(function () {
var xhr;
});
$("#standaardroute").change(function(e) {
csrf = $("#token").attr('content')
option = $(this).val();
$.ajax({
url: '/public/receiveuserinformation',
type: 'POST',
data: { option_id: option },
beforeSend: function(xhr){xhr.setRequestHeader('X-CSRF-TOKEN', csrf);},
success: function(result) {
$("#van").val(result.van);
//here should be something for the dropdownmenu
}
});
});
</script>
Suppose you've two options in an array: $types = array('1' => 'car', '2' => 'bicycle'); and you're saving it in products table and you've current product data in $product variable
<select>
<?php foreach($types as $type_id => type_name): ?>
<option value="<?php echo $type_id; ?>" <?php if($type_id == $product->type) echo "selected"; ?>>
<?php echo $type_name; ?>
</option>
<?php endforeach; ?>
</select>
EDIT: if you're using blade in laravel then you could simply achieve it by doing this:
{!! Form::label('type', 'Type: ') !!}
{!! Form::select('type', $types !!}
EDIT2: Try this:
<option value="{!! $route->id !!}" {{ ($standaardroute->route == $route->id) ? 'selected':'' }}>{!! $route->van !!} - {!! $route->naar !!}</option>
Note: replace $standaardroute->route your actual variable
EDIT3: Put this inside your success function:
$('#van option').each(function(){
$(this).removeAttr('selected');
if($(this).val() == result.van){
$(this).attr('selected', 'selected');
}
});
Note: I've not tested this

How to create a text box after selecting an option from drop-down list?

I'm trying to create a drop-down list with four options such that if I select the 4th option, I want a text box created so that I can get the value typed in that box using "$_GET"
Something like this;
<select name="value">
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
<option value="value3">Option 3</option>
<!-- And a 4th one -->
</select>
And if the 4th one is selected, a box should appear like this;
<input type="text" name="firstname">
Edit;
My current code;
<script>
jQuery(function($){ //calling the code inside braces when document loads and passing jQuery object as '$' parameter;
$("select[name='sortby']").change(function(){ //binding an event that fires every time select value changes
var select = $(this); //caching select, which value was changed
if(select.val() === "byDefindex"){ //checking if we selected the right option
$("<input>").attr({type: "text", name: "defindex"}).appendTo(select.parent()); //creating new input element object, setting its value to "value4" and appending to select parent element or wherever you want it
}
});
});
</script>
<form action="<?php $_PHP_SELF ?>" method="GET">
Select:
<br />
<select name="sortby">
<option value="playHours">Play Hours</option>
<option value="lastLogin">Last Login</option>
<option value="byDefindex">By Defindex</option>
</select>
<br />
<input type="submit" />
</form>
If your 4th option is this:
<option value="value4">Option 4</option>
You can use jQuery to display the field.
Put your field in a <div>
<div id="field"><input type="text" name="firstname"></div>
Now,
<script type="text/javascript">
$(document).ready(function(){
$('input[name="value"]').change(function(){
var v = $('input[name="value"]').val();
if(v=="value4") $('#field').show();
else $('#field').hide();
})
})
This is usually done via javascript; something like this (by using popular JavaScript library, jQuery) :
jQuery(function($){ //calling the code inside braces when document loads and passing jQuery object as '$' parameter;
$("select[name='value']").change(function(){ //binding an event that fires every time select value changes
var select = $(this); //caching select, which value was changed
if(select.val() === "value4"){ //checking if we selected the right option
$("<input>").attr({type: "text", name: "firstname"}).appendTo(select.parent()); //creating new input element object, setting its value to "value4" and appending to select parent element or wherever you want it
}
});
});
Hope that helps. You can find more here jQuery site
I'm not certain this is what you're asking, but it seems you're wanting to add new lines to your select list?
I often do something similar to this for adding new options to lists. The first option would be 'add a new record', like this:
<select name="value">
<option value="-1">Add New Option</option>
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
<option value="value3">Option 3</option>
</select>
Note that the value for "add new" is -1... you could put anything here, but it should be something that would never show up in the other options, so your javascript knows what to do when it is selected.
Add a 'onchange' to the select box like this:
<select name="value" onchange="if(this.value == -1) addOption(this);">
Note that if the selected option is -1, then a javascript function is called. It references itself (this), so that your function knows who called it.
Then create a function that allows adding a new option:
function addOption(theSelectElement){
// create a text box, underneath the select box:
var newInput=document.createElement('input');
newInput.type='text';
theSelectElement.parentNode.insertAfter(newInput,theSelectElement);
}
You'll want to add more code to this function so that the new text field has a name and perhaps an ID.
Hope this helps, or at least points you in the right direction.

Dependable dropdown menus with jQuery, PHP and SQL

this weekend i've been trying to use this script To create dependable menus.
It consists of an sql table with three rows: "ID, Master, Name" It later grabs the entries that contain 0 as the "master" and will use the resulting data to populate the first option list
To populate the next selection lists from the database, it uses a combination of the following JS and php:
and the rest of the select lists will populate accordinly.
The problem that i'm having is that After it populates the select lists I would like to have the visitors of the website hit a seach button to perform a search based on the data collected. The problem is that when I submit the form it sends the info stored in the "master" row of the database instead of the info on "name"
I'm Getting
index.php?genre=1&fruit=37&colour=39
Instead of
index.php?genre=Male&fruit=Strawberry&colour=Red
I tried to switch '.$row['name'].' to '.$row['id'].
But that was a no go, I also tried to only use '.$row['id'].' and it just messed up with the forms. Is there anyway I can accomplish what i'm looking for so that i can send the values selected on the fields to the url?
Thanks in advanced for any help on this one.
The behavior that you mentioned is normal as submitting a form automatically sends the value, instead of the text, of the selected option. The switch that you mentioned ('.$row['name'].' to '.$row['id'].)should work fine. If it is messing up the forms, please provide more information on what you mean by messing up the forms.
Otherwise, here is a possible solution. It's not the most elegant solution and is probably best suited for simple forms that do not require further complexities but basically, generate the querystring and redirect manually. This is based on the original example that you linked to at http://www.ssdtutorials.com/tutorials/series/dependable-dropdown.html.
JS:
var formObject = {
run: function (obj) {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
var id = obj.attr('id');
var v = obj.val();
jQuery.getJSON('http://jquery-dependable-dropdown.ssdtutorials.com/mod/update.php', {
id: id,
value: v
}, function (data) {
if (!data.error) {
obj.next('.update').html(data.list).removeAttr('disabled');
} else {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
}
});
}
};
$(function () {
$('.update').live('change', function () {
formObject.run($(this));
});
$('#submitButton').click(function () {
window.location.href = 'test.php?gender=' + $('#gender').find(':selected').text() + '&category=' + $('#category').find(':selected').text() + '&colour=' + $('#colour').find(':selected').text();
});
});
HTML:
<div id="wrapper">
<form id="theForm" action="" method="post">
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<select name="category" id="category" class="update" disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update" disabled="disabled">
<option value="">----</option>
</select>
<input type="button" id="submitButton" value="submit">
</form>
http://jsfiddle.net/BUJnf/1/
Hope that helps a bit!

Categories