Cannot fetch the selected value in a drop down box using JavaScript - javascript

In this thread, it is described how you can fetch the selected value from a drop down box using JavaScript. I've been trying to follow the instructions in that thread, but haven't been able to get it working.
Here's a minimal (non-working) example of what I'm trying to do. The code should print the value of the second option from the drop down box, but instead I get the following error in the Chrome's JavaScript console Uncaught TypeError: Cannot read property 'options' of null on row 11 (that is, when I define my second variable).
<html>
<body>
<select name='a_drop_down_box'>
<option value='1'>One</option>
<option value='2' selected='selected'>Two</option>
<option value='3'>Three</option>
</select>
<p id='message'></p>
<script type="text/javascript">
var test = document.getElementById("a_drop_down_box");
var testValue = test.options[test.selectedIndex].value;
document.getElementById('message').innerHTML=testValue;
</script>
</body>
</html>

document.getElementById("a_drop_down_box");
Did you notice that you haven't defined an id for the select item?
The name attribute is used to identify the form element for requests send using the form. You should use an id to retrieve it from the dom.
Alternatively if your select resides inside a form, you could use this:
document.getElementById("myForm").elements["a_drop_down_box"];

You forgot to give your <select> an id attribute.
<html>
<body>
<select id='a_drop_down_box' name='a_drop_down_box'>
<option value='1'>One</option>
<option value='2' selected='selected'>Two</option>
<option value='3'>Three</option>
</select>
<p id='message'></p>
<script type="text/javascript">
var test = document.getElementById("a_drop_down_box");
var testValue = test.options[test.selectedIndex].value;
document.getElementById('message').innerHTML=testValue;
</script>
</body>
</html>

The dropdown's name attribute is "a_drop_down_box" - you're calling it as thought this was its id.
Any time you get an '...of undefined' error it means the object (or element, in your case) you think you're working on has not been found. So always confirm this before wondering why errors are happening. In your case, you could have done:
alert(test); //undefined - no element found with that ID

You forgot to add id to your select tag
var e = document.getElementById("a_drop_down_box");
var strUser = e.options[e.selectedIndex].value;
Will return 2. If you want Two, then do this:
var e = document.getElementById("a_drop_down_box");
var strUser = e.options[e.selectedIndex].text;
Here is a simple example
http://jsfiddle.net/VCerV/3/

Related

jQuery redirect based on two drop downs

I am having some issues with a search form I created based on two drop downs. Pretty simple but, I cant seem to find the issue. I'm still pretty green at this.
Here is the html:
<form id="CustomSearch">
<select id="Location">
<option value='northeast'>North East</option>
<option value='west'>West</option>
<option value='midwest'>Mid West</option>
<option value='south'>South</option>
</select>
<select id="Style">
<option value='industrial'>Industrial</option>
<option value='farmhouse'>Farmhouse</option>
<option value='contemporary'>Contemporary</option>
<option value='beach+style'>Beach Style</option>
<option value='traditional'>Tradtional</option>
</select>
<button id="DropSearch">
Here is the js:
var location = jQuery('#Location').val();
var style = jQuery('#Style').val();
jQuery(document).ready(function(){
jQuery('#DropSearch').click(function (e){
jQuery.post('http://showroomworldwide.com/?geodir_search=1&stype=gd_place&s=' + location + '&stype=gd_place&s=' + style);
});
});
Once the script is added to the footer of the site, I get a never ending loop, almost like if the function was firing before actually clicking on the button.
There's no need from what I can see to be doing a POST request - just set window.location.href also wrapping your jQuery in an IIFE and passing $ as an argument can be a handy way of making $ available to you if you need to use jQuery in noconflict mode.
Finally as #ADyson mentions you need to set retrieve location and style within the event handler otherwise you'll be stuck with the initial values.
(function($){
$(document).ready(function(){
var location = $('#Location').val();
var style = $('#Style').val();
$('#DropSearch').click(function (e){
window.location.href = 'http://showroomworldwide.com/?geodir_search=1&stype=gd_place&s=' + location + '&stype=gd_place&s=' + style; // Can't just reference location.href due to local variable
});
});
}(jQuery));

Can the value obtained by dijit.byId('').value be compared to a String?

