Load a selected option on a dynamically created `<select>`? - javascript

I have a web page that saves a bunch of options (from a <select>). I can store the values via PHP and MySQL just fine and restore the values of those selects.
The problem comes with dynamically created selects. Through logging to the console, I can confirm the HTML of the <select>s has loaded properly and they function properly on screen. But none of them load the stored value.
I’ve tried using:
$("#selectID").val(storedVariable);
$("#selectID").prop("selectedIndex", storedIndex);
$("#selectID option[value=" + storedVariable + "]").prop("selected", true);
None of these options work. And to make matters worse, I can use the console to check the .val() or .prop("selectedIndex") and they return the proper value, but the <option> displayed/selected drop-down option is blank (index 0).
Again, this is only on dynamically created selects, the ones hard-coded in work just fine.
here's the code I'm using:
file.html
<select id="select1">
<option value="choice1">Choice 1</option>
<option value="choice2">Choice 2</option>
</select>
<select id="select2"></select>
file.js
// selectedValue1 & selectedValue2 are sent from file.php
console.log(selectedValue1); // -> "choice2"
console.log(selectedValue2); // -> "choice2B"
// these work, I can verify them in the console
$("#select1").val(selectedValue1);
updateSelections();
$("#select2").val(selectedValue2);
function updateSelections() {
$("#select2").html(function() {
var optionChoices = "<option value='blank'> </option>";
if ("#select1".val() == "choice1") {
optionChoices += "<option value='choice1A'>Choice 1A</option>";
optionChoices += "<option value='choice1B'>Choice 1B</option>";
optionChoices += "<option value='choice1C'>Choice 1C</option>";
return optionChoices;
} else if ("#select1".val() == "choice2") {
optionChoices += "<option value='choice2A'>Choice 2A</option>";
optionChoices += "<option value='choice2B'>Choice 2B</option>";
optionChoices += "<option value='choice2C'>Choice 2C</option>";
}
return optionChoices;
}, 0);
}
Basically selectedValue1 loads perfectly, but selectedValue2 does not.
UPDATE: Here's the actual line of code from my app that should work.
console.log(fieldOfStudy);
$("#selectFieldOfStudy").val(fieldOfStudy);
console.log($("#selectFieldOfStudy").val());
The console.log() outputs the correct stored information both times, but the value is not displayed correctly on screen.

You have errors in your code.
Function updateSelections should be defined before being used
"#select1".val() : wrap "#select1" into $()
Also consider updating select2 each time the first select is modified:
$("#select1").on('change', updateSelections);
See the jsFiddle: https://jsfiddle.net/xpvt214o/613071/

Related

Keep auto created fields shown after reload

