Which <option> field is selected? With jQuery - javascript

I'm looking for a way to find out which field is selected with jQuery. I build a function, but it doesn't work.
HTML example
<select id="bewerbungID">
<option value="1" name="selectName">test1</option>
<option value="2" name="selectName">test2</option>
<option value="3" name="selectName">test3</option>
</select>
JS function
$('#bewerbungID select').on('change', function() {
alert($('option[name=selectName]:checked', '#bewerbsungID').val());
});
Tested in jsfiddle open link

Treat select as an input field such as text. Then it has to have a value selected - show new value whenever it changes. You logic was right but jQuery selectors got a bit confusing.
Simplified your code a bit:
$('#bewerbungID').on('change', function() {
alert($('#bewerbungID').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="bewerbungID">
<option value="1" name="selectName">test1</option>
<option value="2" name="selectName">test2</option>
<option value="3" name="selectName">test3</option>
</select>

The issue you are having is that you are not using the selector properly.
Basic Explanation:
The selector is everything you find within the parenthesis here: $('...'). When you use # in front of the word, that means you are selecting an element that has an id of whatever is to the right of #. In your case, ... is equal to #bewerbungID so the proper code should be as follows:
$('#bewerbungID').on('change', function() {
alert($('#bewerbungID').val());
});

$('#bewerbungID').on('change', function() {
alert($('#bewerbsungID option:selected').val());
});
It should do the trick

Related

Form select not saving in localStorage

I'm working on an HTML view for iAd Producer. I'm trying to add a list of sentences which have alternative words students can choose and to save those values to localStorage as they change and repopulate the selects with those values when the page is revisited.
I'm adapting some code I wrote which works fine to save multiple input boxes on a page. But I have strange behaviour when trying to use it with multiple selects. Basically, no matter which order the answers are completed in, only the last chosen value is being stored. When the page is revisited, the code attempts to put that value in each select. This, of course, fails for the two selects which do not have corresponding values.
I cannot see why this is happening and hope someone can spot the obvious. Thanks.
<div>
<script type="text/javascript">
var uniqueId = "FC2-U2-A-P29";
$(document).ready(function () {
function onStartup() {
$.each( $("select"), function() {
if (localStorage[$(this).attr("value")+uniqueId]) {
$(this).val(localStorage[$(this).attr("value")+uniqueId]);
}
});
}
onStartup();
});
$('.drop').change(function () {
localStorage[$(this).attr("value")+uniqueId] = $(this).val();
});
</script>
<form>
<label class="number">1.</label>
<label class="text">Breakfast is the </label>
<select name="select1" class="drop">
<option value="blank">Choose a word</option>
<option value="one1">one</option>
<option value="first1">first</option>
</select>
<label class="text"> meal of the day.</label>
<br>
<label class="number">2.</label>
<label class="text">I always eat </label>
<select name="select2" class="drop">
<option value="blank">Choose a word</option>
<option value="three2">three</option>
<option value="third2">third</option>
</select>
<label class="text"> meals a day.</label>
<br>
<label class="number">3.</label>
<label name="select3" class="text">My football team is in</label>
<select class="drop">
<option value="blank">Choose a word</option>
<option value="two3">two</option>
<option value="second3">second</option>
</select>
<label class="text"> place in the league.</label>
<br>
<button class="clearButton" onclick="clearAnswers()">Clear </button>
<script type="text/javascript">
function clearAnswers() {
$.each( $("select"), function() {
if (localStorage[$(this).attr("value")+uniqueId]) {
localStorage.removeItem($(this).attr("value")+uniqueId);
$(this).val("blank");
}
location.reload();
});
}
</script>
</form>
</div>
The probable reason for which this code fails in select is because of the following :
$.each( $("select"), function() {
if (localStorage[$(this).attr("value")+uniqueId]) { //select doesn't have any attribute value.
$(this).val(localStorage[$(this).attr("value")+uniqueId]);
}
});
Select tag doesn't have any value attribute. I think .val() is what you need here. If you look at the code, you are basically iterating on select tag and checking value attribute(which doesn't exist) of select. Try changing it to .val() and then try.
To save and load stuff from localstorage use:
localStorage.setItem(<key>, <value>);
and
localStorage.getItem(<key>);
There are multiple problems with your code.
The first one is that you should use .val() instead of .attr('value').
The second one is that the code to add the values in localStorage is executed before the DOM is created fully, so the selects dont exist yet. To overcome this you need to bind the change event on document.ready ( aka $(function() { }); ).
I've made a pastebin with the modified code: http://jsbin.com/jubijuyatu/2/
Your selector is invalid.
Change $(this).attr("value")+uniqueId with $("option:selected",this ).text()+uniqueId; in all occurrences.

Using && in jquery if condition under function

I am checking value on radio and select drop down using jquery. How can check both elements value in a if condition using jquery ? I tried this way but its not working for me:
$("#filterresult").click(function(){
if($('#filter_deductible').val()=="id_0" && $('#trip_type_filter_no').val()=="no")
{
//some code here
}
I know I can't use && in jquery code I have to use multiple selector but I don't know how to use it. Any suggestions please ?
Here is my html:
<select id="filter_deductible" name="filter_deductible">
<option value="">Select Deductible</option>
<option value="id_0">0 Only</option>
<option value="id_0_250">0-250</option>
<option value="id_250_1000">250-1000</option>
<option value="id_1001">1000 and Higher</option>
<option value="All Deductibles">All Deductibles</option>
</select>
AND
<input type="radio" id="trip_type_filter_no" name="trip_type_filter_no" value="no" /> No
Calling function using a button:
<input type="button" name="filterresult" id="filterresult" class="newquote" value="Filter Result" />
First radio buttons that should be linked should have the SAME name, you have different names. That means you can select both of them.
Second, the val() will always return the value. You want to check to see if it is selected.
if ($('#filter_deductible').val()=="id_0" && $('#trip_type_filter_no').is(":checked"))

Remove the first select option

I'd like to remove the first option of an select tag when I click on the select tag. Is this possible?
I don't want to see the first option after that click.
Thanks for any help.
You can remove the first option on click with jQuery.
$(document).on('click', 'select', function() {
$(this).find('option').get(0).remove();
});
This simply removes the first option of a select tag on click. You need to add an if statement to check if it was already removed.
There's also a simple no-javascript solution:
<select>
<option style="display: none">--Choose--</option>
<option>Cheese Cake</option>
<option>Hot Pockets</option>
<option>Sausage</option>
<option>Cookies</option>
<option>Bacon</option>
</select>
(Copied from the comments from #chipChocolate.py)
If you use bootstrap add placeholder attribute in your select.
If your not
<select required>
<option value="" disabled selected>Select your option</option>
<option value="1">1</option>
</select>
// to remove first...
document.getElementById("element_id_str").options[0].remove();
//to remove the lot...
document.getElementById("element_id_str").options.length = 0;
<select required>
<option value="" disabled selected hidden>Select your option</option>
<option value="1">1</option>
</select>
Probably you just want this:
<select required>
<option value="" hidden>Select your option</option>
<option value="1">1</option>
</select>
A very naive way of doing this:
$("#selector").change(function(evt) { //listen to changes of selection
var theElement = $(this);
if (!theElement.data("selected")) { //check if flag is not set
theElement.children("option")[0].remove(); //remove 1st child
theElement.data("selected", true); //set flag, so it doesn't continue removing items for every change
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selector">
<option>--Choose--</option>
<option>Apple</option>
<option>Banana</option>
<option>Papaya</option>
</select>
If you want to remove the first option use this
$(document).ready(function()
{
$("select").children().first().remove();
});
If you want to remove the first option after clicking on the select box use this
$(document).ready(function()
{
var removed=false;
$(document).on("click","select",function()
{
if(!removed)
{
$(this).children().first().remove();
removed=true;
}
});
});
Javascript:
document.getElementById("SelectId")[0].remove();
Get the first option in the select and remove it.
I had the same problem, but the solutions above just work with one form, not with many. I added some extra code in order to validate it for many in your form:
$(document).ready(function()
{
$(document).on("change","select",function()
{
var x = $(this).children().first().attr("name");
var n = x.localeCompare("todelete");
if (n == 0)
$(this).children().first().remove();
});
});
Where "todelete" is the name for all first elements [0] defined inside the
Please select value //all first elem must have the same name
"> //the others another name (can be the same BUT not "todelete")
You need the id or class to remove the item. While testing and debugging I found 'option:first' fails to remove the item. But 'option:first-of-type' always does the work. You can get more info about 'first-of-type' here :first-of-type
$("#ID_or_.CLASS option:first-of-type").remove();

Javascript producing a value into a form textbox on selection

Trying to figure out how I can produce text dynamically in a text box of a form using javascript.
I want to select a type of event from a dropdown list which I have made and on that selection a value be input in to the textbox of the form for eventprice.
So far this is what I have but I have no value being produced in the textbox any help appreciated.
function totalprice(){
if($('#type').val() == '3'){
$('#eventprice') == ("45");
}
}
<input type="text" disabled="" id="eventprice" onChange="totalprice();" name="eventprice" class="form-input" />
If you don't mind using jQuery, it is going to be a breeze: you'll simply need to add the data attribute price to every option. What this function does is:
Compares the value of all options to the value currently visible in the select box when the value is changed.
If the values are the same, copies the data-attribute to the other input.
Working demo: http://jsbin.com/acuyux/6/edit
The HTML
<select id="type">
<option data-price="25">Party</option>
<option data-price="35">Meeting</option>
<option data-price="45">Lounge</option>
</select>
<input type="text" id="eventprice" name="eventprice" disabled="" class="form-input" />
The JS
$('#type').change(function totalprice(){
$('option').each(function() {
if($(this).val() === $('#type').val()) {
$('#eventprice').val($(this).data('price'));
}
});
});
I would recommend using jQuery due to its efficient code.
HTML:
<input type="text" disabled id="eventprice" />
<select id="select">
<option data-cost="5">Event 1</option>
<option data-cost="10">Event 2</option>
</select>
jQuery:
$('#select').change(function () {
var str = $(this).find('option:selected').data('cost');
$('#eventprice').val(str);
});
// This code can be used to run it on load
// $('#select').trigger('change');
Code in action:
http://jsfiddle.net/LkaWn/
Hope this helps :)
Modify the 3rd/4th line of your code to be $('#eventprice').val("45"); as suggested, except that the suggestion had a syntax error.

How to select dropdown list using jQuery

I have the dropdown below. I want to populate orange in the dropdown when the page loads. I made a function, PopulateDropDown, which runs the jQuery code to do so, but it is not working.
<select name="cboFruits" id="cboFruits">
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Pine">Pine</option>
</select>
<script type="text/javascript" src ="jquery.js"></script>
<script>
function PopulateDropDown(pFruitName)
{
$('cboFruits :selected').val(pFruitName);
}
$(document).ready(function(){
PopulateDropDown('Orange');
});
</script>
Well, there are a few problems with your code:
$('cboFruits :selected').val(pFruitName);
First of all, you're missing the # in front of cboFruits, since cboFruits is the ID property of your select list.
Also the correct way of setting the selected option would be something like this:
function PopulateDropDown(pFruitName)
{
$('#cboFruits option:contains("'+pFruitName+'")').prop('selected', true);
}
$(document).ready(function(){
PopulateDropDown('Orange');
});​
Ref this question How do you select a particular option in a SELECT element in jQuery?
You forgot to write ** # ** and remove selected
$('#cboFruits').val(pFruitName);
EDIT :
or you use
<option value="Orange" selected="true">Orange</option>
when page by default 'Orange' will be selected
It should work:
function PopulateDropDown(pFruitName)
{
$('#cboFruits').val(pFruitName);
}

Categories

Resources