Create options onClick attribute - javascript

This is the idea: When I click on "word1" (or "word2") the select tag shows me the options. Once I click on one of the options, my script change "word1" (or "word2") whit the option. I can update the options, but once I click on one of them the script always write the last option.
The script write the same onClick attribute for all the options...
I've been searching a lot but I cannot understand why it happen, and how to solve it.
Here is the code:
function updatemyselect(currentElement, optionsList) {
var mySelect = document.getElementById("mySelect");
var i;
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i]
option.text = newWord;
option.onclick = function() {
currentElement.innerHTML = newWord;
};
mySelect.add(option);
}
}
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" class="changedWord">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" class="changedWord">Word2</p>
Thanks in advance

You can not bind 'click events' on 'options' property of a 'select box'. You will need to bind a onchange event listner on the 'select element'. Inside the callback function of the change event listner put your code logic for updating word text. As the 'change' event listner is not in the scope of 'updatemyselect' function, you can store the last clicked element in a variable and use the same in the callback function for updating the desired word text. Please refer to the below code which I have edited.
var clickedElement;
function updatemyselect(currentElement, optionsList) {
clickedElement = currentElement;
var mySelect = document.getElementById("mySelect");
var i;
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i]
option.text = newWord;
/*option.onclick = function() {
currentElement.innerHTML = newWord;
};*/
mySelect.add(option);
}
}
document.getElementById("mySelect").addEventListener("change", updatePTag);
function updatePTag(){
clickedElement.innerHTML = this.value;
};
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" class="changedWord">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" class="changedWord">Word2</p>

The reason why you are always getting the last option value is because you are using the newWord variable in your onclick function instead of an actual value, or reference to the currently selected option.
As a result, after you have finished going through the loop, the value of newWord is always equal to the last option text, so, regardless of which option is selected, when you are returning newWord, you will get the same value (i.e., either, "Fish" or "Whale").
Instead, try using currentElement.innerHTML = mySelect.value; in the onclick function.

First you need to set the value attribute on each option.
After you can use the onChange event on Select to display your value.
You can use Jquery to do this, its more easy
jquery select change event get selected option

Thanks to everybody.
I didn't realize that currentElement.innerHTML = newWord; was actually giving the value of the same variable to every onClick attribute.
I finally solved in this way, even if I think the solution of Arun Singh is better.
function updatemyselect(currentElement, optionsList) {
var mySelect = document.getElementById("mySelect");
var i;
mySelect.onchange= function() {currentElement.innerHTML=mySelect.value;};
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i];
option.text = newWord;
mySelect.add(option);
}
}
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" value="a">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" value="b">Word2</p>

Related

JQuery get the option of a checkbox checked

I'm doing some code where i need to get the option(value) from an checkbox checked
Here is how i create the checkbox
function createCheckbox(txt) {
var comb = document.createElement("Select");
comb.className = "something";
for (var i = 0; i < txt.length; i++) {
var option = document.createElement("OPTION");
var optionText = document.createTextNode(txt[i]); //some options
option.appendChild(optionText);
comb.appendChild(option);
}
return comb;
}
Function where i need to show the option that is selected
function foo{
var inputTextValue = document.getElementsByClassName("something");
var checkedValue = $(inputTextValue).is(':checked');
alert(checkedValue); //true/false
}
the alert only show true /false depeding if the checkbox is checked or not.But what i need its the option checked. I already tried $(inputTextValue).is(':checked').val().
Checkbox and Select are two different HTML Elements
For Getting the value of Selected option use
$(".something option:selected").val();
I think tou mix here between checkbox and select.
Select option is selected with :selected attribute.
Checkbox is checked with :checked attribute.
The value of a <select> is the value of the selected option.
$(".something").val()

Changing one select option changes many others (JavaScript, JQuery)

