How do I avoid Null Pointer Exception? - javascript

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

Related

How to keep html selected option from POST data after submit?

I have an HTML select with default value and I would like to keep Data on this select, if nothing was selected before, I would like to keep the first value like this :
HTML Side :
<select id="gender" name="gender" class="form-control" required>
<option selected disabled>Gender</option>
<option value="1">Male</option>
<option value="2">Female</option> </select>
PHP Side :
$_SESSION['post'] = $_POST;
// I first protected the data with html_entities
$_SESSION['post']['gender']=$this->_dataProtected['gender'];
// I redirect just for test (it works well with other values from input)
header('Location: ?page=children&action=add');
exit();
Javascript side :
$(window).on('load',function (){
var idGender = document.getElementById('gender').value = "<?php echo $_POST['gender'] ?? " + $('#gender').val($('#gender option:first').val()) + " ?>";
});
Thank you for your help
The result after submit the form : it fill my select with null value in the case I haven't choose an option and the same when I chose an option.
You cannot get a value passed back from an disabled option. Since the selection is required, instead check if the returned value is NULL, then you know that nothing else was selected.
Example:
If (is_null($_SESSION['post']['gender'])) {
$_SESSION['post']['gender'] = 'Gender';
}
With this if/else, you're changing the variable to Gender (The selected disabled option) if the disabled option is "selected".
Thanks you #Stoff,
After adding a value="" to option selected, I changed the Javavscript to this :
var idGender = document.getElementById('gender').value = "<?php echo
$_SESSION['post']['gender'] ?? '' ?>";
And now, its works :D

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

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/

how do we set the default return value of select box to null in jquery

If the selectbox is not selected then it will return null value, how does it possible?
I have tried this code:
<select name="city" id="city" style="width:238px;height:40px;"><option value= NULL >Select City</option>#foreach($cityName as $city)<option value="{{$city->id}}"> {{$city->name}}</option>#endforeach</select>
You can't.
jQuery will always get a string when it tries to read the value of a select element.
The closest you could come would be to use an empty string (value="") or to test explicitly in JS:
var my_value = jQuery('select').val();
my_value = (my_value === "NULL") ? null : my_value;
really simple ,I think it's just about html ,
<option value="" selected="selected"> ---- </option>
use this as a default selected item , and change the received value from "" to null in javascript if you want .

Select tag php generated code requires javascript interaction

Currently I am working on a piece of javascript to copy a link plus the option the user has selected within the select tag.
The variable I assign in the javascript remains undefined. Is there a way to make this code work? I do not wish to use the ID attribute with a loop unless this can be applied into my PHP script (in which I echo the select tags, because I'm showing database results, whenever a result is shown, it will also show a select tag). This link shows a simple example of what I made so far: http://jsfiddle.net/b31au78v/
Here is my code:
<table>
<tr>
<th>Name</th>
<th>Gender</th>
</tr>
<tr>
<td>Hank</td>
<td>
<select onChange="getValue()" class="ddlEval">
<option>Select an option...</option>
<option val="gender.php?=male">Male</option>
<option val="gender.php?=female">Female</option>
</select>
</td>
</tr>
<tr>
<td>Jeff</td>
<td>
<select onChange="getValue()" class="ddleval">
<option>Select an option...</option>
<option val="gender.php?=male">Male</option>
<option val="gender.php?=female">Female</option>
</select>
</td>
</tr>
</table>
<script>
function getValue() {
optVal = this.value;
if(optVal != "Select an option...")
{
window.prompt("This is the link that's going to be coppied: ", "localhost:8080/" + optVal);
}
}
</script>
I guess I need to replace "this" with something else, but it is only to show what I actually want to happen.
Consider the following approach:
var optVal = selectTag.options[selectTag.selectedIndex].value;
In your case (jsFiddle):
<script>
function getValue(s) {
optVal = s.options[s.selectedIndex].value;
if(optVal != "Select an option...")
{
window.prompt("This is: ", "localhost:8080/gender.php?=" + optVal);
}
}
</script>
While changing the onChange event code:
<select onChange="getValue(this)"...
Please notice that you should also pass the id/name of the member,
so when someone changes the first member's gender it won't conflict with the second one.
There are two issues here:
There's no attribute val it should be value:
<option value="none">Select an option …</option>
<option value="gender.php?=male">Male</option>
Note: If you don't have an attribute value the value of the element will be the text of the option-element selected instead.
this in your function has a different scope, so it's not aware of a property called this.value. You can however pass the element into the function, like:
<select onchange="getValue(this);"></select>
Then you can get its value like:
function getValue(e) {
var optVal = e.value;
if ('none' != optVal) {
window.prompt("This is the link that's going to be coppied: ", "localhost:8080/" + optVal);
}
}
Demo
Try before buy

Check if dropdown's selected option is not the first with JavaScript

Below are the options that I have in my HTML code:
<label id="subn">
<select name="subs" id="subs">
<option value="nothing">Choose a Subject</option>
<option value="General Question">General Question</option>
<option value="MemberShip Area">MemberShip Area</option>
<option value="Others">Others</option>
</select>
</label>
I want to create JavaScript code that will check whether the user selected an option other than the first one.
Here is what I tried:
if (document.getElementsByTagName('option') == "nothing"){
document.getElementById("subn").innerHTML = "Subject is Required!";
document.getElementById("subs").focus();
return false;
}
You can check like this if nothing is the first option (usually the case in my experience):
if (document.getElementById('subs').selectedIndex == 0){
To still compare based on the value, do this:
var sel = document.getElementById('subs');
if (sel.options[sel.selectedIndex].value == 'nothing') {
You may want to change your markup so the label is beside, like this:
<select name="subs" id="subs"></select><label id="subn" for="subs"></label>
Otherwise this part: .innerHTML = "Subject is Required!"; will erase your <select> :)
This should do it:
var index = document.your_form_name.subs.selectedIndex;
var value = document.your_form_name.subs.options[index].value;
if (value === "nothing"){
// your further code here.........
}
document.getElementsByTagName('option') gives a collection of all option elements in the document and "nothing" is a string. Comparing a collection to a string is quite useless.
Also setting document.getElementById("subn").innerHTML = "Subject is Required!"; will delete the select element, so document.getElementById("subs") wouldn't find anything any more.
If you just need to know if anything is selected check the selectedIndex property of the select element:
if (document.getElementById("subs").selectedIndex <= 0) {
// nothing is selected
}
EDIT: Changed > 0 to <= 0. I would assume that it should be checked if the user didn't select anything, too.

Categories