Display last selected item in dropdown box in JS - javascript

I need my selection box to display the last selected item from db after user submits form in JS. Below is my code. The JS correctly shows the options from db. After submission the selection box reverts back to the first item and not selected.
$(document).ready(function () {
$.getJSON("getCompany.php", success = function(data)
{
var options = "Select Company";
for(var i = 0; i < data.length; i++)
{
options += "<option value='" + data[i].Value + "'>" + data[i].Company + "</option>";
}
$("#slctCom").append(options);
$("#slctCom").change();
});
});

Related

javascript/php won't load data for first option in dependent dropdown

I'm having a problem with a script that is part borrowed and part my own, it is javascript and php that populates two dropdown lists, with options in the second being dependent on what the user selects in the first. For some reason, it won't load the options in the second dropdown when the initial option is selected in the first, either on page load or if it is selected manually (if the options were 'a, b, c, d, e...etc', it won't load anything for 'a').
I think it might be something to do with the javascript document ready function, but I'm afraid I know very little about javascript. This is the javascript code:
$(document).ready(function () {
$.getJSON("getOutcome.php", success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctOutcome").append(options);
$("#slctProxy").change();
});
$("#slctOutcome").change(function()
{
$.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctProxy").html("");
$("#slctProxy").append(options);
});
});
});
Change event is only fired, when selection is changed - not when filled ;-)
Try adding $("#slctOutcome").trigger("change"); at pre-last line
Have fun :-)
Try the below. Second function wasn't being called in first function.
$(document).ready(function () {
$.getJSON("getOutcome.php", success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctOutcome").append(options);
$("#slctOutcome").change(); //<-Here
});
$("#slctOutcome").change(function()
{
$.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctProxy").html("");
$("#slctProxy").append(options);
});
});
});

dynamic dropdown list with jquery and sqlite show incorrectly

i try to use SQLite with to create dynamic dropdown list.
my sql tabels are COUNTRY, COUNTRY_DISTRICT and DISTRICT.
COUNTRY tabel have c1 and c2.
DISTRICT table have d1,d2,d3,d4.
COUNTRY_DISTRICT gave a pair (c1,d1),(c1,d2),(c1,d3) and (c2,d4).
now i select c1 in country dropdown and d1 in district dropdown.
after that i change selection in country to c2.
my district dropdown still show as d1 but i wan is to be empty string.
Thank
$(document).ready(function () {
$("#country").change(function () {
Country = $(this).val();
$('#district option:eq(0)').attr('selected','selected');
db.transaction(ChangeCountry, errorCB, sucessCB);
});
});
function ChangeCountry(tx) {
tx.executeSql('SELECT d.* FROM COUNTRY_DISTRICT as cd , DISTRICT as d WHERE cd.country=? and cd.district = d.district', [Country], renderDistrictList, errorCB);
}
function renderDistrictList(tx, results) {
var len = results.rows.length;
var htmlstring = "<option value=\"\" > </option>";
for (var i = 0; i < len; i++) {
htmlstring += "<option value=\"" + results.rows.item(i).district + "\">" + results.rows.item(i).district + "</option>";
}
$('#district').empty().append(htmlstring);
}

Get the values of All checkboxes using Javascript

