Selecting default value in html dropdown list - javascript

I am currently looking to have a drop down list in my form. I have this drop down which selects the default value:
<p>Price Band:<select id='priceBand' style = 'width:150px' value = 'band1'>
<option value="band7">Reduce by 30c</option>
<option value="band6">Reduce by 25c</option>
<option value="band5">Reduce by 20c</option>
<option value="band4">Reduce by 15c</option>
<option value="band3">Reduce by 10c</option>
<option value="band2">Reduce by 5c</option>
<option value="band1" selected="selected">default</option>
</select></p>
Which works fine and selects the default as the default value. But what I also need to be able to do - after the form is submitted I want it to keep the last selected value as the default one. It is a form used to add sales with different price bands. The sales are entered by the price bands so the defaults are entered first, the band2, band3 and so on.. What is the best way of doing it? I am currently using javascript and php on the page if that makes it any easier?
Ajax code. I didn't include getting the value of the dropdown as this is only a new thing that I am implementing. I just want to know if it is possible to have a default value selected when the form is loaded first and then when a different value is selected, to keep that value as the new default:
$('#divItemisedSaleAdd').dialog({'autoOpen': false, 'modal' : true, 'buttons' :
[ { text: "Ok", click: function() {
var url = '<?php echo Navigation::gUrl('/users/admin/stocktake_details_sales.php', array('stocktake_id' => $stocktake_id, 'action' => 'add_itemised_sale'));?>';
var productCode = $('#ProductCode').val();
var qty = $('#Quantity').val();
var dialog = this;
$.ajax({
url: url,
dataType: 'json',
data: {'productCode' : productCode, 'qty' : qty},
type: 'post',
timeout: 5000,
success: function(json) {
if (json.status == 'S'){
alert('Sale added');
}
else if (json.status == 'E')
alert('No product with given PLU was found! Please check!');
// loadDepartments();
$( dialog ).dialog( "close" );
},
error: function() {}
});
} } ] });

You can use localStorage for that purpose:
$('#divItemisedSaleAdd').dialog({'autoOpen': false, 'modal' : true, 'buttons' :
[ { text: "Ok", click: function() {
var url = '<?php echo Navigation::gUrl('/users/admin/stocktake_details_sales.php', array('stocktake_id' => $stocktake_id, 'action' => 'add_itemised_sale'));?>';
var productCode = $('#ProductCode').val(),
qty = $('#Quantity').val(),
dialog = this;
// save current selected value in storage
localStorage.setItem("default_option", productCode);
$.ajax({
url: url,
dataType: 'json',
data: {'productCode' : productCode, 'qty' : qty},
type: 'post',
timeout: 5000,
success: function(json) {
if (json.status == 'S'){
alert('Sale added');
}
else if (json.status == 'E')
alert('No product with given PLU was found! Please check!');
// loadDepartments();
$( dialog ).dialog( "close" );
},
error: function() {}
});
} } ] });
// after page reload
if (localStorage.getItem("default_option")) {
$('#ProductCode').val(localStorage.getItem("default_option"));
}

