getting an onclick event to a select option using js - javascript

i am having a very frustrating problem. I have this code
which filters out my results and inputs them into a select box
var syn = <?=json_encode($syn)?>;
function filterByCity() {
var e = document.getElementById("city_filter");
var city = e.options[e.selectedIndex].value;
var selectOptions = document.getElementById('syn_list');
selectOptions.options.length = 0;
for (i = 0; i < syn.length; i++) {
if (city == syn[i]['city'] || city == 'all') {
selectOptions.options[selectOptions.options.length] = new Option(syn[i]['name'], syn[i]['id'] + '" onclick="updateTxtContent(\'' + syn[i]['id'] + '\')');
}
}
}
as you might see i am adding a onclick listener to every select "option" which look great in the source code of the page itself but if i copy it into an edit i notice this
my problem is that the "updateTxtContent()" function is not called.
<select size="10" name="syn_list" id="syn_list" class="span12" dir="rtl" style="text-align:right;">
<option value="13" onclick="updateTxtContent('13')">option a</option>
<option value="14" onclick="updateTxtContent('14')">option b</option>
obviously there should be a better way to do this that i am not aware of.

maybe try an onchange event in your select tag.
<select size="10" name="syn_list" id="syn_list" class="span12" dir="rtl" style="text-align:right;" onchange='updateTxtContext(this.value);'>

I think you want to have your event handler on your select rather than on the option. See this fiddle for what I mean
<select size="10" name="syn_list" id="syn_list" class="span12" dir="rtl" style="text-align:right;" onchange="updateTxtContent();">
<option value="13">option a</option>
<option value="14">option b</option>
</select>
<script>
function updateTxtContent(){
alert($("#syn_list").val());
}
</script>
​
Or since it looks like you aren't using jQuery:
function updateTxtContent(){
var e = document.getElementById("syn_list");
var f = e.options[e.selectedIndex].value;
alert(f);
}

option elements can not have click events in most browsers.
And new option is setting the value and the text, not sure why you think you can set other attributes with it.
You want to use a change event on the select element.

As of 2016 it looks like click events are supported for selects and have the option clicked upon as target:
using jQuery
click_handler = function(e) {
alert('clicked on: ' + e.target.value);
}
$('#syn_list').click(click_handler);
Works at least in Firefox 44

Related

How to build image name/path from two select/option id by Javascript

I'm trying to bulid an image path from two select fields. I have to use the "id"s because "value"s are used already. Unfortunatedly only the second select works. Does anyone have a hint? As you might see I'm not a coder. Could anyone be so kind and help to make the code more elegant/slim?
I use onchange to update the "result1" and "result2" allways when the user alters his selection.
Thanks in advance, Georg
Here is my code:
<script>
function showOptions1(s) {
document.getElementById("result1").innerHTML = "<img src='img/preview/" + s[s.selectedIndex].id;
}
</script>
<script>
function showOptions2(s) {
document.getElementById("result2").innerHTML = s[s.selectedIndex].id + ".jpg'>";
}
</script>
<select onchange="showOptions1(this)" id="my_select1">
<option value="werta" id="1">Text Item 1a</option>
<option value="wertb" id="2">Text Item 1b</option>
</select>
<select onchange="showOptions2(this)" id="my_select2">
<option value="wertc" id="3">Text Item 1c</option>
<option value="wertd" id="4">Text Item 1d</option>
</select>
<span id="result1"></span><span id="result2"></span>
I wouldn't use the onchange event because you want the user to select two things before building the path. So, put another button on the screen called "save image" or something like that. The onclick of this button gets the "value" of each select input and concats them together. You can easily get a handle to the select inputs using jquery by name
var select1 = $("#my_select1");
Now your problem is that you don't want the value. That would be easy. Instead you want the select option and then you want to get the id. You can do that as follows
var my1id = $("#my_select1 option:selected" ).id;
Thanks a lot for your support. Cheers Georg
Finaly I use this code (and stick to onchange because I dont want another button because there are allready three of them):
<script>
var selection01, selection02;
showOptions1 = function(s) {
selection01 = "<img src='img/preview/" + s[ s.selectedIndex ].id;
getResult();
};
showOptions2 = function(s) {
selection02 = s[ s.selectedIndex ].id + ".jpg' width='200px;'>";
getResult();
};
function getResult() {
var total = selection01 + selection02;
console.log( total );
document.getElementById("Image").innerHTML = total;
};
</script>
<select id="select1" onchange="showOptions1(this)">
<option value="" id="01" selected>...</option>
<option value="werta" id="10">Text Item 1a</option>
<option value="wertb" id="20">Text Item 1b</option>
</select>
<select id="select2" onchange="showOptions2(this)">
<option value="" id="02" selected>...</option>
<option value="wertc" id="30">Text Item 1c</option>
<option value="wertd" id="40">Text Item 1d</option>
</select>
<hr><span id="Image"></span>

