I'm making a quiz application involving a select box. The user selects an option and when they press a button, it should check if the selected option is the correct answer by checking an array of values. I can't figure out how to get the selected value from the select box. I've tried to find information about this, but I only want to use JS, no JQuery. I tried using:
var item = document.getElementById("selections");
var selection = item.options[item.selectedIndex].value;
but I get a Type Error, saying that item.selectedIndex isn't defined. I'm confused because from what I found, selectedIndex is a default property of select tags? I've only worked with radio buttons before, using a for loop and checking every option to see which was checked, but I can't use that here. I don't know if it matters, but I'm doing this without a form tag, just linking a js function to an event listener on a button. Any help would be appreciated. Thanks!
Edit: Here is a fiddle of my code as per request: https://jsfiddle.net/jmf68ycu/
The part where the problem lies is in the submit() function in the first line.
Update: I found something online about the problem having to do with JS trying to call the element before the element is loaded, so I put the variables inside the function, which is only called when the button is pressed. The problem still persists (same error).
You use like this
var item = document.getElementById("selections").value;
you select value store item variable
this code use full for you. :)
You have a syntax error somewhere. your code looks right. you probably aren't getting the right id. your first line probably doesn't return the right select.
var e = document.getElementById("bla");
var str = e.options[e.selectedIndex].value;
alert(str);
<select id="bla">
<option value="val1">test1</option>
<option value="val2" selected="selected">test2</option>
<option value="val3">test3</option>
</select>
Related
I am trying to disable a textbox in SharePoint WSS3 and force a specific value (given by another JavaScript function) but I can't seem to find the right way of doing it. I have come across different issues. Let's say I have a normal single line text value named prova and another one named Description. Description is required, prova is not.
First Issue: If the field IS required, even if there is something in the textbox, SharePoint says otherwise and does not allow me to insert the entry.
$(document).ready(function(){
//var value = someFunction(...);
var value = "test";
$("input[title='Description']").attr("disabled", "disabled");
$("input[title='Description']").val(value);
});
Second Issue: If the field IS NOT required SharePoint doesn't say anything but it inserts a blank value instead of the one given.
$(document).ready(function(){
//var value = someFunction(...);
var value = "test";
$("input[title='prova']").attr("disabled", "disabled");
$("input[title='prova']").val(value);
});
I have a feeling that tells me that there is some kind of SharePoint JavaScript function somewhere that listens for KeyUp or something. I have really no idea what to do now...
EDIT: It looks like the problem is related to disabling the textbox, if I comment the line where I disable the textbox it works in both scenarios. Maybe if I catch the insert request I can re-enable the textbox before SharePoint do the actual post. No idea how to do it though...
Your problem really is related to disabling the textbox first. By default disabled textboxes are not contained in the POST request in IE.
See this post: Disabled form inputs do not appear in the request or this one: how to save data by disabled text box?
What you actually want to do is set the readonly attribute of the field, not disable it (readonly="readonly"). The problem with that is that the readonly state sometimes looks the same as the default state, so you also have to add some CSS to make it look greyed out.
I have a select box in my webpage to fill a formulary. I want to recover the info filled by the user other times in it exists.
All my fields are properly filled except select box.
This is my code in html related to selectbox:
<br>Gender: <select id="gender">
<option value="man">Man</option>
<option value="woman">Woman</option><br>
It is a simple webpage just with a formulary in it. There is not anything else. I am just trying it.
With this line:
$(document).on("pageinit", '#settings', function() {
document.forms[0].gender.value = userGender;
...
I am modifiying the value of that box for reading it in other parts of my webpage or send it to the database. And the value keept is the correct one, but, the displayed value is not propertly shown.
Do you know which property do I have to modify to change the displayed value?
According to your question the asnwer developerCK has provided is correct.
Anyway look this demo and give a feed back if any thing we missed.
$('#gender').val('woman');
If you are using jQuery, then you can change or select the value of select box through jQuery!
It is very easy. Use selector and val.
$('#gender').val(userGender);
Ok, first off this isn't to find a value of a select boxes selected option. But its along the lines there of. I have a function I am working on that will check to see if the value selected matches that of the one being compared to from somewhere else, where if the match is found it does one thing if not it does another. However. Due to a recent requirement. The original function breaks cause there is not the probability that the select wont even be touched prior to the need of function.
So Im trying to tell if theres anyway to check to see if the select in question has had anything chosen or not prior to it doing anything else. I'm thinking of the concept of checking for an empty array with length, but I'm not looking to see if the select is empty or not. I need to know if there is a selected value or not so I can act accordingly with that. Hope this makes sense.
I'm totally not sure if I get you right, but wouldn't this be enough:
if( $('option:selected').length ) {
// at least one option element was selected
}
Easiest way to find if a select has a selected value:
var selectedValue = $('#someSelect option:selected').val();
There will always be a selected option. Use:
var $val = $('select option:selected').val();
to capture the value. If no option is selected by the user, the first option will be selected by default. So check against that value. If no value is given to the first option, it will pass back the text of the option. See the following jsFiddle.
However, it is important to note that assuming the first option will always be chosen isn't full proof. Some browsers such as FireFox can cache the value of form elements. In order to ensure that the form element acts as expected use the autocomplete attribute like so:
<select name='something' autocomplete='off'>
See: FireFox Doc on Autocomplete
I want to be able to send all the selected values from a listbox as a hidden field using JQuery.
I was able to send/retrieve a single value on form submission.
If anyone can share some code snippet, that would help.
Thanks in Advance!
Well, it's not so clear what you are really asking for. There is no "multiple selection dropdownlist" in HTML. To have a multiselect you need to specify
<select id="foobar" multiple>
that will create a listbox where you may select multiple elements. Calling
var sel = $('#foobar').val();
will return an Array of selected items.
edit
To get the text from each option, use .map() or jQuery.map(). Example:
var sel = $('#foobar').children('option:selected').map(function(i,e){
return e.innerText;
}).get();
That will create an Array containing the text of all selected entrys.
There's absolutely no need to do like that. You was apparently using request.getParameter() instead of request.getParameterValues() and wondering why it returned only the first value.
Just fix your servlet code accordingly:
String[] selectedItems = request.getParameterValues("dropdownname");
No need for ugly JS/jQuery hacks to send them all as single parameter. In future questions, try to ask how to solve a problem instead of how to achieve a solution which may after all not be the right solution per se.
I have the following HTML containing a drop down list (single selection)
<script type="text/javascript">
$(document).ready(function () {
$("#garden").bind('change', function() {
alert("Changed");
});
});
</script>
<body>
<div id="content">
<select id="garden">
<option value="flowers">Flowers</option>
<option value="shrubs">Shrubs</option>
<option value="trees">Trees</option>
<option value="bushes">Bushes</option>
</select>
</div>
</body>
</html>
When the HTML page is rendered, Flowers is the already selected element in the drop-down by default (being the first one). If I select any other value (other than "Flowers"), the Javascript function is fired and a alert box containing "Changed" is shown.
Q1: But, in case I re-select Flowers again, the onchange event is not triggered. I understand it is because nothing was 'changed' in the drop-down list. Is there a way a function is triggered even when no change to the already selected value in drop-down is done?
Q2: How to extract the value of the element which has just been selected (even if nothing new was selected - that is, user clicked on the drop down, and simply clicked somewhere else).
I have already tried the onblur but that requires that the user clicks somewhere else on the document so that the drop-down loses focus. Any help would be really appreciated.
[I have edited out the HTML headers and other script inclusions in the code snippet provided for brevity.]
Well I think I don't get you 100%, but some things I can suggest here are:
bind a click event handler to the select
$("#garden").bind('click', function() {
alert($(this).find('option:selected').text());
});
bind a focusout event handler
$("#garden").bind('focusout', function() {
alert($(this).find('option:selected').text());
});
and of course bind the change event handler which you already got. The click event handler might be a little bit tricky since it would fire every time you click on the element. But if you don't alert() it every time it should not be a problem at all, you got the current selection and can do with it whatever you want.
You can manually trigger the event when you load the page:
$(document).ready(function() {
$("#garden").bind("change", function() {
// ...
}).change();
});
This will pick up the initial value - so I think it makes your second question irrelevant. This won't work in all situations (I'm hoping that your actual handler isn't an alert but actually something useful!), but could come in handy...
Are you sure that whatever you are doing is the most sensible way to do things? It seems like very strange UI to have different behaviour if you select an item by leaving it as the default compared to selecting it by opening up the select and selecting the currently selected item.
If you are wanting to make them explicitly choose flowers then maybe you want a dummy entry at the top that says "Please choose one" that will then mean they are forced to actually change to flowers if that is what they want. It would probably be simpler than complicating your code with more event handlers and such like.
If you do really need to go down the path you are following then you may want to consider what the behaviour is if somebody just tabs to the control and then past it. ie should that fire your script off as well?
Edit to respond to comment at length:
What you will want to do in this case is hook into the onSubmit handler of the form. This is called, as you can imagine, when the form submits. If your handler returns false that form will not be submitted.
This handler is traditionally where you would do client side validation by examining the state of whatever form elements you care about and checking their values are valid. In this case you'd check if the value of garden was "N/A" or whatever you set it to and if so pop up an alert (in the simplest case) and possibly mark whichever fields need attention. Then the user will choose a valid entry (hopefully) and next time he submits your validation will succeed, you return true in the handler and the user can be happy he submitted valid input.
As always though the standard disclaimer that any data can be sent to your server by a determined user so you should not assume that just becasue you had this validation that you are getting valid data on the server. :)
Question 1: I think the event for that would be "onSelect".
Question 2: I think the "onSelect" event would work for that as well, not 100% sure. Something to try at least and mess with.
To my opinion, the easiest solution is to duplicate the first option into a disabled and hidden element having the same label. Your dropdown list will display the label of the hidden option, but thus won't be displayed in the list.
<select id="garden" name="blabla" onchange="this.form.submit();" >
<option value="" disabled selected style="display:none;">Flowers</option>
<option value="flowers" >Flowers</option>
<option value="shrubs" >Schrubs</option>
<option value="trees" >Trees</option>
<option value="bushes" >Bushes</option>
</select>
Your question seems same as HTML SELECT - Trigger JavaScript ONCHANGE event even when the option is not changed
and the solution mentionned above was provided by Simon Aronsson.
Nota bene : the solution works perfectly with Firefox, but not with Internet Explorer.