In my page, I have a combo box with an add button. How do I create a new combo box below the original combo box when I clicked the add button? If clicked again, it will produce another combo box. The value inside each combo box is called from the database.
Here's an example, though you'll have to work out the middle tier and back end portion yourself.
Example: http://jsfiddle.net/9hvbt/3/
JavaScript
$('#btnAdd').click(function(){
//Use Ajax to talk to your server (middle tier)
$.ajax({
url: '/echo/json/', //Replace with your URL to return Database data (JSON format)
dataType: 'json',
type: 'get',
success: function(data){
//Use the returned data to pass into CreateDropDown (Hard coded for an example)
CreateDropDown(["Item 1", "Item 2", "Item 3"]);
}
});
});
function CreateDropDown(data){
var $newSelect = $('<select />');
$.each(data, function(i, val){
$newSelect.append($('<option />', {
'text':val
}));
});
$newSelect.appendTo('#dropDowns');
}
HTML
<div id='dropDowns'>
<select>
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
</div>
<input type='button' id='btnAdd' value="Add" />
EDIT
You should also read up on jQuery's AJAX method
any ideas with jquery? jquery clone() will help you to solve this problem
JQuery .clone()
A LIVE EXAMPLE : http://jsfiddle.net/laupkram/6LBNs/
in the case of your problem try to study this one
Dynamic Loading of ComboBox using jQuery and Ajax
Related
I have an HTML table that has a column with select options that submits using onchange event using ajax.
the code works perfectly for the first row of each page (since pagination is applied on the table) but any other row is useless.
I had submitted a question related to this matter earlier and I stumbled on this question by chance that thankfully helped me a lot but not for the entire table.
this is the original Q&A link:
Submit form on select change via AJAX
my customized HTML code
<td>
<form action="" method="POST">
<select class="changeStatus" name="changeStatus" style="margin-bottom:10px;">
<option value="<?php echo $row["STATUS"]; ?>" > <?php echo $row["STATUS"]; ?></option>
<option value="new">new</option>
<option value="checking">checking</option>
<option value="processing">processing</option>
<option value="done">done</option>
</select>
<input class="order_Id" type="hidden" name="order_Id" value="<?php echo $row["ORDER_ID"];?>"/>
</form>
</td>
ajax code
<script>
$(document).ready(function() {
$('select.changeStatus').change(function(){
$.ajax({
type: 'post',
url: 'test2.php',
data: {selectFieldValue: $('select.changeStatus').val(), order_Id: $('input[name$="order_Id"]').val()},
success: function(html){alert('Select field value has changed to' + $('select.changeStatus').val()); },
dataType: 'html'
});
});
});
</script>
note:the alert is only echoing the first row vlue as well.
php code
<?php
$connection = mysqli_connect('localhost' , 'root' ,'' ,'project_name');
$changeStatus=$_POST['selectFieldValue'];
$id=$_POST['order_Id'];
$sql='UPDATE new_order SET STATUS="'.$changeStatus.'" WHERE ORDER_ID ="'.$id.'"';
$result = mysqli_query($connection, $sql);
?>
I have searched for days and this was my one and only successful code so far.
thanks in advance
When handling an event for multiple objects, you need to be careful to handle only the object the event was fired on.
In your case you have an event callback on every select with the class .changeStatus. When any of those are changed, you post with the data
selectFieldValue: $('select.changeStatus').val()
Since $('select.changeStatus') gives you an array of all objects matching the selector, and .val() only returns the value for the first object in the array, you're effectively handling the first row only no matter which row was changed. Instead you need to use
selectFieldValue: $(this).val()
with this referring to the object the event was fired on.
Same goes for your alert; change $('select.changeStatus').val() to $(this).val().
Final script with those changes would be:
<script>
$(document).ready(function() {
$('select.changeStatus').change(function(){
$.ajax({
type: 'post',
url: 'test2.php',
data: {selectFieldValue: $(this).val(), order_Id: $(this).siblings(".order_Id").val()},
//***only select that rows .order_Id by using $.siblings() with selector
success: function(html){alert('Select field value has changed to' + $(this).val()); },
dataType: 'html'
});
});
});
</script>
is it possible to add a new option dynamically to a select box and also can be added to the database using Ajax. i am looking for a button which appends new option to the select box as well as to add that field to the database. Thanks...
EDIT 2
is it possible to update the select box values without page refresh, The case is when i adds new data to database and not making use of .append here...
Try this
This is for add new option in select
$('select').append('<option value="0">--Select--</option>');
And after adding new option you can call ajax
$.ajax({
url:'url',
data:'data',
type:'post',
success:function(data){
}
});
In server side put code to save data in database.
Edit
$.ajax({
url:'url',
data:'data',
type:'post',
success:function(data){
//data will be list of values which you want in options and this sent from server side in json result
$(data).each(function(index,item){
$('select').append('<option value="'+item.val+'">'+item.name+'</option>');
});
}
});
Do you mean something like this?
JSFiddle: http://jsfiddle.net/s4yh3Lor/1/
HTML
<button id="pop-btn">Populate</button>
<select id="options-box">
<option value='1'>Option 1</option>
</select>
jQuery
$(document).ready(function(){
$("#pop-btn").on("click",function(){
value = "2";
name = "Option 2";
$("#options-box").append("<option value='"+value+"'>"+name+"</option>");
$.ajax({
url: "addtodb.php?value="+value+"&name="+name,
type: "GET",
success: function(data) {
alert(data);
}
});
});
});
PHP - While this is valid, make you sure sanitize your inputs into the query to avoid SQL Injection.
$value = $_GET["value"];
$name = $_GET["name"];
mysql_query("INSERT INTO tablename (name,value) VALUES ('$name','$value')");
Hope someone can help me..
i made my program more simpler so that everybody will understand..
i want my program to get the value of the without submitting, i know that this can only be done by javascript or jquery so I use the onChange, but what I want is when i select an option the value should be passed immediately on the same page but using php..
<select id="id_select" name="name" onChange="name_click()">
<option value="1">one</option>
<option value="2">two</option>
</select>
<script>
function name_click(){
value_select = document.getElementById("id_select").value;
}
</script>
and then i should pass the value_select into php in post method.. i dont know how i will do it.. please help me..
You cannot do this using PHP without submitting the page. PHP code executes on the server before the page is rendered in the browser. When a user then performs any action on the page (e.g. selects an item in a dropdown list), there is no PHP any more. The only way you can get this code into PHP is by submitting the page.
What you can do however is use javascript to get the value - and then fire off an AJAX request to a php script passing the selected value and then deal with the results, e.g.
$(document).ready(function() {
$('#my_select').on('change', do_something);
});
function do_something() {
var selected = $('#my_select').val();
$.ajax({
url: '/you/php/script.php',
type: 'POST',
dataType: 'json',
data: { value: selected },
success: function(data) {
$('#some_div').html(data);
}
});
}
With this code, whenever the selected option changes in the dropdown, a POST request will be fired off to your php script, passing the selected value to it. Then the returned HTML will be set into the div with ID some_div.
not sure ..but i guess ajax is what you need..
<script>
function name_click(){
value_select = $("#id_select").val();
$.post('path/to/your/page',{"value":value_select},function(data){
alert('done')
})
}
</script>
PHP
$value=$_POST['value']; //gives you the value_select data
Post with ajax as Alex G was telling you (+1) and then handle the post with PHP. You can define a callback in Javascript which will run when the page responds.
My suggestion go with jquery. Try with this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
<script>
$(document).ready(function(){
$("#id_select").change(function(){
var url = 'http:\\localhost\getdata.php'; //URL where you want to send data
var postData = {'value' : $(this).value};
$.ajax({
type: 'POST',
url: url,
data : postData,
dataType: 'json',
success: function(data) {
//
},
error: function(e) {
console.log(e.message);
}
});
})
})
</script>
In getdata.php
<?php
var $value = $_POST['value'];
// you can do your logic
?>
I'm trying to get a drop down box to alter a second drop down box through the use of a jquery/ajax script. Firebug is showing Jquery is working but my script isn't showing at all.
<script type="text/javascript">
function ajaxfunction(parent)
{
$.ajax({
url: '../functions/process.php?parent=' + parent;
success: function(data) {
$("#sub").html(data);
}
});
}
</script>
process.php is just a MySQL query (which works)
My initial drop down box is populated by a MySQL query
<select name="front-size" onchange="ajaxfunction(this.value)">
//Query
</select>
And then the second drop down box is just
<select name = "front-finish" id="sub">
</select>
How can I solve this?
calling inline function is not good at all... as web 2.0 standards suggest using unobtrusive JS rather than onevent attributes....check out why here..
other thigs..correct way to use ajax is by using type and data ajax option to send values in controller..
<script type="text/javascript">
$(function(){
$('select[name="front-size"').change(function()
{
$.ajax({
url: '../functions/process.php',
type:'get',
data:{'value' : $(this).val()},
dataType:"html", //<--- here this will take the response as html...
success: function(data) {
$("#sub").html(data);
}
});
});
});
</script>
and your proces.php should be..
<?php
//db query ...thn get the value u wanted..
//loop through it..
$optVal .= "<option value="someDbValue">some DDB values</option>";
// end loop
echo $optValue;exit;
updated
looks like you still have onchange="ajaxfunction(this.value)" this in your select remove that it is not needed and the ajaxfunction in javascript too...
<select name="front-size" >
//----^ here remove that
use jQuery.on() that will allow us to add events on dynamically loaded content.
$('select[name^="front-"]').on('change',function(e){
e.preventDefault();
var value = $(this).val();
ajaxfunction(value);
});
[name^="front-"] this will select all the SELECT box having name starts with front-.
In your process.php give like this
echo "<select name='front-finish' id='sub' onchange='ajaxfunction(this.value)'>";
like this you need to add the "onchange" function to the newly created select box through ajax
or you can remove onchange function and write like
$("select[name^='front-']").live('change',function(){
//Do your ajax call here
});
I have a drop down list (ddlAccount) which i can choose an item from it and do a db query in test.php to retrieve corresponding data, then output an input element with the returned data.
This is my javascript code:
function load1(){
$('#divAccountNum').load('test.php?accountInfo=' + document.getElementById('ddlAccount').value , '' ,function() {
alert('Load was performed.')});
}
load1 function called when i change the dropdown list items, and it takes the value of the selected option and sends it to test.php in a parameter called "accountInfo".
my html:
<select name="ddlAccount" id="ddlAccount" onchange="load1();">
<option value="1"> Account1</option>
<option value="2"> Account2</option>
<option value="3"> Account3</option>
</select>
<div id="divAccountNum" >
</div>
And test.php :
if($_GET['accountInfo'])
{
$account = $accountDAO->load($_GET['accountInfo']); //mysql query
//print an input holding account number as its value
echo "<input type='text' name='txtAccountNum' id='txtAccountNum' value='".$account->accountnumber."'/>";
}
The problem is that nothing happened when i choose an option (nothing appear in div (divAccountNum))
Any suggestions? Thanks in advance.
Edit:
I used #thecodeparadox 's bit of code and it works and i found a solution for the problem that i mentioned in the comments below which is that when choosing one item from the dropdown list it shows the value in input element and loads the form again. The solution is in:
jQuery Ajax returns the whole page
So my jquery code now looks like:
$(document).ready(function(){
$('#ddlAccount').on('change', function() {
$.get('testJquery.php?accountInfo=' + $(this).val(), function(accountNum) {
//console.log(accountNum);
$('input#txtAccountNum').val(accountNum);
});
});
And testJquery.php :
if($_GET['accountInfo'])
{
$account = $accountDAO->load($_GET['accountInfo']);
$accountNum = $account->accountnumber;
echo $accountNum;
}
And at last i added input element in divAccountNum which has id="txtAccountNum"
Though you don't give enough info about your problem, but you can try this:
function load1(){
$('#ddlAccount').on('change', function() {
$.get('test.php?accountInfo=' + $(this).val(), function(response) {
$('div#divAccountNum').html(response);
}, 'html');
});
}
NOTE:
$('#ddlAccount').on('change', fires when dropdown change
$.get('test.php?accountInfo=' + $(this).val().. send a get(ajax) request to test.php with value selected from drop down
parameter response with in $.get() second parameter callback function is the response from the server
'html' as third parameter of $.get() for data type you return, as you return a html so it is html.
for more info read:
change()
$.get()
To get selected option value from select input use:
$('#ddlAccount option:selected').val()