How to run a piece of javascript when you select a dropdown option?

I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};

Adding to a HTML text field by clicking items in a multiple select box

I'm wondering if it is possible that when I click on an item in a multiple select box in HTML that it goes into another form box? Basically, when I click on something I want that text to go into a form. I've tried searching, but nothing seems to have an answer.
<form name="input" method="post" action="#">
Display Tag:<input type="text" name="taginput">
<input type="submit" value="Go">
<select name="tags" multiple>
<option value="C#">C#</option>
<option value="Java">Java</option>
<option value="Javascript">Javascript</option>
<option value="PHP">PHP</option>
<option value="Android">Android</option>
<option value="jQuery">jQuery</option>
<option value="C++">C++</option>
<option value="Python">Python</option>
<option value="HTML">HTML</option>
<option value="MySQL">MySQL</option>
</form>
To give an example, when I click on the Java option, I want Java to go into the input box called taginput. If I then click on the Python option, I want Java Python. Is this possible?
This will work, with plain javascript:
var sel = document.getElementsByName ('tags')[0];
sel.onclick = function () {
document.getElementsByName ('taginput')[0].value = this.value;
}
Demo here
A second version avoiding duplicates:
var sel = document.getElementsByName('tags')[0];
var choosen = [];
sel.onclick = function () {
var is_there = !!~choosen.indexOf(this.value);
if(is_there){return false;};
choosen.push(this.value);
document.getElementsByName('taginput')[0].value += this.value + ' ';
}
Demo here
You can do this, it finds the selected options, creates an array of text, then adds it to the text input.
$("select[name=tags]").change(function() {
var arrSelected = $(this).find("option:selected").map(function() {
return $(this).text();
}).get();
$("input[name=taginput]").val(arrSelected);
});
Demo: http://jsfiddle.net/SyAN6/
You can see this fiddle :
http://jsfiddle.net/ppSv4/
$('select option').on('click',function(){
$('#texthere').val( $(this).attr('value') );
});
You can do this using jquery, simply by checking for a change in the multi select box and then adding the newly changed data to the input field.
You can also the jsFiddle http://jsfiddle.net/eUDRV/85/
$("#values").change(function () {
var selectedItem = $("#values option:selected");
$("#txtRight").val( $("#txtRight").val() + selectedItem.text());
});

Populating an input from two drop-downs with Jquery

