accessing global variables after setting them javascript - javascript

I am trying to keep track of changes to a select box in django. My code below is working up to alert(change.new_time);, so I am making the object correctly-
var changed_select_box_array = [];
function handleChanges(id){
var x = document.getElementById(id).selectedIndex;
var time = document.getElementsByTagName("option")[x].value;
var change = {id:id, new_time:time};
alert(change.id);
alert(change.new_time);
changed_select_box_array[changed_select_box_array.length] = change;
alert(changed_select_box_array[0].id);
}
but I cannot access the new item in the array. I tried 4-5 different ways and followed some rules for global variables in funcs I found on this site, and I cannot access anything from the new array. Am I doing something wrong adding to the array? I tried push too. Thank you

You can use Object as associative array.
var changed_select_box_array = {};
function handleChanges() {
var x = this.selectedIndex;
var id = this.id;
var time = this.getElementsByTagName("option")[x].value;
var change = { id: id, new_time: time };
changed_select_box_array[id] = change;
console.log(changed_select_box_array);
}
<!--Emitation of some select inputs with change events-->
<select id="s1" onchange="handleChanges.call(this)">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
</select>
<select id="s2" onchange="handleChanges.call(this)">
<option value="val4">Value 1</option>
<option value="val5">Value 2</option>
<option value="val6">Value 3</option>
</select>

Related

Two dynamic select boxes with data attribute in both and dependant on them

