Dynamically Set Value in seletpiker using jquery and Ajax - php

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

Related

repopulate child dropdow when parent dropdown changed

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

how to add more dropdown options to it with ajax or jquery?

In my code new value through textbox is getting added to dropdown and stored in database but the problem is that, previous dropdwn list like here say rohit,viraj etc is not getting displyed along with new inserted value. how to show all option list along with new added one? is there any perfect way to do this using array? please help...
htmlcode
`html code:
<select class="deligates1" id="deligates1" name="deligates1[]" size="1" multiple>
<option value="">--select--</option>
<option value="rohit">ROHIT</option>
<option value="viraj">VIRAJ</option>
<option value="sachin">SACHIN</option>
</select>
<span style="cursor:pointer;background-color:lightgoldenrodyellow;">Add delegates here</span><span><input type="text" id="write_dele" name="write_dele" >
<input type="button" id="add_dele" value="add"></span>
`
script code
:<script>
$(document).ready(function(){
$("#add_dele").click(function(){
var delegate = $("#write_dele").val();
$.ajax({
type:'POST',
data:'q='+delegate,
url:'add1.php',
success:function(new_delegate){
$("#deligates1").html(new_delegate);
}
});
});
});
</script>
add1.php:
<?php
$new_delegate=$_POST['q'];
$con=mysql_connect("localhost","root","");
mysql_select_db("task",$con);
echo '<option value="'.$new_delegate.'" >'.$new_delegate.'</option>';
?>
.html() Replace the entire select option with your new option
Try with this
$("#deligates1").append(new_delegate); // it will add your new option in select box

Populate inputs on selects JQUERY

i have a dropdown menu generated by my php when the page loads filling with my rows in the sql table, being the table ID(Value) and they NAME.
<select>
<option value="0"></option>
<option value=6>Alientech</option>
<option value=2>FNAC</option>
<option value=5>Logitech</option>
<option value=1>MHR</option>
</select>
Then i have:
<input type="text" name="editname">
<input type="text" name="editmail">
<input type="text" name="editwebsite">
<input type="text" name="editphone">
<input type="text" name="editfax">
<input type="text" name="editadress">
<input type="text" name="editincharge">
What i want to do is on selecting the option above he gets the id of the row in mysql and fills the inputs accordingly to the values in the SQL table so a person can edit the values on submitting the form.
How can i with jQuery do this?
Where is your code attempt?
The way to do this is on select of the jquery
you would take the value of the select where
<select id="some_id">
also you will need to ID all your fields of input.
Your PHP script should return a JSON where your on success you parse the JSON and set it to the value of your INPUT field via ID.
$.ajax({
url: some_php_mysql.php
type:post,
data: {some_id:$('#some_id').val()},
success:function(data){
//json object returned - parse and then ID each value
});
First, you could reload the page :
<form action="" method="post" id="myform">
<select name="myselect">
<option value="0" disabled="disabled"></option>
<option value=6>Alientech</option>
<option value=2>FNAC</option>
<option value=5>Logitech</option>
<option value=1>MHR</option>
</select>
</form>
With a little bit of jQuery...
$("form#myform select").change(function(){
$("form#myform").submit(); // Submit the form if the value is changed.
});
And when you load your page, if you find a value for $_POST["myselect"] then you have to load something in the fields (except if it's 0).
You could also do things asynchronously with Ajax (instead of submitting the form, send a HTTP request and parses the result to fill the form). However, if the purpose of your page is only to edit an entry, the you should use the above method.
Ajax reference : http://www.w3schools.com/ajax/

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!

jQuery Related (Dependent) Selects Plugin

I found this jquery plugin for dependent select box . This worked now but i have big problem ! when put this in submit form not worked because this plugin worked with form id and post/get data using json. Original Demo HERE
Problem e.x:
<div id="box">
<form action="search.php" method="POST" >
<form id="example-1">
<div class="field">
<label for="name">state :</label>
<select name="stateID">
<option value="">Choose State »</option>
<option value="MA">Massachusetts</option>
<option value="VT">Vermont</option>
</select>
</div>
<div class="field">
<label for="name">Country :</label>
<select name="countyID">
<option value="">Choose County »</option>
</select>
</div>
<div class="field">
<label for="name">town :</label>
<select name="townID">
<option value="">Choose Town »</option>
</select>
</div>
<div class="field">
<label for="name">village :</label>
<select name="villageID">
<option value="">Choose Village »</option>
</select>
</div>
</form>
</form>
</div>
If I Remove form action this plugin worked perfectly, Otherwise not worked. How To Fix This Thanks.
To elaborate on my comment, you can capture the submit of the form and do with it what you like.
$("form").submit(function(e){
e.preventDefault(); //stop the default behavior
$.ajax({
type: 'POST', //default is get, set to 'POST' if you want to post.
url: 'search.php',
success: function(data){
//if our data was returned from our search file as json, then...
$("#element").html(data.a) //returns the a value from our json object
$("#element").html(data.b) //returns the b value from our json object
//etc
}
});
});
The submit function stops the form from submitting per the usual fashion, and stops the page-reload. Then we use an ajax request to send our data through the 'POST' method to our file search.php. The returned data is sent in an object, and we access it through our success:function(data). Then, if our data was returned with JSON values, we can use data.a to get the a value, or data.b to get the b value of our JSON string.

Categories