I have a javscript code that create fields based on select menus
HTML
<div class="container">
<div id="selected_form_code">
<select id="select_btn">
<option value="0">--How many rooms ?--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div id="form_submit">
<!-- Dynamic Registration Form Fields Creates Here -->
</div>
</div>
JS
function get_chambre_html(cn)
{
return "<div>"
+ "<b>Chambre " + cn + ":</b> "
+ "<br/>Adultes: <select id='adultes" + cn + "'>"
+ "<option value='0'>--How many adults ?--</option>"
+ "<option value='1'>1</option>"
+ "<option value='2'>2</option></select>"
+ "<br/>Enfants: <select id='enfants" + cn + "'>"
+ "<option value='0'>--How many enfants ?--</option>"
+ "<option value='1'>1</option>"
+ "<option value='2'>2</option><option value='3'>3</option><option value='4'>4</option></select>"
+ "<div id='ages" + cn + "'></div>" // empty block for further usage
+"</div>";
}
$(document).ready(function()
{
$('select#select_btn').change(function()
{
var sel_value = $('option:selected').val();
$("#form_submit").empty(); //Resetting Form
// Below Function Creates Input Fields Dynamically
create(sel_value);
// Appending Submit Button To Form
});
function create(sel_value)
{
for (var i = 1; i <= sel_value; i++)
{
$("div#form1").append($("#form_submit").append(get_chambre_html(i)));
$("div#form1").append($("#form_submit").append("<div id='ages"+i+"'/>"));
$('select#enfants'+i).change(function(){
var infants = this.value;
var i=this.id.substr(7); // 7 = strlen of 'enfants'
$('#ages'+i).empty();
for(var j=0; j<infants; j++)
$('#ages'+i).append("Age enfant "+(j+1)+" : <select><option>1 an</option><option>2 ans</option><option>3 ans</option></select>");
});
}
};
});
Is there any way to keep auto created fields shown after page reload ? Because, for now, if i reload the page for another search, this fields disappear.
Before/After search:
Fields values are sent by GET method.
There are many ways of doing this. I would write a cookie. A cookie is data written to the user's browser and will persist between requests. Cookies are a great way to store data and there are already API's in javascript to do so. You can write to the cookie by assigning to document.cookie. As your working with a form I would serialize an object that represents the current state of your form.
document.cookie = JSON.stringify({ destination: 'BERCELONE' });
When the page loads you can check your value
var currentFormState = JSON.parse(document.cookie);
functionThatBuildsTheFormFromObject(currentFormState);
Now that we know how to store a cookie we need to figure out what to store in the cookie. To do this I would write two functions. The first function lets call it functionThatBuildsTheFormFromObject() would accept an object. I would use the following object. Note here that for each adult and child we use a value in an array.
{
destination : "Berclona",
depatureDate : "30-08-2016",
adults : [],
children : [ 5, 8],
seniors : [ 55, 58 ]
}
With this object let's create the form
functionThatBuildsTheFormFromObject (theFormObject) {
createDestinationField(theFormObject.destination);
createDepatureDateField(theFormObject.depatureDate);
theFormObject.adults.forEach(adultAge => {
createSelectAgeField('adult', adultAge)
})
theFormObject.children.forEach(childAge => {
createSelectAgeField('child', childAge)
})
theFormObject.seniors.forEach(seniorAge => {
createSelectAgeField('senior', seniorAge)
})
}
So now all that is required is to white functions to create all the fields which in part you have already done. Going the other way I would define a function that will give you the current values of your form. Check this
Convert form data to JavaScript object with jQuery question as it does exactly what you need. I would call this function serializeForm(). I would also look at setting the cookie each time the form changed. That way when ever the user refreshes their browser the form should always be updated. You might also think about providing the user a reset form button too incase they want to start again.

Issue with getting selected value of select menu in query?