So I've got an input field that I'm trying to populate using two separate drop-down menus. I've got it working with a single drop-down currently, but I'm unable to do two. Here's an example of what I'm trying to accomplish:
<select type="text" id="make">
<option value="">- select one -</option>
<option value="chevy">Chevy</option>
</select>
<select type="text" id="model">
<option value="">- select one -</option>
<option value="silverado">Silverado</option>
</select>
<input type="text" id="input" value="" />
So the value of the text input should be 'Chevy Silverado' if both fields are selected. Here's the script that I've got so far:
$(function(){
$('select#make').bind('change', function(){
$('input#input').val($(this).val());
});
});
Which works great for one drop down, but obviously does nothing for the other. Any ideas? I've tried a few solutions that I'd found with absolutely no success. Thanks for looking!
Big thanks to those of you who answered my question! With your guidance I was able to get the below code working for me perfectly. Note that I DID add an additional class to my select boxes
$(function(){
var $makemodel = $('.makemodel');
$('.makemodel').on('change',function(){
$('#input').val($makemodel.eq(0).val()+' '+$makemodel.eq(1).val());
});
});
No problem! Please forgive the length of this answer, it offers multiple options depending on whether you place greater importance on code readability vs efficiency. It will only make marginal differences in speed but hopefully it shall inspire you to think of speed in your overall code!
Easy solution:
$('#make,#model').on('change',function(){
$('#input').val($('#make').val()+' '+$('#model').val());
});
More efficient:
Give your selects a class:
<select type="text" id="make" class="MakeModel">
<option value="">- select one -</option>
<option value="chevy">Chevy</option>
</select>
<select type="text" id="model" class="MakeModel">
<option value="">- select one -</option>
<option value="silverado">Silverado</option>
</select>
<input type="text" id="input" value="" />
And then select on the class:
$('.MakeModel').on('change',function(){
$('#input').val($('#make').val()+' '+$('#model').val());
});
Giving it a class just makes it slightly easier for the parser to query only one selector rather than two.
Most efficient:
Use the appropriate .eq() values and caching instead of querying the ID selectors again:
var $makemodel = $('.MakeModel');
$makemodel.on('change',function(){
$('#input').val($makemodel.eq(0).val()+' '+$makemodel.eq(1).val());
});
This means the select items do not need to be requeried since all the objects of .MakeModel are contained within the function under the cached $makemodel and you can just specify the object order number to reference a specific one.
jsFiddle to show what I mean here
Additional notes:
Notice the use of .on rather than .bind, which is the more correct syntax for modern jQuery applications.
Also, using tagnames before ID or class will actually make your selectors less efficient, as the parser needs to verify the ID/class is associated with the tag, rather than just grabbing the ID (which should be unique anyway) or class name (which should be appropriately isolated in its naming).
Simple solution:
$(function() {
$('#make, #model').on('change', function() {
var makeCurr = $('#make').find(":selected");
var madelCurr = $('#model').find(":selected");
var make = (makeCurr.val() != '') ? makeCurr.text() : '';
var model = (madelCurr.val() != '') ? madelCurr.text() : '';
$('input#input').val(make + ' ' + model);
});
});
View Example
I'd suggest amending the HTML somewhat, to group the select elements within a single parent, and binding, using on(), the change event to that element:
<form action="#" method="post">
<fieldset>
<select type="text" id="make">
<option value="">- select one -</option>
<option value="chevy">Chevy</option>
</select>
<select type="text" id="model">
<option value="">- select one -</option>
<option value="silverado">Silverado</option>
</select>
<input type="text" id="input" value="" />
</fieldset>
</form>
With the jQuery:
$('fieldset').on('change', function(){
var self = $(this);
$('#input').val(function(){
return self.find('select').map(function(){ return this.value; }).get().join(' ');
});
});
JS Fiddle demo.
Modifying further, to use a class to identify the summary element (the text-input into which the value will be inserted) reduces the reliance on known elements, and allows for more general-purpose code:
$('fieldset').on('change', function(){
var self = $(this);
self.find('.summary').val(function(){
return self.find('select').map(function(){ return this.value; }).get().join(' ');
});
});
JS Fiddle demo.
And a non-jQuery, plain-JavaScript approach to the same solution (albeit only works in those browsers that support document.querySelector()/document.querySelectorAll() and addEventListener()):
function summarise(container, what, sumClass) {
var els = container.querySelectorAll(what),
sumTo = container.querySelector(sumClass),
vals = [];
for (var i = 0, len = els.length; i < len; i++) {
vals.push(els[i].value);
}
sumTo.value = vals.join(' ').trim();
}
var fieldsets = document.querySelectorAll('fieldset');
for (var i = 0, len = fieldsets.length; i < len; i++) {
fieldsets[i].addEventListener('change', function(){
summarise(this, 'select', '.summary');
}, false);
}
JS Fiddle demo.

Jquery - Grab multiple selections' data in Jquery

This originates from my original question. I'm expanding on it.
Html select options
<select id="1d" name="camp" multiple="multiple">
<option data-url0="week_1" value="Week 1">30th July</option>
<option data-url1="week_2" value="Week 2">6th August</option>
</select>
<input type="hidden" name="camp_url0" id="1e">
<input type="hidden" name="camp_url1" id="1f">
Jquery script I'm struggling with.
$("#1d").on("change", function () {
var url1 = $(this).children(":selected").data("url0");
var url2 = $(this).children(":selected").data("url1");
$("#1e").val(url0);
$("#1f").val(url1);
});
This code works beautifully (maybe not the cleanest?), except for one important issue. Even though it is a multiple selector, whenever both options are selected, only one option is marked as :selected in DOM, meaning only one data-url{row_id} is being inputted. I need both, if both are selected.
I hope that makes sense. Thanks for your help.
UPD:
Add some additional “routing” data to the html
<select id="1d" name="camp" size="5" multiple>
<option data-url="week_1" data-id="1e" value="Week 1">30th July</option>
<option data-url="week_2" data-id="1f" value="Week 2">6th August</option>
</select>
and use it
$("#1d").on("change", function () {
$('input[type=hidden]').val('');
$('option:selected', this).each(function() {
$('#' + $(this).data('id')).val($(this).data('url'))
})
})
http://jsfiddle.net/5ctDC/1/
OLD:
Just .map it and you will get an array with the data.
$('option:selected', this).map(function() {
return $(this).data('url')
})
["week_1", "week_2"]
http://jsfiddle.net/5ctDC/
Go through ALL of the selected elements:
$("#1d").on("change", function () {
var allurl1 = '', allurl2 = '';
$(this).children(":selected").each(function(){
allurl1 += $(this).data("url0");
allurl2 += $(this).data("url1");
});
$("#1e").val(allurl1);
$("#1f").val(allurl2);
});
Working Demo: http://jsfiddle.net/maniator/mtAgS/ (I made the inputs shown so you can visually see what happens)
In an unrelated note, you should'nt be using id that don't start with a letter.

Categories