How to get dynamic select boxes dependant on the value of data attributes in both?
Got this code
HTML
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>
JS
var sel1 = document.querySelector('#hours');
var sel2 = document.querySelector('#paxno');
var options2 = sel2.querySelectorAll('option');
function giveSelection() {
sel2.innerHTML = '';
for(var i = 0; i < options2.length; i++) {
if(options2[i].dataset.option === $("#hours").find(":selected").data("option")) {
sel2.appendChild(options2[i]);
}
}
}
I have been trying to do this from the example given on this question on Stackoverflow, and it is working when data-attribute is non numeric but data stored in both will be numeric.
Any thoughts what I am doing wrong here? is this the best approach to 2 dynamic select boxes with both having data attributes?
Since you're using jQuery, you might as well use it all the way.
To make it consistent, always use the jQuery data() method. data() will always try to intelligently convert the value of the data field to another type if it can determine that it is a number, or an object, or an array, or etc. So your original was comparing a dataset.option to a data(), using === which removes type coersion. So nothing would ever be equal.
var sel1 = $('#hours');
var sel2 = $('#paxno');
var options2 = sel2.find('option');
function giveSelection() {
var target = sel1.find(':selected').data('option');
sel2.empty().append(
options2.filter(function(){
return $(this).data('option') === target;
})
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>

Multiple values of <option>

I would like to put multiple values in tag within select, so I could adress precisely one or few items.
Example:
<select id="select1">
<option value="pf, nn">NN</option>
<option value="pf, x2, jj">JJ</option>
<option value="pf, uu">UU</option>
<option value="pf, x2, oo">OO</option>
<option value="tt">TT</option>
<option value="rr">RR</option>
</select>
In my js I got that one function that depend on one value that is common for many items:
if (document.getElementById("select1").value = "pf";) {
// do something;
}
if (document.getElementById("select1").value = "x2";) {
// do some-other-thing;
}
But I don't want to use (cos' and with more options gonna get messy)
var sel1 = document.getElementById("select1").value
if (sel1="nn" || sel1="jj" || sel1="uu" || sel1="oo") {
// do something;
}
if (sel1="jj" || sel1="oo") {
// do some-other-thing;
}
Neverthelesst I need to be able to set item by precise one value
if (document.somethingelse = true) {
document.getElementById("select1").value = "oo";)
}
Is there a nice way to achieve this? Maybe use some other "value-like" attribute of option (but which?)?
Only JS.
I think you can do what you want with selectedOpt.value.split(",").includes("sth") code:
$(document).ready(function(e){
selectedChange($("#select1")[0])
});
function selectedChange(val) {
var selectedOpt = val.options[val.selectedIndex];
var status1 = selectedOpt.value.split(",").includes("x2");
var status2 = selectedOpt.value.split(",").includes("pf");
console.log(status1);
console.log(status2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1" onchange="selectedChange(this)">
<option value="pf,nn">NN</option>
<option value="pf,x2,jj">JJ</option>
<option value="pf,uu">UU</option>
<option value="pf,x2,oo">OO</option>
<option value="tt">TT</option>
<option value="rr">RR</option>
</select>

variables seem to be coupled

I've got this weird problem with my JavaScript code.
I'm trying to create dynamically loading select boxes without the luxury of something like React.
It compares values of other select boxes so that a value can only be selected in once. So if a value is already set in one select box, it cannot be selected again.
For this I use a list of original values, clone those values into a new variable and remove the ones already selected and then create new lists.
Works fine albeit the numerous loops. The only problem is that if I remove an item from the cloned variable, the original also changes.
Even if I push the original variable in a prototype object or use const.
window.initial_abstract_list = ["Option one", "Option two", "Option three", "Option four", "Option five"];
// Set the option values
function reset_abstract_list() {
var in_list = [];
var new_list = window.initial_abstract_list;
console.log(window.initial_abstract_list); /// window.initial_abstract_list changes!!!
// Get selected value of all select boxes
$.each($('select.values-list'), function(index, value) {
in_list.push($(value).val().toString())
});
// Remove already set values from list
$.each($('select.values-list'), function(index, value) {
$.each(in_list, function(index2, value2) {
delete new_list[value2.toString()];
});
});
// Generate new options for select boxes
$.each($('select.values-list'), function(index, value) {
var current_selected_key = $(value).val().toString();
var current_selected_val = $('option:selected', value).text();
$(value).empty();
$(value).append($('<option></option>')
.attr('value', current_selected_key)
.text(current_selected_val));
for (var index2 in new_list) {
"use strict";
$(value).append($('<option></option>')
.attr('value', index2)
.text(new_list[index2]));
};
});
}
// Alter content on change select boxes
jQuery(document).ready(function($) {
$(document).on('click', 'button', function(e) {
reset_abstract_list();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="values-list">
<option value="0">Option one</option>
<option value="1">Option two</option>
<option value="2">Option three</option>
<option value="3">Option four</option>
</select>
<select class="values-list">
<option value="0">Option one</option>
<option value="1">Option two</option>
<option value="2">Option three</option>
<option value="3">Option four</option>
</select>
<select class="values-list">
<option value="0">Option one</option>
<option value="1">Option two</option>
<option value="2">Option three</option>
<option value="3">Option four</option>
</select>
<button>Ye olde button</button>
When you set your new_list to the default list, it's basically creating a reference to the original. You need to instead copy the values of the original list so they aren't coupled.
var new_list = window.initial_abstract_list.slice();
By doing var new_list = window.initial_abstract_list; you are only creating a reference to the original array. Any changes made to new_list will reflect in the initial array.
What you want to do is create a deep copy of the initial array, so as to get a different variable but with the same values. You can do this like so:
var new_list = jQuery.extend(true, {}, window.initial_abstract_list);

Fetching data value defined in the select tag when an option is selected

I have the following markup and I need to fetch value of data-base inside the function below.
<select id="myid" onclick="myselected(this)" data-base="/admin/index">
<option value="2">Two</option>
<option value="3">Three</option>
</select>
JS
function myselected(obj) {
var idx = obj.selectedIndex;
var ival = obj.options[idx].value;
var baseval = .... ? how do I access data-base value?
}
Try element.getAttribute():
var baseval = obj.getAttribute('data-base')

Javascript to Select item from listbox by value number

I have a listbox on a page:
<select id="user_list" name="user_list" size="21" style="width:200px;">
<option value=1>User 1</option>
<option value=2>User 2</option>
<option value=3>User 3</option>
<option value=5>User 5</option>
<option value=6>User 6</option>
</select>
And if I select a item I can get the current value by using the following code:
var el = document.getElementById("user_list");
var val = el[el.selectedIndex].value;
alert(val);
However, the problem I am having is that I want to be able to search the user_list (start from 1) for the next avaliable number (in my example above it will alert 4, as that is missing)
But I have tried using:
var el = document.getElementById("user_list");
var val = el[4].value;
alert(val);
but it doesn't work, does anyone know what I am doing wrong?
My guess is that var val = el[4].value; is wrong.. ?
it works well.
http://jsfiddle.net/ubpn7/

Categories