I have a lot of select drop downs on a jsp page with a long list of elements. All of these drop downs have the same list of elements. Say I have to get the choice in descending order of preference from the user. I made (many) selects in the following way:
<select id="sel1" class="myClass">
<script>
populate(document.getElementById('sel1'));
</script>
</select>
...
<script>
function populate(op1)
{
var myArray = ["Chinese", "Italian", "Indian", ...//a long list of elements
var sel = op1;
for(var i = 0; i < myArray.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = myArray[i];
opt.value = myArray[i];
sel.appendChild(opt);
}
}
</script>
I have to create javascript/JQuery code in such a way that if a user selects an option the first select, that option gets disabled/removed in the others, leaving room for changes later. Say, the user's preference order is: Chinese, Indian, Italian... then on selecting Chinese in the first drop down, it gets disabled/removed from the other drop downs. Then, on selecting Indian from the second, it gets disabled/removed from all the others (including the previous one).
Now, if the user decides his order of preference is actually Chinese, Italian, Indian, .. he should be able to change his choice in such a way that the code doesn't break down. Say, we can have a button for reset and it resets all the choices by calling this function:
function resetFunc()
{
var options = document.getElementsByClassName("myClass");
for (var i = 0, l = options.length; i < l; i++)
{
options[i].selectedIndex = "0";
}
}
Any idea how to accomplish this? I need the code to be browser independent (while googling, I read somewhere that IE doesn't support removal of elements from drop down).
EDIT: Here's what I basically want:
http://jsfiddle.net/RaBuQ/1/
However, there's a problem in this. If a user keeps changing his choices, this thing breaks down. I'm able to select multiple choices.
$('select').change(function(){
var v = $(this).val();
$('select option[value="'+$(this).data('old-val')+'"]').prop('disabled', false);
$(this).data('old-val',v);
if(v != "0"){
$('select option[value="'+v+'"]').not(this).prop('disabled',true);
}
});
Here's a fiddle.
If I selected 'Football', 'Golf', 'Tennis', I'd need to select 'No preference' in the third box before I could then select it in one of the other boxes. I think this is acceptable from a UX perspective.
Since you've tagged this jQuery my example below will utilize that:
function populate() {
var myArray = ["Chinese", "Italian", "Indian"];
$('.myClass').each(function() {
var dis = $(this);
dis.append($("<option>").attr("value", "").text("select"));
$.each(myArray, function(i, o) {
dis.append($("<option>").attr("value", o).text(o));
});
});
}
function init() {
$('.myClass').html('').prop('disabled', false);
populate();
}
$(document).on('change', '.myClass', function() {
$('.myClass option[value="' + $(this).val() + '"]:not(:checked)').remove();
$(this).prop('disabled', true);
});
$('#reset').click(init);
init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel1" class="myClass"></select>
<select id="sel2" class="myClass"></select>
<select id="sel3" class="myClass"></select>
<input type="button" id="reset" value="Reset options" />
The following might not be the most efficient solution, but you should try it if there is nothing better: when you change a select, empty all other selects and then fill them with all the other options.
lets say you have 3 selects: sel1, sel2, sel3
in the onchange event, you could call a function "fill_other_sel(number)" where number is the number of the current selector.
This function should delete current options and then populate checking with the previous selectors so that you dont populate with a previously selected value.
function fill_other_sel(number){
var num_selectors = 3;
while (number <= num_selectors){
number++;
$('#sel'+number).options.length=1;
populate('sel'+number, already_selected_values_array);
}
}
also you might add a parameter to your populate function showing which values have already been selected to prevent them from appearing again

How to apply onfocus function to all "input" objects?

I'd like to create an onfocus function to my input fields in a form. I'm working with a drag and drop landing page wizard(in Marketo) therefore I don't have access to the HTML tags.
I tried to do use getElementById and it worked only on the first field. I also tried the following:
<script>
var input = document.getElementsByTagName('input')[0]
input.onfocus = function() {
this.value=''
}
</script>
You query for all the <input>s elements, but work only with the first match:
var input = document.getElementsByTagName('input')[0]
Iterate over all the matches and do your magic:
var inputs = document.getElementsByTagName('input');
for (var i=0; i< inputs.length; i++){
inputs[i].onfocus = function(){this.value = '';};
}
If you can use jQuery, it's a lot easier:
$('input').focus(function(){this.value = '';});
Another variant would be this
//get all inputs
var inputs = document.getElementsByTagName('input')
//cache the length
, inputsLen = inputs.length;
//define one handler
function focusHandler(){
this.style.backgroundColor = 'red';
}
//loop through all
while(inputsLen--){
//each element's onfocus references only one function instead of "one each"
inputs[inputsLen].onfocus = focusHandler;
}
yea ,in jquery you can do it like:
$("input").on("focus",function(){
//function data block goes here
});
Everyone beat me to it but try this
$("input").on("focus",function()
{
this.value=''
});

How do I add items to multiple drop down lists at the same time with Javascript in Razor?

I'm creating an MVC form, and I have multiple checkboxes and two drop down lists. I have figured out how to populate the first DDL based on what boxes are checked (i.e. empty at the beginning, checking boxes fills the items). However, I want to add another DDL that has the same items and populates in the same manner. My code looks like this:
<script type="text/javascript">
function checkedToggle(value, checked) {
x = document.getElementById("filter1");
y = document.getElementById("filter2");
if (checked == true) {
var option = document.createElement("option");
option.text = value;
x.add(option, null);
y.add(option, null);
}
else {
for (i = 0; i < x.length; i++) {
if (x.options[i].value == value) {
x.remove(i);
y.remove(i);
}
}
}
}
</script>
The else statement obviously removes an item from the list once you uncheck the box.
Now, when you click a check box, rather than adding the item to both lists, it only adds to the second one, and I'm not exactly sure why. Any advice?
You need to create two elements, since in your code you just move the first DOM element to the second select.
var option = document.createElement("option");
var option2 = document.createElement("option");
option.text = value;
option2.text = value;
x.add(option, null);
y.add(option2, null);

How do I access the "displayed" text of a select box option from the DOM?

Given the following HTML:
<select name="my_dropdown" id="my_dropdown">
<option value="1">displayed text 1</option>
</select>
How do I grab the string "displayed text 1" using Javascript/the DOM?
var sel = document.getElementById("my_dropdown");
//get the selected option
var selectedText = sel.options[sel.selectedIndex].text;
//or get the first option
var optionText = sel.options[0].text;
//or get the option with value="1"
for(var i=0; i<sel.options.length; i++){
if(sel.options[i].value == "1"){
var valueIsOneText = sel.options[i].text;
}
}
var mySelect = document.forms["my_form"].my_dropdown;
// or if you select has a id
var mySelect = document.getElementById("my_dropdown");
var text = mySelect.options[mySelect.selectedIndex].text;
Assuming you want the selected option's text:
var select = document.getElementById('my_dropdown');
for(var i = 0; i < select.options.length; i++) {
if(select.options[i].selected) {
break;
}
}
var selectText = select.options[i].text;
In Prototype:
var selectText = $$('#my_dropdown option[selected]')[0].text;
Edit: And jQuery for completeness' sake (assuming jQuery's CSS selector support is roughly equivalent to that of Prototype's):
var selectText = $('#my_dropdown option[selected]').get(0).text;
The displayed text is a child node of the option node. You can use:
myOptionNode.childNodes[0];
to access it, assuming the text node is the only thing inside the option (and not other tags).
EDIT: Oh yeah, as others mentioned, I completely forgot about:
myOptionNode.text;
Assuming you modified your code a bit to have an id / class on the and were using jQuery you could have something like the following. It will pop up an alert for each option with the text of the option. You probably won't want to alert for all the text, but it illustrates how to get at the text in the first place:
$('select#id option').each(function() {
alert($(this).text());
});
If you use a class instead of an id, then you'd just have to change the 'select#id' to 'select.class'. If you didn't want to add a class/id there are other ways to get at the select.
I leave figuring those ways out if you want to go that route as an activity for the reader.
If you were using Prototype, you could get at it like this:
$$('#my_dropdown option[value=1]').each( function(elem){
alert(elem.text);
});
The above is using a CSS selector that says find all option tags with value="1" that are inside the element that has id="my_dropdown".

Categories

Resources