When a button is clicked a new category is added to the database and also displayed on the same page as well.But my problem is that when I click multiple times on button it adds multiple checkboxes for same checkbox value. I made it to insert into database only if it is not already present. My issue is that when i click on button it should add the category if it not present in database. I have two function
add_cat(); javascript function which calls ajax for adding the new category to the database.
is php function which is used for creating new page.
I did that when displaying checkboxes on page i used name= cats[] like array for all checkboxes like
<input type="checkbox" name="cats[]" id="<?php echo $row{'term_id'};?>" value="<?php echo $row{'name'};?>"> <?php echo $row{'name'}; ?> `
In add_cat() function i am using this code
var val = document.getElementById('cat_name').value;
var checkboxes = document.getElementsByName('cats');
var flag = 0;
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i] == val) {
flag = 1;
}
alert(flag);
} //check the duplicates
if (flag == 1) {
alert(flag);
document.getElementById('error').innerHTML = "Already exists";
setTimeout(function() { // to show the Error
$('#error').fadeIn("fast").delay(500).fadeOut("slow");
}, 1500);
flag = 0;
} else {
var div = document.getElementById('divContainer');
div.innerHTML = div.innerHTML + "<input id='chk_" + idCounter + "' type='checkbox' checked value='" + val + "' /><label for='chk_" + idCounter + "'>" + val + "</label>";
idCounter++;
cat_2_db(val); // call ajax to insert category in database
}
But problem is that flag never get turned into 1 and checkboxes variable is not returning checkbox values
you missed to find the value:
if (checkboxes[i].value === val) {
Refactoring your for loop
for(var i = 0, i < checkboxes.length; i++) {
if (checkboxes[i].value === val) {
flag = 1;
}
}

Using Jquery val() on a dropdown list

Among other things I am trying to alert the selected value in the 'Amount' drop down box which is a list of numbers from 1 to 10. The list is generated and then inserted in to a div.
// generate the amount dropdown list
var dropdown = "<select name=\"amount\">";
for(var i=1; i <= MAX_PRINT; i++) {
dropdown = dropdown + "<option>" + i + "</option>"
}
dropdown = dropdown + "</select>";
jQuery("#" + divId).html("<div>Amount: " + dropdown + "</div></div>");
var amount = 1;
jQuery(document).ready(function() {
amount = jQuery("#amount").val();
alert(amount);
});
My question is: Why does it produce 'undefined' when I alert the amount? I am expecting it to return the selected number
Make sure you give your select an id—right now it just has a name. As a result, your jQuery('#amount') selector is not returning anything, which is why the alert is showing
undefined.
var dropdown = "<select id='amount' name='amount'>";
you are using amount = jQuery("#amount").val(); for that you have to give your dropdown an id
var dropdown = "<select name=\"amount\" id=\"amount\">";
DEMO
there are 2-3 Approach to get a selected value from <select>
use :selected
use .prop
use .attr
use this if this works for you:
jQuery(document).ready(function() {
var amount = jQuery("select[name='amount']").val();
alert(amount);
});
The id is missing on your dropdown.
// Generate the amount dropdown list
var dropdown = "<select id="amount" name=\"amount\">";
for(var i=1; i <= MAX_PRINT; i++) {
dropdown = dropdown + "<option>" + i + "</option>"
}
dropdown = dropdown + "</select>";
jQuery("#" + divId).html("<div>Amount: " + dropdown + "</div>/div>");
var amount = 1;
jQuery(document).ready(function() {
amount = jQuery("#amount").val();
alert(amount);
});

display my dropdown box in a specific area

Ok here's what I am doing. Based on some dropdown value I am craeting another dropdown value.
Is it possible to display that dropdown in some specific area as I wish based on my existing code.
if (SelectedIndex == 2 || SelectedIndex == 5 || SelectedIndex == 7) {
$("#DomContainer").remove();
var MainContainer = document.createElement("Div");
MainContainer.id = "DomContainer";
$("body").append(MainContainer);
var Options = new Array();
for(var i=1;i<=28;i++){
Options.push(i);
}
AddDropDown(Options);
}
function AddDropDown(Options) {
var selectHTML = "<label>Day:</label> ";
selectHTML += "<select>";
for (i = 0; i < Options.length; i = i + 1) {
selectHTML += "<option value='" + Options[i] + "'>" + Options[i] + "</option>";
}
selectHTML += "</select>";
document.getElementById("DomContainer").innerHTML = selectHTML;
}
For example <div id="new_drop">//Display the drop down here </div>
Simply add a second parameter to AddDropDown for passing the ID of the container to which you want to insert your dropdown list:
function AddDropDown(Options, containerId) {
...
document.getElementById(containerId).innerHTML = selectHTML;
Then call it like this:
AddDropDown(Options, "new_drop");
(if I understand you correctly)
No need to remove and append elements from the DOM, just replace the existing element contents ... here's a simplified version.
// if "SelectedIndex" is one of the values in the array provided
if ($.inArray(SelectedIndex, [2,5,7])) {
$("#DomContainer").html("<label>Day:</label> "+inject_dropdown(28));
}
// Creates and returns a new drop-down based on the "length" provided
function inject_dropdown(length){
var selectHTML = "<select>";
for( i=1; i<=length; i++ ){
selectHTML += "<option value='" + i + "'>" + i + "</option>"
}
selectHTML += "</select>"
return selectHTML;
}
Replace the $('#DomContainer') selector with whatever selector identifies the place you want the new drop-down to appear.

Categories