Form select not saving in localStorage - javascript

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.

Related

Which <option> field is selected? With jQuery

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

Database value cannot get it to the Dropdownlist jQuery

In my database there's a column, name is Sequence & it consist of numbers(int). In my application's edit function I need to show that selected number in my jQuery dropdown list.
In my AJAX call I sent ProductId and get the specific row.
Html Control
<select class="form-control" id="drpsequence"></select>
My jQuery dropdown
$("#drpsequence option:selected").append($("<option></option>").val(msg._prodlng[0].Sequence).text(msg._prodlng[0].Sequence));
In the above code msg._prodlng[0].Sequence comes as selected number
I'm not sure what you are trying to do but it looks like you are adding an <option> tag into another <option> tag which is most likely not what you want.
If the returned value already exists as a selected option:
$("#drpsequence").val(msg._prodlng[0].Sequence).prop('selected', true);
Or, if you need to add an option:
var opt = $("<option>")
.val(msg._prodlng[0].Sequence)
.text(msg._prodlng[0].Sequence);
$("#drpsequence").append(opt);
Snippet example:
// foo --> select
$('#foo').val('baz').prop('selected', true);
$('#bim').click(function(){
$('#foo').append('<option id="boop" value="boop">boop</option>'); //<-- or loaded value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="foo">
<option>-- select --</option>
<option id="bar" value="bar">bar</option>
<option id="baz" value="baz">baz</option>
</select>
<button id="bim">Add an option</button>
You need to do one of following.
Either find that option and make that selected = true like this.
$("#sel option").each(function(i) {
if ($(this).val() == "Orange") $(this).attr("selected", "true");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</select>
Or if that option is not found then add and make that selected = true.
Like the one, which you had in your question.

Jquery - Display element on <select> change

I've searched and searched but my jquery/js skills are so poor I can't get it to work.
What I desire is for each option in the selection a different is displayed for further information.
<label class="checklabel">Is it possible to recieve mail?</label>
<select class="mailoption">
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<div class="yesmail">Yes can recieve mail.</div>
<div class="nomail">No can't recieve mail.</div>
When the value is 1 it should display 'yesmail' and option 2 should display 'nomail'. I've tried several lines of coding gathered from stackoverflow but I all had to adjust it which I can't do to this degree.
Can anyone help me out here?
Thanks,
I guess you have had problems with selecting the DOM elements. As #Teemu points out you might want to use ids instead. You can use $(".foobar") to select the elements with the class foobar and $("#foobar") to select the element with id foobar.
$(document).ready(function() {
$(".mailoption").change(function() {
if($(this).val() == 1) {
$(".yesmail").removeClass('hidden');
$(".nomail").addClass('hidden');
} else {
$(".yesmail").addClass('hidden');
$(".nomail").removeClass('hidden');
}
});
});
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checklabel">Is it possible to recieve mail?</label>
<select class="mailoption">
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<div class="yesmail">Yes can recieve mail.</div>
<div class="nomail hidden">No can't recieve mail.</div>

Showing content of div depending on selection in drop down

I'm having problems with some jQuery that needs to display the content of a div depending on the options selected in a drop down
The drop down needs to pass numerical values into a calculator in order to work out a loan amount so when I added numerical values for the option value and corresponding div id the code doesnt work. If I change the the value and id to a word it works fine.
Is there a work around for this to get it working using the numerical values.
<select name="apr" id="apr" class="loan-calculator__input" >
<option value="">Select</option>
<option value="4.7" class="good">Good</option>
<option value="14.9" class="fair">Fair</option>
<option value="29.9" class="poor">Poor</option>
</select>
</div>
<div id="4.7" style="display:none;" class="rating" ><p>Good - </p>
</div>
<div id="14.9" style="display:none;"class="rating" ><p>Fair</p>
</div>
<div id="29.9" style="display:none;" class="rating"><p>Poor </p>
</div>
(function($) {
$(document).ready(function() {
$('#apr').change(function(){
$('.rating').hide();
$('#' + $(this).val()).show();
});
});
})(jQuery);
I've created a jsfiddle to show the code - http://jsfiddle.net/nineseven/W37np/
use the data attribute because you cannot use a number for an object id
<div data-selectvalue="4.7"/>
$("[data-selectvalue='"+$(this).val()+"']").show()
It is not going to work when you use decimal ID's.
I probably wouldn't go with this workflow for displaying content.
But anyway, here you have a fiddle based on string id's:
http://jsfiddle.net/W37np/11/
(function($) {
$(document).ready(function() {
$('#apr').change(function(){
$('.rating').hide();
$('#' + $( "#apr option:selected" ).attr("value")).show();
});
});
})(jQuery);
This is not working because its been taken as an expression.. don't use numbers
Error: Syntax error, unrecognized expression: #14.9'
check the error console of the browser
I think you need to grab the value of the selected option instead. The others are right too - your ids are not suitable. In the demo I've replaced them with dashes.
$('#' + $(this).find('option:selected').val()).show();
Demo
if want those value to those options value and you can change the div's id to different id say the class the option has then you can extract the class as follows and display it
$('#' + $( "#apr option:selected").attr('class')).show();
fiddle demo
$(document).ready(function () {
$('#apr').change(function () {
$('.rating').hide();
var prefix = "div-";
$('#' + prefix + $("#apr option:selected").attr("value")).show();
});
});
<select name="apr" id="apr" class="loan-calculator__input" >
<option value="-1">Select</option>
<option value="123" class="good">Good</option>
<option value="456" class="fair">Fair</option>
<option value="789" class="poor">Poor</option>
</select>
<div id="div-123" style="display:none;" class="rating" ><p>Good - You are likely to have stable address and job history be on the electoral role and have plenty of good credit and no missed payments</p>
</div>
<div id="div-456" style="display:none;"class="rating" ><p>years carry a higher level of debt and perhaps missed the odd payment</p>
</div>
<div id="div-789" style="display:none;" class="rating"><p>Poor – May have missed made late payments or have CCJs and have frequently moved jobs or not be on the electoral role </p>
</div>
Since Id does not accept numeric value. You can use a prefix on div tag.

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.

Categories

Resources