I am relatively new to Spring MVC and Dojo/Dijit widgets and I am stuck with a problem. I need to unblock a particular div based on the option selected from the dropdown i.e. when the user selects the reason as "Unexperienced" I am supposed to unblock a div with id = "unexpUser" style="display:none;" to collect some additional information.
JSP -
<select data-dojo-type="dijit.form.Select" name="userReason" id = "reason">
<option value="opt0">Experienced</option>
<option value="opt1">Not experienced</option>
</select>
JC -
<script>
if(dijit.byId('reason').value == "opt1"){
unexpUser.style.display = 'block';
}
</script>
When the page loads, the option displayed on the dropdown is "Experienced". When I change the option to "Not experienced" , I need to unblock the div but this particular code doesn't seem to be the right code for comparing. Please help.
.value is not the right way to get value from a dijit widget instead use:
dijit.byId('reason').get("value")
Use onchange listener :
dijit.byId('reason').on("change",function(evt){
alert(evt); //(evt == value of option )
// your code here
});
okay I got my mistake. This is the solution. #Harpreet Singh your solution works perfectly with this code.
JSP-
<form:select data-dojo-type="dijit.form.Select" path "" name="userReason" id = "reason" onchange="myFunction1();">
<option value="opt0">Experienced</option>
<option value="opt1">Not experienced</option>
</form:select>
and in my JS I created a function for the String comparison.
JS -
<script>
function myFunction1(){
if(dijit.byId('reason').get("value") == "opt1"){
unexpUser.style.display = 'block';
}
</script>
this works. Thank you so much for your help!

jquery If selector changes reset or clear text input field issue

So, I want certain fields to reset or clear whenever the previous selector changes. I can get select tags to go back to the default option but can't get text input fields to clear out.
Here is the jsfiddle to give you an idea of what I'm talking about: http://jsfiddle.net/wsk3opbf/
Below is my code:
HTML
<select id="type">
<option>--Select--</option>
<option>45ppm</option>
<option>55ppm</option>
</select>
<input id="testone" type="text">
</input>
<select name="mediumcopier" id="mediumcopier">
<option value="">--Select--</option>
<option value="">no</option>
<option value="onecopier">yes</option>
</select>
<select name="largecopier" id="largecopier">
<option value="">--Select--</option>
<option value="">no</option>
<option value="onecopier">yes</option>
</select>
jquery
$('#type').change(function(){
$('#smallcopier, #mediumcopier').prop('selectedIndex',0);
$('#testone'.val() = '');
});
You don't have anything with an id smallcopier, and the set for testone was incorrect, try
$('#type').change(function(){
$('#mediumcopier, #largecopier').prop('selectedIndex',0);
$('#testone').val('');
});
You provide new value as an parameter/argument to the val() function like below
$('#type').change(function(){
$('#smallcopier, #mediumcopier').prop('selectedIndex',0);
$('#testone').val('');
});
Actually, .val() just returns a value that you can store into a variable.
If you want to change the actual value of the selector, you have to pass it as a parameter.
$('#testone').val('');
It should be
$('#testone').val('') ;
not you can't assign like this
$('#testone').val = '';
because val is method or function of jQuery object where parameters are passed as ('') or ('any value'), it's not variable to assign
Your code:
$('#testone'.val() = '');
Can't work, this is a syntax error; you have a misplaced ), it should be – syntactically, but still 'broken' – as follows:
$('#testone').val() = '';
This, however, will give an error of Invalid left side in assignment (or similar) because you're trying to assign an empty string to another string. What I suspect you want is:
$('#testone').val('');
Which will set the value of the #testone element to the empty string, or, possibly, to set the <input> back to the default value:
$('#testone').val(function () {
return this.defaultValue;
});

PHP Javascript cant access echoed element id outside php mode

Humble appologies if this is a stupid question but I cant for the life of me figure out what is wrong here.
I have an echoed element inside php mode:
echo'<select name="picks" id="winner">';
echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
echo'</select>';
Now outside php
I try to do a basic javascript GET:
document.getElementById("winner");
However the elemnt is not accessible am I missing something here, is it not possible to get echoed elements Ids?
You should make sure your DOM has at least loaded before performing element selects. If you can use jQuery, then this is as easy as the following, and you can place this script in the head section, or anywhere in the body:
$(document).ready(function() {
// Perform any selects on the DOM
});
JS
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
// The DOM is loaded and ready to be selected
var select = document.getElementById("winner");
var optionText = select.options[select.selectedIndex].text;
var optionValue = select.options[select.selectedIndex].value;
});
</script>
Of course you can also perform DOM selects using jQuery:
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
// The DOM is loaded and ready to be selected
var optionText = $("#winner option:selected").text();
var optionValue = $("#winner option:selected").val();
});
</script>
Another possibility
If $row, $team1 or $team2 are not defined and you have PHP errors and notices turned on, then the HTML will render like so:
<select name="picks" id="winner"><b>E_NOTICE : </b> type 8 -- Undefined variable: row -- at line 4<br /><b>E_NOTICE : </b> type 8 -- Undefined variable: team1 -- at line 4<br />
<option value=""></option><b>E_NOTICE : </b> type 8 -- Undefined variable: row -- at line 5<br /><b>E_NOTICE : </b> type 8 -- Undefined variable: team2 -- at line 5<br />
<option value="" selected="selected"></option>
</select>
However, if you have PHP errors and warnings turned off, you would see something like this instead:
<select name="picks" id="winner">
<option value=""></option>
<option value="" selected></option>
</select>
If you are unable to access the value of options in your select HTML (because they are empty), this would be a good pace to start investigating.
Using JQUERY you can try following:
// I have used mouse down event for demo purpose.
$(document).delegate('#winner', 'mousedown', function ()
{
alert('hi');
});
Try accessing the value of the selected id
I am giving a demo fiddle
Demo fiddle
document.getElementById("winner").value;
Echoing JS codes is common but there are these possibilities:
1-You put document.getElementById("winner"); before php creating that element.
2-There is a syntax error in script tag which cause error and there for your select does not work.
since the php part will be available before page load you can simply do like this:
<?php
$row['team1']=1;$team1='India';$row['team2']=2; $team2='SA';
echo'<select name="picks" id="winner">';
echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
echo'</select>';
?>
<script>
console.log(document.getElementById("winner"));//see this in console.
</script>

Passing variable to a PHP page with Spaces

I have a select element as shown below.I am passing the value of the selected option to a PHP page as a variable with javascript as shown below :
<script>
var area1=document.getElementById("area").value;
$("#list").load("selectcity.php?city1="+city1+"&area1="+area1);
<script>
<select id="areas" name="areas">
<option value="Queens Town">Queens Town</option>
<option value="QueensTown">QueensTown</option>
</select>
Now the thing is , In the PHP page I am able to echo $_GET['area1']; when QueensTown is selected but whenever I am trying to pass Queens Town ,its now working.Can anybody help.
You have to escape the values properly, otherwise you would end up with a URL like this:
selectcity.php?city1=xyz&area1=Queens Town
Which is unlikely to work the way you want. Use this instead:
var data = {
city1: city1,
area1: $('#areas').val()
};
$('#list').load('selectcity.php?' + $.param(data));
See also: jQuery.param()

Categories

Resources