There is a select menu in my page which loads the values from DB. I am able to view the values in select menu. but while displaying the selected value, I am not able to display it properly. i.e. If the value contains any spaces it is not getting full value( EX: if I selected "Wilson Garden", I am getting only "Wilson". It is displaying "Wilson Garden" in select box, when I try to get that value by on change event I got only "Wilson",Same thing happen for all the values which has space in it.
my html is code is:
<select name="select-choice-1" id="select-choice-1">
<option value="Select Category">Select Category</select>
</select>
And my Jquery code is as follows,
$("#select-choice").on('change', function(event) {
alert( this.value );
console.log("Category is: " +this.value); // Here I am getting the value..
});
// Store the values dynamically in to select menu..
$(document).on("pagebeforeshow","#homePage",function(){
var db = window.sqlitePlugin.openDatabase({name: "MYDB"});
db.transaction(function (tx) {
tx.executeSql("select distinct Category from Locationlog;", [], function (tx, res) {
for (var i = 0; i < res.rows.length; i++) {
$("#select-choice").append('<option value='+res.rows.item(i).Category+'>'+res.rows.item(i).Category+'</option>');
}
$("#select-choice").listview('refresh');
});
});
});
It because you didn't quote the attribute. You need to wrap those values around double quotes.
var opt = '<option value="';
opt += res.rows.item(i).Category;
opt += '">';
opt += res.rows.item(i).Category;
opt += '</option>';
$("#select-choice").append(opt);

option onChange on currentpage using database information

I've written a query that takes the usernames from the database and puts them in s like this:
<?php
$username_set = get_all_usernames();
while ($username = mysql_fetch_array($username_set)){
echo "<option>" . $username['username'] . "" . "</option>";
}
?>
That works fine but now I want to add a onchange function to my tags. I've done it like this:
<select name="user_result" onChange="top.location.href = this.form.user_result.options[this.form.user_result.selectedIndex].value,'_self';">
That works fine too, it is redirecting to the selected option. But I want to select a option and stay at the same page and display the (coming) information that username contains. But for now printing the username below the would be good enough.
If you want to execute code on change of a select, it's easy to include this in a javascript function. Not sure if you want the javascript or the jquery solution, so I'll include them both.
Plain javascript:
function show_user(data) {
var el = document.getElementById("show_username").innerHTML = data;
}
jQuery solution:
function show_user(data) {
$("#show_username").html(data);
}
Then you call this function on the select change:
<select name="user_result" onchange="show_user(this.options[this.selectedIndex].value);">
<option>--select a user--</option>
<option>username</option>
<option>username 2</option>
</select>
<div id="show_username">this will update to the selected user name</div>
jsfiddle for plain javascript: http://jsfiddle.net/CwFs5/
jsfiddle for jquery: http://jsfiddle.net/5PuX3/

Pass contents of drop-down select list from one form to another in PHP

I have a PHP script that displays information from a MySQL database in a table format based on a normal form filled in by the user.
When the user clicks Search the script calls itself (Get method). The form is redisplayed and below it is the output table. The user can refine the search and try again if he wants.
After the output is displayed I also want the user to be able to change which fields in the database he wants displayed in the table, and do another search. I want to make it totally intuitive.
I could add a bunch of Select dropdowns to the form, but that is not very intuitive. Part of the problem is depending on the search values it produces two totally different displays from two different MySQL tables. So it would be very difficult to explain to the user which drop-down boxes to fill in depending on his other input.
The most intuitive method I can think of is to change the column headings in the output table from plain text to dropdown select boxes. The first time he does the search he would get the default output fields. He can then change any of the column heading dropdown boxes to a different field name from the table and then click Search on the form above to redisplay the table with different columns.
The problem is it really needs two forms, the search form at the top and another form embedded in the first line of the output table with the column heading dropdown boxes. But is that even possible? Can a form be embedded in a table or does it have to be the other way around?
Complicating things slightly is the fact that I use pagination as the output is generally too long to display on one page. So I display 500 lines at a time and provide page number and previous-next links for the next pages, like a Google search.
If I can sort that bit out I then envisage setting up an "onclick" or similar on each dropdown box that calls some javascript to insert the selected value into a hidden field in the first form. Problem is I have no idea how to do it. Any ideas on doing it that way or alternative ways of achieving what I want would be greatly appreciated.
For what it is worth, I currently call some javascript to submit the existing form:
<form action="'.$_SERVER['PHP_SELF'].'" method="GET" onsubmit="return SubmitForm(this);">
It does user-side form validation plus it remove all empty or default values from the search string. The simplest implementation would be if that code could go out to the second form and grab the column headings that have changed and add them to the parameter string that it builds. The existing JS code to format the $_GET search string URL is like this:
var elems = form.getElementsByTagName('input');
var default_values = new Array();
default_values['surname_type'] = 'starts';
default_values['firstname_type'] = 'starts';
default_values['spousename_type'] = 'starts';
default_values['remarks_type'] = 'contains';
default_values['cemname_type'] = 'starts';
default_values['seltype'] = 'all';
default_values['state'] = 'ALL';
var inputs = [];
var getstring = "";
// beautify $_GET querystring to remove blank fields
for(var i = 0; i < elems.length; i++) {
// add non-blank input fields to querystring and store field names so we can ignore changed radio buttons for blank fields
if(elems[i].type == "text" && elems[i].value != "") {
getstring += "&" + elems[i].name + "=" + encodeURIComponent(elems[i].value);
inputs[elems[i].name + "_type"] = "y"; // eg. surname_type = y if surname is present
}
// add changed radio buttons if the associated text field was present
if(elems[i].type == "radio" && elems[i].checked && elems[i].value != default_values[elems[i].name]) {
if (inputs[elems[i].name] || elems[i].name == "seltype")
getstring += "&" + elems[i].name + "=" + encodeURIComponent(elems[i].value);
}
}
// add state code if no other values input or if a specific state is selected
var state = document.getElementById('state');
if (state.value != "ALL" || getstring == "")
getstring += "&state=" + state.value;
var getstring = "?" + getstring.substring(1); // replace first & with ?
window.location.href = form.action + getstring; // submit form
return false; // tell form above not to re-submit it
So I guess what I am really looking for is some JS code to insert just before the second last line above. The pseudo code would be like this:
if (first-column-heading-dropdown-in-second-form != "name")
getstring += '&outputcolumn1=' + value-of-first-column-heading-dropdown-in-second-form;
if (second-column-heading-dropdown-in-second-form != "address")
getstring += '&outputcolumn2=' + value-of-second-column-heading-dropdown-in-second-form;
if (third-column-heading-dropdown-in-second-form != "state")
getstring += '&outputcolumn3=' + value-of-third-column-heading-dropdownin-second-form;
Heck, in trying to explain what I want I am slowly answering my own question. I can see that I can just use the ID of the dropdowns in the second form to extract the values to insert in the first form get string.
So now all that leaves is how to integrate a form into the column headings in the output table. If I wrap a form around the entire output table... Hmmm. It is starting to look do-able.
In trying to explain what I wanted I answered my own question. It works like a dream. I did not need to create a form for the drop-down column headers. I simply inserted them instead of the existing th /th headers. Not sure if it is valid HTML syntax but it works on all major browsers.
In the javascript I then grabbed the values from the dropdown selects using their ID and inserted them in the querystring I had built from the form. I gave the dropdowns a class and formatted them the same as the other column headings using CSS.
The code for the column headers looks like this. (It includes code to re-display the selected value when the script re-calls itself on form submission):
echo '<table><tr>
<th>Name</th>';
// Exit from previous echo and php to allow use of conditional echo statements below to select previously selected dropdown item
?>
<td><select id="col1" class="thdropdown" name="col1">
<option value="address" <?php if($col1=="address") { echo "selected"; }?>>Address</option>
<option value="alternate_name" <?php if($col1=="alternate_name") { echo "selected"; }?>>Alt Name</option>
<option value="town" <?php if($col1=="town") { echo "selected"; }?>>Town</option>
<option value="postcode" <?php if($col1=="postcode") { echo "selected"; }?>>Postcode</option>
<option value="latlong" <?php if($col1=="latlong") { echo "selected"; }?>>Lat/Long</option>
<option value="source" <?php if($col1=="source") { echo "selected"; }?>>Source</option>
</select>
</td>
<td><select id="col2" class="thdropdown" name="col2">
<option value="state" <?php if($col2=="state") { echo "selected"; }?>>State</option>
<option value="alternate_name" <?php if($col2=="alternate_name") { echo "selected"; }?>>Alt Name</option>
<option value="town" <?php if($col2=="town") { echo "selected"; }?>>Town</option>
<option value="postcode" <?php if($col2=="postcode") { echo "selected"; }?>>Postcode</option>
<option value="latlong" <?php if($col2=="latlong") { echo "selected"; }?>>Lat/Long</option>
<option value="source" <?php if($col2=="source") { echo "selected"; }?>>Source</option>
</select>
</td>
<?php
echo '<th>... other columns ...</th></tr>';
The CSS code looks like this:
th, .thdropdown {
font-weight: bold;
font-style: italic;
font-size: 11pt;
text-align: left;
vertical-align:top;
}
The Javascript code that I inserted as per the pseudo code above is as follows:
// add state code if no other values input or if a specific state is selected
var state = document.getElementById('state');
if (state.value != "ALL" || getstring == "")
getstring += "&state=" + state.value;
// add column headings from dropdown selects in output table
var col1 = document.getElementById('col1');
if (col1.value != "address")
getstring += "&col1=" + col1.value;
var col2 = document.getElementById('col2');
if (col2.value != "state")
getstring += "&col2=" + col2.value;
var getstring = "?" + getstring.substring(1); // replace first & with ?
window.location.href = form.action + getstring; // submit form
return false; // tell form above not to re-submit it
When I change the values and do a search the querystring now looks something like this:
http://mysite/index.php?state=NSW&col1=town&col2=lat/long

How do I avoid Null Pointer Exception?

I am working on a project in which I need to create a form with a dropdown field for category. And according to the category selected, I have to populate the second drop down called subcaste.
This I am achieving through AJAX.
I also wrote a method which will be called on change of the category to disable the sub caste dropdown box if the selected category is OPEN as:
if(str=="OPEN"||str=="open"){
document.form.subcaste.disabled=true;
}
But when I hit the submit button, i get a null pointer exception in the line:
subCaste = request.getParameter("subcaste");
in the servlet. (This line takes the value of the subcaste from the jsp page).
I have also done: <option value="none" selected="selected">Select</option>
in the drop down of the subcaste so that a default value is selected. But I still get a null pointer exception. I believe that after I disable the dropdown box, the value isnt available to the servlet at all.
The detailed code is:
JSP:
<td id='category'><select name='category' onchange="showSubCaste(this.value);">
<option value="none" selected="selected">Select</option>
<% for (i = 0; i < categorySize; i++) {%>
<% category = (String) categoryArr.get(i);%>
<option value=<%= category%>><%= category%></option>
<% }%>
</select>
</td>
<td >SubCaste</td>
<td id='subcaste'> <select name='subcaste'>
<option value="none">Select</option>
</select>
</td>
JavaScript:
function showSubCaste(str){
...
if(str=="OPEN"||str=="open"){
document.form.subcaste.disabled=true;
document.form.issuingAuthority.disabled=true;
}
else{
document.form.subcaste.disabled=false;
document.form.issuingAuthority.disabled=false;
var url="SubCasteController";
url +="?caste=" +str;
...}
After retrieving the values in a servlet and passing it to another JSP:
<%String buffer = "<select name='subcaste' onchange='subCasteChanged(this.value);'><option value='none' selected='selected'>Select SubCaste</option>";
for (int i = 0; i < sizeInfo; i++) {
subCaste = (String) retrievedInfo.get(i);
buffer = buffer + "<option value='" + subCaste + "'>" + subCaste + "</option>";
}
buffer = buffer + "</select>";
response.getWriter().println(buffer);
%>
I do not know how to proceed with this. Please help me.
Thank you in advance.
Yes , you are right . If the <select> is disabled , its values will not be POSTED. So when you get its value using request.getParameter() , it will return null pointer exception.
The standard practices to get a disabled <select> to post its value are
Add a hidden input field that will submit the same value and copy the value from the disabled <select> to this hidden field in the <form> 's onsubmit() event
or
Re-enable the disabled <select> in the <form> 's onsubmit() event
Or alternatively , as you believe the null pointer exception is because subCaste is set to null ,you can try to to set subCaste variable to some specific value if the subCaste parameters is null to see if it can be solved.
if ( request.getParameter("subcaste") != null){
subCaste = request.getParameter("subcaste");
}else{
subCaste = "xxxxx"; //set to a specific value according to your requirement.
}
Reference
HTML form readonly SELECT tag/input

Categories