I am a newbie with a localstorage issue. I have a few dependent dropdowns that are loaded via ajax from a server. When the user makes a selection the localstorage stores the wrong value...the last value. From my research I thought that .map() may be a solution to my problem but being a newbie I am not familiar with the syntax and I have not been able to get it to work. Can anyone figure out what is causing this problem? Is .map() the correct solution? Here is a photo of what I am having an issue with.
Here is the code
$('.country').on('change', function () {
var countryId = $(this).val();
var state_select = $(this).closest('form').find('.state');
var city_select = $(this).closest('form').find('.city');
if (countryId) {
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'ajaxData3.php',
data: {
country_id: countryId
},
success: function (r) {
console.log('States', r);
$(state_select).html('<option value="" selected="selected">State</option>');
$(city_select).html('<option value="" selected="selected">City </option>');
if (r.status) {
r.data.forEach(function (state) {
$(state_select).append(`<option value="${state.id}">${state.name}</option>`);
$('.state').each(function(r) {
var stateList = $(state);
var thisSelection = $(this);
var thisId = thisSelection.attr('id');
var storageId = 'state-' + thisId;
var storedInfo = JSON.parse(localStorage.getItem(storageId));
thisSelection.change(function(i) {
var selectedOptions = []; // create an array to hold all currently selected options
thisSelection.find('option:selected').each(function(i) {
var thisOption = $(this);
selectedOptions.push(thisOption.val());
});
localStorage.setItem(storageId, JSON.stringify(state.name));
})
})
})
} else {
$(state_select).html('<option value="" selected="selected">Unavailable </option>');
$(city_select).html('<option value="" selected="selected">Unavailable </option>');
}
}
})
};
Here is the markup
<form id="form1" autocomplete="off">
<select id="country1" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state1" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city1" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
<form id="form2" autocomplete="off">
<select id="country2" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state2" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city2" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
<form id="form3" autocomplete="off">
<select id="country3" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state3" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city3" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
I decided to post the answer so others can see. Hopefully someone here on stackoverflow will take the time to help me next time. This 'voting', 'points' and 'badge' thing gets in the way of actual learning.
The forEach() reiterates the function each time it is called. So the last entry will be where the reiteration completes. The localStorage.setItem needs to be moved into a .change() function or .on('change', function()) and the value needs to be .text() to simply read the text that was displayed.
localStorage.setItem('yourkeyhere', JSON.stringify($(this).text()));
Related
I have 4 choice fields in a single form. My jQuery code only captures one field. How can I capture the other fields and extract their values?
Also, I have applied the Select2 plugin on all these fields. Can someone please guide me? Thanks in advance.
$('select').change(function() {
var optionSelected = $(this).find("option:selected");
var valueSelected = optionSelected.val();
var textSelected = optionSelected.text();
var csr = $("input[name=csrfmiddlewaretoken]").val();
console.log(textSelected);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<label for="id_package_form-patient">Patient:</label>
<select name="package_form-patient" required id="id_package_form-patient">
<option value="" selected>---------</option>
<option value="8">jfkdfkldlfd</option>
</select>
<label for="id_package_form-diagnosis">Diagnosis:</label>
<select name="package_form-diagnosis" required id="id_package_form-diagnosis">
<option value="" selected>---------</option>
<option value="1">fefafd</option>
<option value="2">effeafaefe</option>
</select>
<label for="id_package_form-treatment">Treatment:</label>
<select name="package_form-treatment" required id="id_package_form-treatment">
<option value="" selected>---------</option>
<option value="1">fdfef</option>
</select>
<label for="id_package_form-patient_type">Patient type:</label>
<select name="package_form-patient_type" required id="id_package_form-patient_type">
<option value="" selected>---------</option>
<option value="1">kflkdjkf</option>
<option value="2">fldfjdfj</option>
</select>
To get the selected text of all the select elements you can use map() to build an array of them, like this:
let getSelectedText = () => {
let textArr = $selects.map((i, el) => $(el).find('option:selected').text()).get();
console.log(textArr);
}
let $selects = $('select').on('change', getSelectedText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<label for="id_package_form-patient">Patient:</label>
<select name="package_form-patient" required id="id_package_form-patient">
<option value="" selected>---------</option>
<option value="8">jfkdfkldlfd</option>
</select>
<label for="id_package_form-diagnosis">Diagnosis:</label>
<select name="package_form-diagnosis" required id="id_package_form-diagnosis">
<option value="" selected>---------</option>
<option value="1">fefafd</option>
<option value="2">effeafaefe</option>
</select>
<label for="id_package_form-treatment">Treatment:</label>
<select name="package_form-treatment" required id="id_package_form-treatment">
<option value="" selected>---------</option>
<option value="1">fdfef</option>
</select>
<label for="id_package_form-patient_type">Patient type:</label>
<select name="package_form-patient_type" required id="id_package_form-patient_type">
<option value="" selected>---------</option>
<option value="1">kflkdjkf</option>
<option value="2">fldfjdfj</option>
</select>
I have a code that works perfectly fine because it is hardcoded but extremely large. I would like to simplify this code to make it general and of course smaller. Does anybody know how to do this? Since it is so large I will shrink it down for this question.
var theform1 = $('#form1').find('.state option');
var stateForm1 = Object.keys(localStorage).filter(key => key.endsWith('-state1'));
var stateChoice1 = JSON.parse(localStorage.getItem(stateForm1));
var theform2 = $('#form2').find('.state option');
var stateForm2 = Object.keys(localStorage).filter(key => key.endsWith('-state2'));
var stateChoice2 = JSON.parse(localStorage.getItem(stateForm2));
var theform3 = $('#form3').find('.state option');
var stateForm3 = Object.keys(localStorage).filter(key => key.endsWith('-state3'));
var stateChoice3 = JSON.parse(localStorage.getItem(stateForm3));
if (localStorage.getItem(stateForm1)) {
$(theform1).empty();
$(theform1).val(stateChoice1).append(`<option value="${stateChoice1}">${stateChoice1}</option>`).trigger('window.load');
};
if (localStorage.getItem(stateForm2)) {
$(theform2).empty();
$(theform2).val(stateChoice2).append(`<option value="${stateChoice2}">${stateChoice2}</option>`).trigger('window.load');
};
if (localStorage.getItem(stateForm3)) {
$(theform3).empty();
$(theform3).val(stateChoice3).append(`<option value="${stateChoice3}">${stateChoice3}</option>`).trigger('window.load');
};
The HTML markup is as follows:
<form id="form1" autocomplete="off">
<select id="country1" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state1" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city1" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
<form id="form2" autocomplete="off">
<select id="country2" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state2" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city2" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
<form id="form3" autocomplete="off">
<select id="country3" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state3" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city3" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
Maybe you're looking for this compressed version:
$('#form1,#form2,#form3').each(function () {
var index = this.id.substring(this.id.length - 1, this.id.length);
var stateForm = Object.keys(localStorage).filter(key => key.endsWith('-state' + index));
var stateChoice = JSON.parse(localStorage.getItem(stateForm));
if (localStorage.getItem(stateForm)) {
var theform = $(this).find('.state option').empty();
theform.val(stateChoice)
.append(`<option value="${stateChoice}">${stateChoice}</option>`)
.trigger('window.load');
}
});
If you have more than 10 forms with the index increasing from 1 to 99 or 999... You can edit the way to name your form id to: form01 form02 form03 or form001 form002 form003...
Then, because all of the id names start with form, you can update the selectors like this:
Changing $('#form1,#form2,#form3') to $('[id^="form"]'). That selector means: selecting some element(s) which contains the id starts with form.
Lastly, if your form id following by 2 digits (form01), you update the line to get the index to:
var index = this.id.substring(this.id.length - 2, this.id.length);
You can do the same way for the ids following by 3 digits (form001):
var index = this.id.substring(this.id.length - 3, this.id.length);
Loop over all the select.state and get the number from the parent form.
Something like:
$('select.state').each(function() {
const $sel = $(this),
formNum = $sel.closest('form').attr('id').replace('form', ''),
stateForm = Object.keys(localStorage).find(key => key.endsWith(`-state${formNum }`)),
stateChoice = localStorage.getItem(stateForm);
if (stateChoice) {
$sel.append(new Option(stateChoice. stateChoice))
.val(stateChoice)
.trigger('window.load');
}
})
Note I changed filter() to find() for the keys since filter returns an array
How to take the values of value1 and value2 in two variables using javascript?
<select class="form-control" id="country" name="country">
<option value="**value1**" "**value2**" >Select Item</option>
</select>
You could make your own attribute. I know you probably do not want to get the element with an ID, but I don't know the context. You can just call getAttribute on the option and use any name you gave to the "custom" attribute.
window.addEventListener('load', ()=>
{
const option = document.getElementById('option');
function init()
{
//Use this to get the values
console.log(option.getAttribute('other-value'));
}
init();
});
<select class="form-control" id="country" name="country">
<option id="option" value="value1" other-value="value2">Select Item</option>
</select>
I don't know what you really want to do with your piece of code,
but here is a proper way to use the option elements, and a way to split multiple values with a fixed separator:
var example = document.getElementById('example');
example.addEventListener('change', function() {
// Console displays the “value”, and not the text, of the selected option
console.log("option value:", example.value);
});
// Here is what I'll do with your "multiple" values
var country = document.getElementById('country');
var options = country.querySelector('option');
var values = options.value.split("/");
values.forEach(function(val) {
country.innerHTML += "<option value=" + val + ">" + val + "</option>";
});
<p>My simple example</p>
<select id="example" name="country">
<option value="--">Select Country</option>
<option value="GB">Great Britain</option>
<option value="FR">France</option>
</select>
<br>
<br>
<p>Example with option getting splitted</p>
<select class="form-control" id="country" name="country">
<!-- Let's say your multiple values are separated by a "/" -->
<option value="**value1**/**value2**">Select Item</option>
</select>
Hope it helps.
$('select').on('change', function() {
console.log( $('#country').val() );
console.log($(this).find(':selected').data('second'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control" id="country" name="country">
<option value="value1" data-second ="value2" >Select Item 1</option>
<option value="value3" data-second ="value4" >Select Item 2</option>
</select>
I am very new to javascript. So i have a select option and an input field. What i want to achieve is to have the value of the input field change when i select a particular option. This is what i have tried:
First Name: <input type="text" value="colors">
<select name="">
<option>Choose Database Type</option>
<option onclick="myFunction(g)>green</option>
<option onclick="myFunction(r)>red</option>
<option onclick="myFunction(o)>orange</option>
<option onclick="myFunction(b)>black</option>
</select>
<script>
function myFunction(g) {
document.getElementById("myText").value = "green";
}
function myFunction(r) {
document.getElementById("myText").value = "red";
}
function myFunction(o) {
document.getElementById("myText").value = "orange";
}
function myFunction(b) {
document.getElementById("myText").value = "black";
}
</script>
A few things:
You should use the onchange function, rather than onclick on each individual option.
Use a value attribute on each option to store the data, and use an instance of this to assign the change (or event.target)
You have no ID on your text field
You're missing the end quote for your onclick function
<select name="" onchange="myFunction(event)">
<option disabled selected>Choose Database Type</option>
<option value="Green">green</option>
<option value="Red">red</option>
<option value="Orange">orange</option>
<option value="Black">black</option>
</select>
And the function:
function myFunction(e) {
document.getElementById("myText").value = e.target.value
}
And add the ID
<input id="myText" type="text" value="colors">
Fiddle: https://jsfiddle.net/gasjv4hs/
More proper way is to put your JS code in a different .js file and use Jquery as when you go further with your programming this is the proper way.
Your HTML
<input type="text" id="color" name="color">
<select name="" id="changeData">
<option>Choose Database Type</option>
<option data-value="green">green</option>
<option data-value="red">red</option>
<option data-value="orange">orange</option>
<option data-value="black">black</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
Your JS
$(document).ready(function () {
$('#changeData').change(function(){
var color = $(this).val();
$('#color').val(color);
})
});
Also make sure that you have added Jquery Library to your Project. You can either download Jquery and add in your project folder OR also you can use CDN. in this example CDN is used.
I came up with a similar problem. In my case i was trying to change the minimum value of an input based on the value of an option in a select list. I tried to apply the above solutions but nothing worked. So i came with this, which can be applied to problems similar to this
HTML
<input id="colors" type="text" value="">
<select id="select-colors" name="" onchange="myFunction()">
<option disabled selected>Choose Colour</option>
<option value="green">green</option>
<option value="red">red</option>
<option value="orange">orange</option>
<option value="black">black</option>
</select>
JS
function myFunction() {
var x = document.getElementById("select-colors").value;
document.getElementById("colors").value = x;
}
This works by getting the value of the select with id "select-colors" on every change, assigning it into a variable "x" and inserting it into the input value with id "colors". This can be implemented in anyway based on your problem
You create functions with same name multiple times.
Only last one will work.
the variables you pass g,r,o,b are undefined.
Don't add onclick to option add onchange to select.
Make use of HTML5 data-* attribute
function myFunction(element) {
document.getElementById("myText").value = element;
}
First Name: <input type="text" id="myText" value="colors">
<select name="" onchange="myFunction(this.value);">
<option>Choose Database Type</option>
<option data-value="green">green</option>
<option data-value="red">red</option>
<option data-value="orange">orange</option>
<option data-value="black">black</option>
</select>
You can resolve it this way.
` First Name:
<select name="" onchange="myFunction()" id="selectID">
<option>Choose Database Type</option>
<option >green</option>
<option >red</option>
<option >orange</option>
<option >black</option>
</select>
<script>
function myFunction() {
var selectItem = document.getElementByID('selectID').value;
document.getElementByID('yourId').value = sekectItem;
}
</script>
Here's a way to achieve that:
var select = document.getElementById('colorName');
function myFunction(event) {
var color = 'No color selected';
if (select.selectedIndex > 0) {
color = select.item(select.selectedIndex).textContent;
}
document.getElementById('myText').value = color;
}
select.addEventListener('click', myFunction);
myFunction();
First Name: <input type="text" id="myText">
<select id="colorName">
<option>Choose Database Type</option>
<option>green</option>
<option>red</option>
<option>orange</option>
<option>black</option>
</select>
Your code should be like following.
<input type="text" name="color" id="color">
<select name="" id="change_color">
<option>Choose Database Type</option>
<option >green</option>
<option >red</option>
<option >orange</option>
<option >black</option>
</select>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function () {
$('#change_color').change(function(){
var color = ($(this).val());
$('#color').val(color);
})
});
</script>
Here is JS Code that worked for me
var selectYear = document.getElementById('select-year');
selectYear.addEventListener('change', function() {
var selectedYear = document.getElementById('selected-year');
selectedYear.innerHTML = selectYear.value;
});
Select Input ID: select-year
Text ID: selected-year
Code generated from Codex AI :)
I'm working on a small website and I currently have two dropdowns in my form, both are below:
<select name="classType" id="classType" required>
<option value="" disabled selected>Select Your Class Type</option>
<option value = "Beginner">Beginner</option>
<option value = "Intermediate">Intermediate</option>
<option value = "Advanced">Advanced</option>
</select>
<br/>
<select name="studentType" id="studentType" required>
<option value="" disabled selected>Select Your Student Type</option>
<option value = "lowerLevel">Lower Level</option>
<option value = "upperLevel">Upper Level</option>
</select>
<br/>
I've experimented with some javascript but only at a beginner level. I was wondering if there's a way to disable a specific value in the studentType dropdown.
So for example if i select "Beginner" in the first dropdown then the option for "UpperLevel" in the second dropdown should be disabled.
This is what I tried, but it was not working:
var dropdown = document.getElementById("classType");
dropdown.onchange = function(event){
if (dropdown.value == "Beginner") {
// .....
Any ideas?
Thanks!
You can achieve this by hooking an event handler to the change event of the first select which sets the disabled property of the relevant option in the second select based on the chosen option, something like this:
$('#classType').change(function() {
$('#studentType option[value="upperLevel"]').prop('disabled', $(this).val() == 'Beginner')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="classType" id="classType" required>
<option value="" disabled="true" selected="true">Select Your Class Type</option>
<option value="Beginner">Beginner</option>
<option value="Intermediate">Intermediate</option>
<option value="Advanced">Advanced</option>
</select><br/>
<select name="studentType" id="studentType" required>
<option value="" disabled="true" selected="true">Select Your Student Type</option>
<option value="lowerLevel">Lower Level</option>
<option value="upperLevel">Upper Level</option>
</select><br/>
This should fit your needs:
http://codepen.io/themeler/pen/yOjWXB
<select name="classType" id="classType" required>
<option value="" disabled selected>Select Your Class Type</option>
<option value = "Beginner">Beginner</option>
<option value = "Intermediate">Intermediate</option>
<option value = "Advanced">Advanced</option>
</select>
<br/>
<select name="studentType" id="studentType" required>
<option value="" disabled selected>Select Your Student Type</option>
<option value="lowerLevel">Lower Level</option>
<option value="upperLevel">Upper Level</option>
</select>
<br/>
$(function () {
var $class = $('#classType'),
$student = $('#studentType');
$class.on('change', function () {
var $this = $(this),
$ul = $student.find('[value="upperLevel"]');
// clear value of student type on class type change
$student.find(':selected').prop('selected', false);
$student.find('option:first-child').prop('selected', true);
// lock / unlock position
if ($this.val() === 'Beginner') {
$ul.prop('disabled', true);
} else {
$ul.prop('disabled', false);
}
});
});
By jQuery:
$('#studentType option[value="upperLevel"]').attr('disabled','disabled');
Here is how I would do it, add a data-enabled tag to each option like this:
<select name="classType" id="classType" required>
<option value="" disabled selected>Select Your Class Type</option>
<option value = "Beginner" data-enabled="lowerLevel">Beginner</option>
<option value = "Intermediate" data-enabled="lowerLevel,upperLevel">Intermediate</option>
<option value = "Advanced" data-enabled="upperLevel">Advanced</option>
</select>
<br/>
<select name="studentType" id="studentType" required>
<option value="" disabled selected>Select Your Student Type</option>
<option value = "lowerLevel">Lower Level</option>
<option value = "upperLevel">Upper Level</option>
</select>
<br/>
And on change of the drop down, disable all options in the other drop down, then loop through and see if they're either in the enabled tag of the selected, or blank like this:
$('#classType').on('change', function(){
var allowed = $('#classType option:selected').attr('data-enabled').split(',');
$('#studentType option').attr('disabled','disabled');
$('#studentType option').each(function(){
if (allowed.indexOf($(this).val()) > -1 || !$(this).val()) {
$(this).removeAttr('disabled');
}
});
});