This might do it - either selected = "selected" or just selected depending on whether you will use XHTML or not. It requires making the value a simple integer, but that simplifies cleaning it up by allowing you just to use its intval() which you would use in your query as well as to control the selected option. This version assumed page submission which apparently is not the case here now as it is all done by Ajax but hope it will be useful to someone.
if(!isset($priceBand_value)) $priceBand_value = array();
$priceBand_value = ''; // reset it if already used
// set default 'selected = "selected"'; or just 'selected';
<?php if(!isset($_POST['priceBand']) $priceBand_value[1] = 'selected = "selected"'; ?>
<?php $priceBand_value[intval($_POST['priceBand'])] = 'selected = "selected"'; ?>
<p>Price Band:<select id='priceBand' style = 'width:150px'>
<option value="7" <?php echo $priceBand_value[7] ?>>Reduce by 30c</option>
<option value="6" <?php echo $priceBand_value[6] ?>>Reduce by 25c</option>
<option value="5" <?php echo $priceBand_value[5] ?>>Reduce by 20c</option>
<option value="4" <?php echo $priceBand_value[4] ?>>Reduce by 15c</option>
<option value="3" <?php echo $priceBand_value[3] ?>>Reduce by 10c</option>
<option value="2" <?php echo $priceBand_value[2] ?>>Reduce by 5c</option>
<option value="1" <?php echo $priceBand_value[1] ?>>default</option>
</select></p>
You could start from 0 rather than 1 for most cases but this was intended primarily to fit the code framework given. This would avoid the need to set the default as intval($_POST['priceBand']) would be 0 when the page is first rendered but in this case it could be harder to keep track of the "bands".

Related

How can I add select2 dynamic select box inside a while loop?

I'm trying to put a Select2 box inside a while loop. But it only works the first select tag. Although loop works fine, the select tag is not working after the first 1. how can I fix this issue?
I also tried adding printing PHP unique id to fix it. but nothing happened.
<select type="text" name="city" id="city-<?php echo $id; ?>" class="form-control"></select>
This is the javascript part:
<script type="text/javascript">
$('#city-<?php echo $id; ?>').select2({
placeholder: 'Select city',
ajax: {
url: 'processes/cities.php',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
</script>
I'm expecting all the select boxes to work fine. But actually, only first 1 works.
It would be helpful if you provided the loop in your code example.
The most likely problem is that your id's are not unique. If you have multiple tags with the same id then javascript will only recognize the first one.
Here's an example to demonstrate.
https://jsfiddle.net/n8vxjoc1/1/
<div id="city-1">Content</div>
<div id="city-1">Content</div>
<script>
jQuery( '#city-1' ).html( jQuery( '#city-1' ).length );
</script>
Only the 1st element will change and it will display the number 1.
From the W3C specs:
The id attribute specifies its element's unique identifier (ID).
https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute
You should give the select dropdowns a class and target that instead.
E.g.
https://jsfiddle.net/n8vxjoc1/1/
<select name="city" class="select2 form-control">…</select>
<select name="city" class="select2 form-control">…</select>
<script type="text/javascript">
$('select.select2').select2({});
</script>
You can take help from this link: Demo
<select class="select2_el" style='width: 200px;'>
<option value='0'>- Search user -</option>
</select>
<div id='elements'>
</div>
<input type="button" id="btn_add" value="Add">
PHP:
<?php
include 'config.php';// add your config details on that file
$request = 1;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Select2 data
if($request == 1){
if(!isset($_POST['searchTerm'])){
$fetchData = mysqli_query($con,"select * from users order by name limit 5");
}else{
$search = $_POST['searchTerm'];
$fetchData = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5");
}
$data = array();
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array("id"=>$row['id'], "text"=>$row['name']);
}
echo json_encode($data);
exit;
}
// Add element
if($request == 2){
$html = "<br><select class='select2_el' ><option value='0'>- Search user -</option></select><br>";
echo $html;
exit;
}
JS
$(document).ready(function(){
// Initialize select2
initailizeSelect2();
// Add <select > element
$('#btn_add').click(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 2},
success: function(response){
// Append element
$('#elements').append(response);
// Initialize select2
initailizeSelect2();
}
});
});
});
// Initialize select2
function initailizeSelect2(){
$(".select2_el").select2({
ajax: {
url: "ajaxfile.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}

Trying to populate select based on previous 2 selection

Can You Please Find Out The Problem In The Following Code
I am trying to populate 1 select option based on previous 2 select options.
For example, you will select option 1 and then select option 2 based on those 2 options I will get 3rd option.
Here is my jquery part
/*This Is Basically My Jquery Part Which will Take 2 values from selects*/
$(".asset").change(function(){
var id=$(this).val();
console.log(id);
var dataString1 = 'id='+ encodeURIComponent(id);
console.log(dataString1);
$(".amc").change(function(){
var aid=$(this).val();
console.log(aid);
var dataString2 = 'aid='+ encodeURIComponent(aid);
console.log(dataString2);
//console.log(data);
$.ajax({
type: "POST",
url: "fetch.php",
data : {dataString1: id,dataString2: aid},
cache: false,
success: function(html)
{
$(".scheme").html(html);
}
});
});
});
Here is the fetch part
<?php
include('dbconfig.php');
if($_POST['id'] && $_POST['aid'])
{
$id=$_POST['id'];
$aid=$_POST['aid'];
$stmt = $DB_con->prepare("SELECT * FROM Master_MutualFundMasters WHERE AssetClassID=:id AND AMCID = :aid");
$stmt->execute(array(':id' => $id));
$stmt->execute(array(':aid' => $aid));
?><option selected="selected">Select City :</option>
<?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value="<?php echo $row['WW_UniqueInvestmentCode']; ?>"><?php echo $row['PrimarySchemeName']; ?></option>
<?php
}
}
?>
When I check my console it is showing me the data but its not passing on next page
You should use select at beginning.
Example:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi" selected>Audi</option>
</select>
since you are asking
In your console it is showing me the data but its not passing on next page means (fetch.php).
then you can do-
$.ajax({
type: "POST",
url: "fetch.php",
data : {"id":dataString1,"aid":dataString2},
cache: false,
success: function(html)
{
$(".scheme").html(html);
}
});
and in fetch.php page.
if($_POST["id"] && $_POST["aid"])
{
$id=$_POST["id"];
$aid=$_POST["aid"];
//write ur code here...
}
I Hope this help u.

How to populate a dropdown with AJAX

I want to populate a dropdown (AJAX) when I click on the dropdown.
I have a dropdown categories and a button Add categories
When I open the page the first time, I can see my categories inside the dropdown.
If I want to include another categories, I click on Add categories and I insert my new categories.
After, if I click on the dropdown, I must see my new categories.
How to do that ?
I don't know exactly how to create that.
Thank you
my_ajax_file.php
$Qcheck = $OSCOM_Db->prepare('select categories_id as id,
categories_name as name
from :table_categories');
$Qcheck->execute();
$list = $Qcheck->rowCount();
if ($list > 0) {
$array = [];
while ($value = $Qcheck->fetch() ) {
$array[] = $value;
}
# JSON-encode the response
$json_response = json_encode($array); //Return the JSON Array
# Return the response
echo $json_response;
HTML code
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
});
}
</script>
<select name="category_id" id="Mycategory_id" class="form-control">
<option value="0" selected="selected">Haut</option>
<option value="23">Panneaux Signalétique</option>
<option value="20">Signalétique Camping</option>
<option value="22"> Barrières</option>
<option value="21"> Entrée</option>
</select>
<input type="hidden" name="current_category_id" value="0" /></div>
You need to update the select element with new options.
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
var options_html = '';
for(index in data){
var category_id = data[index]['categories_id'];
var category_name = data[index]['categories_name'];
options_html += '<option value="'+category_id+'">' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
)};
</script>
To make rendering easy, you can use mustache.js

codeigniter csrf not work in select option

I want to make step input with select option, in this case, i make 3 step, when select first option then will show next option 2, then option 3. i am using ajax and i set $config['csrf_protection'] = TRUE; in Codeigniter config file. In first select option (#kategori) is work and show next value in second select option, but in step 3 select option (#sub1 or secon function of javascript) n't work. thank before.
This is my view:
<?php echo form_open_multipart('',array('class'=>'form-horizontal'));?>
<?php echo form_label('Kategori','id_kategori',array('class'=>'col-sm-2 control-label'));?>
<select id="kategori" name="id_kategori">
<option value=""></option>
<?php
foreach($kategori as $kategori_umum)
{
echo '<option value='.$kategori_umum->id.'>'.$kategori_umum->nama_kategori.'</option>';
}
?>
</select>
<select id="sub1" name="id_kategori_sub1"> //step 2
<option value=""></option>
</select>
<select id="sub2" name="id_kategori_sub2"> //step 3
<option value=""></option>
</select>
Ajax :
<script type="text/javascript">
$('#kategori').change(function(){
var kategori_id = $('#kategori').val();
//alert(state_id);
if (kategori_id != ""){
var post_url = "<?php echo base_url();?>masuk/produk/get_sub1";
$.ajax({
type: "POST",
url: post_url,
data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>','kategori_id':kategori_id},
dataType: 'json',
success: function(kategori_sub1, dataType) //calling the response json array 'kategori_sub1'
{
$('#sub1').empty();
$('#sub1').show();
$.each(kategori_sub1,function(id,sub1)
{
var opt = $('<option />'); // creating a new select option for each group
opt.val(id);
opt.text(sub1);
$('#sub1').append(opt);
$('#sub2').hide();
});
},
error:function(xhr)
{
alert("Terjadi Kesalahan");
}
}); //end AJAX
} else {
$('#sub1').empty();
$('#sub2').empty();
}});
$('#sub1').mouseout(function(){
var sub1_id = $('#sub1').val();
if (sub1_id != ""){
var post_url = "<?php echo base_url();?>masuk/produk/get_sub2";
$.ajax({
type: "POST",
url: post_url,
data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>','sub1_id':sub1_id},
dataType: 'json',
success: function(kategori_sub2, dataType)
{
$('#sub2').empty();
$('#sub2').show();
$.each(kategori_sub2,function(id,sub2)
{
var opt = $('<option />');
opt.val(id);
opt.text(sub2);
$('#sub2').append(opt);
});
},
error:function(xhr)
{
alert("Kesalahan");
}
}); //end AJAX
}});</script>
I suspect your problem is using wrong event mouseout.
You should be using change the same way the first one that works does.
Beyond that more information is needed about the actual requests by inspecting in browser dev tools

How to display the data came from controller/model using Ajax process?

I have a problem here about ajax. Actually I'm a beginner in using Ajax that's why I can't figure out my problem. I have a form that have 4 select boxes. The initial or main selectbox is the country selector. Second is the state next is city and last is barangay. My goal is like this. After the user select his'her country the second selectbox which is state will automatically change according to the user's country. And after selecting the state it will automatically change also the city and last is the barangay. It is just like a dynamic address fields. I am using codeigniter. Here's what I did. This is the process for getting the state.
In my PHP form I have this:
<tr>
<td><label style="font-weight: normal">State / Province: </label></td>
<td >
<select class="form-control" name="c_state" id="c_state">
<option value="">--Select State--<option>
</select>
</td>
</tr>
<tr>
<td><label style="font-weight: normal">Country: </label></td>
<td >
<select class="form-control" name="c_country" id="c_country">
<option value="">--Select Country--</option>
<?php
foreach($countries as $country){
if($country['country'] == 'Philippines'){
echo "<option value='".$country['code']."'selected='selected'>".$country['country']."</option>";
}else{
echo "<option value='".$country['code']."'>".$country['country']."</option>";
}
}
?>
</select>
</td>
</tr>
....
$("#c_country").on('change',function(){
var c_country = $("#c_country").val();
var var_country_selection = '<?php echo site_url("alliance_controller/get_provinces/'+c_country+'"); ?>';
console.log(c_country);
$.ajax({
type: 'POST',
url: var_country_selection,
data: { id: $(this).val() },
dataType: 'json',
success: function(d){
alert(d['c_country']);
}
});
});
In my controller I have this:
public function get_provinces($id){
$country = $this->alliance_model->hhj_provinces($id);
echo json_decode($country);
}
In my model I have this:
public function hhj_provinces($id) {
$query = "SELECT * FROM ref_region_province WHERE country_code = '".$id."'";
$result = $this->db->query($query);
echo json_encode($result->result_array());
}
The output in the success in jquery which is in alert is 'undefined'. And I also use the developer tool in Chrome and I looked in the Network tab it shows the URL of my ajax together the Code. But in my preview I have something like this.
[]
No Properties
That's all guys. I just want to get the state of the country selected.
you must return a JSON object in the controller like this
public function get_provinces(){
$id = $this->input->post('id');
$country = $this->alliance_model->hhj_provinces($id);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode( $country));
}
then in the View
$.ajax({
type: 'POST',
url: var_country_selection,
data: { id: $(this).val() },
dataType: 'json',
success: function(data){
$.each(data, function (key, value) {
console.log(value.field)
}
});

Categories

Resources