Can anyone help me to populate the select box from web sql. I am creating an offline mobile app. So I have two select boxes one for category and other for level. When the user selects the category corresponding level has to appear in the select box. As I am new to web sql I need some help to get the corresponding level from web sql based on the category selected in the first drop down box.Thanks in advance.
$(document).ready(function(){
$('#category').on('change',function(){
var cat = document.getElementById('category').value;
alert(cat);
db.transaction(function (tx) {
//alert("SELECT levell FROM level WHERE category="+cat);
tx.executeSql('SELECT levell FROM level WHERE category='+cat, [category], function (tx,results) {
alert("hello");
for (var i=0; i < results.rows.length; i++){
row = results.rows.item(i);
editRecords2(row.lev_id,row.levell);
}
});
});
});
});
function editRecords2(lev_id,levell) {
f = $('#level');
f.html("");
f.html(f.html() + '<option value='+lev_id+'>'+levell+'</option>');
}
html:
<select id='category' required>
<option value='' disabled selected>Select your category</option>
<option id='c1'>Category 1</option>
<option id='c2'>Category 2</option>
<option id='c3'>Category 3</option>
<option id='c4'>Category 4</option>
<option id='c5'>Category 5</option>
<option id='c6'>Category 6</option>
</select>
<select id="level">
<option value="">Select your level</option>
</select>
Assuming you have a country table set up in your database here is a working example on Chrome.
<script type="text/javascript" src="../assets/js/jquery.min.js"> </script>
<script type="text/javascript">
var errCallback = function(){
alert("Database Error!");
}
// initialise the db - this will fail in browsers like Firefox & IE
var db = openDatabase("local_customers", "0.1", "myData", 65536);
db.transaction(
function(transaction) {
transaction.executeSql(
'CREATE TABLE IF NOT EXISTS customers (user_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, country_id TEXT);'
);
});
// This is the SAVE function
var saveCustomers = function(user_id, country_id, successCallback){
db.transaction(function(transaction){
transaction.executeSql(("INSERT INTO customers (user_id, country_id) VALUES (?, ?);"),
[user_id, country_id], function(transaction, results){successCallback(results);}, errCallback);
});
};
// Document ready event.
$(function(){
var form = $("form");
db.transaction(function (tx) {
tx.executeSql('select * from country', [], function (tx, results){
var len = results.rows.length, i;
var html = "<select name=\"country_id\">";
for (i = 0; i < len; i++) {
html += "<option value='" + results.rows.item(i).country_id + "'>" + results.rows.item(i).country + "</option>";
}
html += "</select>";
var el = document.getElementById("country_id");
el.innerHTML = html;
});
});
// Override the default form submit in favour of our code
form.submit(function(event){
event.preventDefault();
saveCustomers($('#user_id').val(), $('#country_id').val(), function(){
alert($('#country_id').val() + " has been added.");
})
});
});
<!--HTML is here & just using a dummy input for user_id here-->
<form>
<input type="text" id="user_id" name="user_id" class="user_id" value = "2" hidden />
<p><select type="text" id="country_id" name="country_id" class="country_id" >Select Country</select></p>
<p><input type="submit" value="Add Country" /></p>
</form>
Related
i want to automatically select value of dropdown matching value of php variable
here is my
<select class="destinationId" id="destination" name="destinationId" onchange="getNationalityAndLiving(this.value,'','');">
<option value="" disabled selected>Select Traveling to</option>
<option data-prefix="azerbaijan" value="azerbaijan" >
Azerbaijan </option>
<option data-prefix="cambodia" value="cambodia" >
Cambodia </option>
<option data-prefix="egypt" value="egypt" >
Egypt </option>
<option data-prefix="india" value="india" >
India </option>
<option data-prefix="kenya" value="kenya" >
Kenya </option>
</select>
<select class="nationality" name="nationality" id="nationality">
<option value="" disabled selected>Select Citizen of</option>
</select>
this is my ajax code to retrive dynamic dropdown for select select option "nationality"
<script>
$(document).ready(function(){
$("#destination").change(function(){
var deptid = $(this).val();
var dbnm = "country";
var res = dbnm.concat(deptid);
$('.overlay').show();
$.ajax({
url: 'getcountry.php',
type: 'post',
data: {dest:res},
dataType: 'json',
success:function(response){
var len = response.length;
$("#nationality").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#nationality").append("<option data-nation='"+name+"' value='"+name+"'>"+name+"</option>");
}
$('.overlay').hide();
}
});
});
});
</script>
i have some dynamic php variable coming on this page from previous url.
for example
$nationality = "some value";
What i want is selected dropdown with value of $nationality in second dropdown,
if it was static i could have achieved this, but how to auto select in dynamic i am not able to get any workaround.
you can pass the php variable to js variable
var Nationality = "<?php echo $nationality; ?>";
then when append the option you can use
$("#nationality").append("<option data-nation='"+name+"' value='"+name+"' "+ (Nationality.trim() == name.trim()) ? 'selected' : '' +">"+name+"</option>");
I have two selection (city, building) is the dependent on what the users choose for state.
<form method="post">
<div class="summary">
<div class="trip">
<select name="State" class="state">
<option selected disabled>Choose a State</option>
<option value="1">California</option>
<option value="2">New York</option>
</select>
<select name="City" class="city" disabled="true">
<option value="Z">Select a city</option>
</select>
<select name="Building" class="building" disabled="true">
<option value="Z">Select a building</option>
</select>
<br><br>
</div>
</div>
City and building is pull as json from an ajax call.
jQuery:
$(document).ready(function() {
var additional = $('.trip').html();
$('#result').hide();
$('form').on("change", "select", function(){
var current_index = $(this).index();
if ($(this).is('.state')) {
var stateid = $(this).val();
}
else {
var stateid = $(this).siblings('.state').val();
};
if($(this).eq(current_index).val() == 'Z') {
$('.city').eq(current_index).html("<option>Select a fare</option>");
$('.city').eq(current_index).attr('disabled', true);
$('.building').eq(current_index).html("<option>Select a fare</option>");
$('.building').eq(current_index).attr('disabled', true);
}
else {
var current = $(this);
$.getJSON('get_city/', {state_id: stateid}, function(data) {
var options_city = '<option value="Z">Select a city</option>';
for(var i=0; i<data.length; i++){
options_city+='<option value="'+data[i].pk+'">'+data[i].fields['name']+'</option>';
}
current.siblings('.city').html(options_city);
current.siblings('.city option:first').attr('selected', 'selected');
current.siblings('.city').attr('disabled', false);
});
$.getJSON('get_building/', {state_id: stateid}, function(data) {
var options_building = '<option value="Z">Select a building</option>';
for(var i=0; i<data.length; i++){
options_building+='<option value="'+data[i].pk+'">'+data[i].fields['building']+</option>';
}
current.siblings('.building').html(options_building);
current.siblings('.building option:first').attr('selected', 'selected');
current.siblings('.building').attr('disabled', false);
});
}
});
$('#add').click(function() {
if ($('.summary').children().length >= 4) return;
$('.summary').append('<div class="trip">' + additional + "<div>");
});
});
The output of the json AJAX for city looks like:
<option value="1">New York City</option>
<option value="2">Albany</option>
Similarly for buildings:
<option value="1">Empire State Building</option>
<option value="2">Penn Station</option>
The issue here is that when I select a city, the building select box resets and all of the options disappears. I know this is because the two getjson call is in the same function. How do I make it so that the selection of city and building are independent from each other?
Once state has been changed and select, I should only need to call $.getjson once until someone changes the state value again.
Here is the relevant code that is "resetting" the city and building checkboxes:
$('form').on("change", "select", function(){
var current_index = $(this).index();
if($(this).eq(current_index).val() == 'Z') {
} else {
current.siblings('.city option:first').attr('selected', 'selected');
current.siblings('.building option:first').attr('selected', 'selected');
}
});
So any time you change ANY dropdown, as long as the value isn't Z, you are setting the city and state to the first option.
Instead of doing $('form').on("change", "select", function(){}) and then if statements for each input, why don't you monitor the change event for each input directly:
<select id="selState" name="State" class="state">
<option selected disabled>Choose a State</option>
<option value="1">California</option>
<option value="2">New York</option>
</select>
<select id="selCity" name="City" class="city" disabled="true">
<option value="Z">Select a city</option>
</select>
<select id="selBuilding" name="Building" class="building" disabled="true">
<option value="Z">Select a building</option>
</select>
If you want to populate the city and building dropdowns based on the state dropdown, and do nothing when the city and building dropdowns are changed, you would do something like this:
$('form').on("change", "#selState", function(){
//get state id
var stateid = $(this).val();
//Get cities for selected state
$.getJSON('get_city/', {state_id: stateid}, function(data) {
//add "Select a city option"
$('#selCity').html('<option value="Z">Select a city</option>');
//Loop through returned cities.
for(var i=0; i<data.length; i++){
//add city to select
$('#selCity').append('<option value="'+data[i].pk+'">'+data[i].fields['name']+'</option>');
}
});
//Get buildings for selected state
$.getJSON('get_building/', {state_id: stateid}, function(data) {
//add "Select a building option"
$('#selCity').html('<option value="Z">Select a building</option>');
//Loop through returned buildings.
for(var i=0; i<data.length; i++){
//add building to select
$('#selBuilding').append('<option value="'+data[i].pk+'">'+data[i].fields['name']+'</option>');
}
});
//enable other select
$('#selCity').attr('disabled', false);
$('#selBuilding').attr('disabled', false);
})
I have a page that builds drop down menus dynamically from the database as follows:
<select name="set_order[]" class="form-control" data-catid="3">
<option value="1" selected="">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="set_order[]" class="form-control" data-catid="2">
<option value="1">1</option>
<option value="2" selected="">2</option>
<option value="3">3</option>
</select>
<select name="set_order[]" class="form-control" data-catid="1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected="">3</option>
</select>
What I want to do is that when one of them is changed, I want to resort the drop downs according to the change that was made with Javascript and update the selected dropdown in each dropdown so as that each drop down has a unique choice made.
I've been trying to sort them but I haven't been successful.
Thank you in advanced!
Edit, as requested, here is my trial JS to sort them:
$(document).on('change', 'select[name="set_order[]"]', function(){
var newOrder = $(this).val();
var change_id = $(this).attr('data-catid');
console.log(newOrder, ' ', change_id);
var order = new Array();
var cat_id = new Array();
var checker = false;
$('select[name="set_order[]"]').each(function(i){
order[i] = parseInt($(this).val());
cat_id[i] = parseInt($(this).attr('data-catid'));
console.log(order[i], ' ', cat_id[i], ' ', i);
if(checker == false){
if(cat_id[i] == change_id){
checker = true;
}else{
order[i] = order[i] + 1 ;
}
}else{
order[i] = order[i] - 1;
}
//console.log(order[i], ' ', cat_id[i], ' ', i);
});
});
You can do that with jQuery
//Sort alphabetically the contact list in the biography page
function sortList() {
//Replace #list by the id of the div who enclose your select
$("#list").html(
$(".form-control").children("option").sort(function (a, b) {
return $(a).text().toUpperCase().localeCompare(
$(b).text().toUpperCase());
})
);
};
I have an ajax dynamic dropdown form that onchange changes a second dropdown based on the firsts selection. However, if someone were to reset the form, all elements get cleared except for the dynamic one.
I made a reset button function that does: $('#myForm')[0].reset();
However it doesn't reset the dynamic dropdown.
Then I added $('#state').prop('selectedIndex',0); which only then selects the initial subitem.
Essentially I want it to go back to the default <option value="">State/Province</option> state that was there prior to becoming dynamic and I cannot figure out how to exactly to do this.
I am very very new and used previous questions and google to even get me this far.
Thanks
Update:
This is what I need reset:
<select name="state" class="dropdown" id="state">
<option value="">State/Province</option>
<!-- this is populated by ajax -->
</select>
This form changes the above:
<select name="country" class="dropdown" id="country" onchange="getStates();">
<option value="">Select Country</option>
<?php
$con = mysql_connect($db_host, $db_user, $db_pass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('earth');
$query = "select id,country from regions order by country";
$result = mysql_query($query);
while ( $row = mysql_fetch_object( $result ) )
{
?>
<option value=<?php echo $row->id; ?>><?php echo $row->country;?> </option>
<?php }
mysql_free_result($result);
?>
</select>
Additional code:
function getStates()
{
$('#state').html('');
var e = document.getElementById("country");
var countryID = e.options[e.selectedIndex].value;
$.ajax({
type: "POST",
url: "getStates.php",
data: {countryID:countryID},
dataType:'json',
//success: function(result){
success: function(data){
var toAppend = '';
$.each(data,function(i,o){
toAppend += '<option value=' +o.id + '>' + o.name + '</option>';
});
$('#state').append(toAppend);
},
});
}
function reset_select_box(selector, default_value)
{
if(typeof default_value !== 'string') default_value = "";
var select_box = $(document).find(selector),
children = select_box.children();
console.log(children);
for(var i in children){
if(children[i].value === ""){
select_box.prop('selectedIndex', i);
}
}
};
function resetForm()
{
// since the form is dynamic, reset form does not reset the states
$('#frmSigGen')[0].reset();
}
This seems to do the trick:
function resetForm()
{
$('#frmSigGen')[0].reset();
$('#state').empty();
$('#state').append('<option value="">State/Province</option');
}
Maybe try looping through the select elements children looking for the default value?
var reset_select_box = function(selector, default_value){
if(typeof default_value !== 'string') default_value = "";
var
select_box = $(document).find(selector),
children = select_box.children();
console.log(children);
for(var i in children){
if(children[i].value === ""){
select_box.prop('selectedIndex', i);
}
}
};
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<select id="test">
<option value="">Default</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5</option>
</select>
<button type="button" onclick="reset_select_box('#test');">Reset</button>
</body>
</html>
You could mark the newests options adding a particular data tag, i.e. data-toreset. Then, when you need to reset, remove only options with that tag.
The newest options:
<option data-toreset="1"></option>
The JQuery script could be like:
$('*[data-toreset="1"]').remove();
And then you could select the first element of your combo.
I am trying to select dropdown automatically based on values from another dropdown. Second dropdown will have more values than first one. If I select the first dropdown, then the second should be selected automatically. I tried the below code and getting error: Options is null or not an object. ???
<script type="text/javascript">
function showState(me){
var values = ''; //populate selected options
for (var i=0; i<me.options.length; i++)
if (me.options[i].selected)
values += me.options[i].value + ',';
values = values.substring(0, values.length-1);
var selected=[values];
var del = document.getElementById('data').value;
for(var i=0; i<del.options.length; i++);
{
if(values[i] == del.options[i])
{
del.options[i].selected;
}
}
}
</script>
<select multiple="multiple" onchange="showState(this);">
<option value="1">Test1</option>
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
<select name="data" id="data" multiple="multiple">
<option value="1">Test1</option>
<option value="2">Test2</option>
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
I think you should make some correction in your code as below :
<script type="text/javascript">
function showState(me){
var values = ''; //populate selected options
for (var i=0; i<me.length; i++)
if (me.options[i].selected)
values += me.options[i].value + ',';
values = values.substring(0, values.length-1);
var selected=[values];
var del = document.getElementById('data');
for(var i=0; i<del.length; i++)
{
for(var j=0;j<values.length;j++)
{
if(values[j] == del.options[i].value)
{
del.options[i].selected = true;
}
}
}
}
</script>
for more details on Select and Option objects in javascript you may refer this link !
I think your problem is here var del = document.getElementById('data').value;. If you want to access the select options, you should use var del = document.getElementById('data');, without the .value. This way the variable del should have the .options array.