I have a select form:
<select>
<option value ="one">Label 1</option>
<option value ="two">Label 2</option>
<option value ="three">Label 3</option>
</select>
but I also have some buttons that call the same functions as the select form would
<button class="one">Label 1</button>
<button class="two">Label 2</button>
<button class="three">Label 3</button>
So if I select one of these buttons how could I change the option that shows up in the select form (by that I mean the text that's in the form before you open it up) ?
so if you $("button.three").click(); "Label 3" would show up in the select form
I'm not sure what the function is to change the <select>'s label. I've tried these but they don't work:
$("select").select().val("three");
$("select").find([value="three"]).select();
$("select").selectedIndex = 1;
$("button").on("click", function() {
var selectedClass = $(this).attr("class");
$("option[value="+ selectedClass + "]").attr("selected", true);
});
Try $("select").val("three");
http://api.jquery.com/val/#val-value
This seems to be the simplest solution:
$("button").click(function () {
$('select').val($(this).attr('class'))
});
jsFiddle example
Apparently others beat me to the answer while I was writing a response, but eh... here's a non-jQuery solution. ;)
var buttons = document.getElementsByTagName('button');
var mySelect = document.getElementById('mySelect');
var mySelectOptions = mySelect.getElementsByTagName('option');
for (var i = 0, length = buttons.length; i < length; i++) {
var button = buttons[i];
button.onclick = function(event) {
var text = event.target.innerText;
for (var x = 0, length = mySelectOptions.length; x < length; x++) {
var option = mySelectOptions[x];
if (option.innerText === text) {
mySelect.selectedIndex = x;
return;
}
}
}
}
http://jsfiddle.net/bvaughn/x1chabLa/
Related
I have a select and a list of div elements like this:
<select name="select" id="select">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<button>submit</button>
<div id='list'>
<div><h2>a</h2>0</div>
<div><h2>b</h2>1</div>
<div><h2>c</h2>2</div>
<div><h2>d</h2>3</div>
<div><h2>a</h2>0</div>
<div><h2>b</h2>1</div>
<div><h2>c</h2>2</div>
<div><h2>d</h2>3</div>
</div>
I want to only show the div that has the h2's text that matches the selected value.
I'm trying the following JavaScript loop:
<script>
var select = document.getElementById('select');
var divItems = document.querySelectorAll('#table div');
var h2Items = document.querySelectorAll('#table div h2');
var button = document.querySelector('button');
button.addEventListener('click',function(){
var selectValue = select.value;
for(i=0; i < divItems.length; i++){
var h2Text = h2Items[i].innerHTML;
if (h2Text == selectValue){
divItems[i].display='block';
} else {
divItems[i].display='none';
}
}
});
But it doesn't work.
The console.log show that the h2's text and selected value are all correct,
but I don't know how to control the div's style.
Can somebody help me?
Thanks.
You need to specify that you are updating a style.
divItems[i].display='block'; should be divItems[i].style.display='block';
AND
divItems[i].display='none'; should be divItems[i].style.display='none';
Also, you are targeting #table, but you should be targeting #list since that is the id set on your main div.
Full JS:
<script>
var select = document.getElementById('select');
var divItems = document.querySelectorAll('#list div');
var h2Items = document.querySelectorAll('#list div h2');
var button = document.querySelector('button');
button.addEventListener('click',function(){
var selectValue = select.value;
for(i=0; i < divItems.length; i++){
var h2Text = h2Items[i].innerHTML;
if (h2Text == selectValue){
divItems[i].style.display='block';
} else {
divItems[i].style.display='none';
}
}
});
</script>
I have changed couple of things which I will explain below but first here is the solution which works as expected:
const select = document.getElementById('select');
const divItems = document.querySelectorAll('#list div'); // this was #table
const h2Items = document.querySelectorAll('#list div h2');
const button = document.querySelector('button');
button.addEventListener('click', function() {
const selectValue = select.value;
for(let i = 0; i < divItems.length; i++) {
if (h2Items[i].innerHTML === selectValue){
divItems[i].style = "display:block";
} else {
divItems[i].style = "display:none";
}
}
});
<select name="select" id="select">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<button>submit</button>
<div id="list">
<div><h2>a</h2>0</div>
<div><h2>b</h2>1</div>
<div><h2>c</h2>2</div>
<div><h2>d</h2>3</div>
<div><h2>a</h2>0</div>
<div><h2>b</h2>1</div>
<div><h2>c</h2>2</div>
<div><h2>d</h2>3</div>
</div>
Suggestions:
It is worth to check how HTMLElement.style works please find a link here.
Additionally learn the differences between var, let and const.
Last but not least differences between == and ===.
I hope this helps!
Created a multi-select dropdown, when I click on any of the options I have a input field which stores the values in a textbox. When the page reloads- I want to reselect the values in the multi-select drop down. The text box keeps its values so i was hoping to loop through this if i put it in an array.
E.g. Text contains: "cheese,mozarella"
It is important to only check the items that have the value in the textbox
Jquery:
document.getElementById("txt1").value = "cheese,mozarella";
var data = document.getElementById("txt1").value;
var dataarray = data.split(","); //splits values (,)
console.log(dataarray);
var i;
for (i = 0; i < dataarray.length; i++) {
}
HTML:
<input type="text" runat="server" id="txt1" visible="true" value="0" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="cheese">Cheese</option>
<option value="tomatoes">Tomatoes</option>
<option value="mozarella">Mozzarella</option>
<option value="mushrooms">Mushrooms</option>
<option value="pepperoni">Pepperoni</option>
<option value="onions">Onions</option>
</select>
</div>
I have a codeply to demonstrate: https://www.codeply.com/go/mCcxCM0vHs
My aim is to get some jquery code to loop through a dataarray variable and check the box if the value exists and tick it.
This function receives a select and a value and will cycle through the select's options, compare to the given value and mark matching options as selected.
function prepopulateOptions(selectElement, value) {
var options = selectElement.options;
for (var i = 0, numberOfOptions = options.length; i < numberOfOptions; i++) {
if (options[i].value == value) {
options[i].selected = true;
}
}
}
This function clears all selected options.
function clearSelect(selectElement) {
var options = selectElement.options;
for (var i = 0, numberOfOptions = options.length; i < numberOfOptions; i++) {
options[i].selected = false;
}
}
Then tweak your script:
var data = "cheese,mozarella",
dataarray = data.split(","),
selectElement = document.getElementById('basic');
// clear select first
clearSelect(selectElement);
for (var i = 0; i < dataarray.length; i++) {
prepopulateOptions(selectElement, dataarray[i]);
}
Check the fiddle
With jQuery this could be rewritten even easier:
https://jsfiddle.net/rtm0n53b/
Use the localStorage and jQuery.
<script type="text/javascript">
function fnLoadOptions(text){
//--clear selection
$('#basic option').prop("selected", false);
//--load selection
text = text||'';
var items = text.split(',');
for(var i in items) {
$('#basic option[value="'+items[i]+'"]').prop("selected", true);
}
if($.fn.multiselect!=null) {
$('#basic').multiselect('refresh'); //--if using the bootstrap multiselect plugin, then refresh it.
}
}
var key = 'checkedOptions';
//--load previous selection
var previousSelection = localStorage.getItem(key);
fnLoadOptions(previousSelection);
$("#txt1").val(previousSelection);
//--bind to new selection
$('#basic').change(function () {
var v = $('#basic').val();
$("#txt1").val(v);
localStorage.setItem(key,v);
});
$('#txt1').bind("keyup change",function () {
fnLoadOptions($(this).val());
});
</script>
I recently trying to make a form with multiple select box. When someone select the options the number of selected options will be display on another text. I'm a beginner in JavaScript.
The function is called, but it doesn't count the number of the selected options.
<select name="element_17_1[ ]"
size="7" multiple="multiple"
class="element select medium"
id="element_17_1[ ]"
onfocus="selectCount(this.form);"
onClick="selectCount(this.form);"
>
<option value="Opt1">Opt1</option>
<option value="Opt2">Opt2</option>
<option value="Opt3">Opt3</option>
<option value="Opt4">Opt4</option>
<option value="Opt5">Opt5</option>
<option value="Opt6">Opt6</option>
<option value="Opt7">Opt7</option>
</select>
and this is the function I tried in the <head>
function selectCount(f) {
var selObj = myForm.elements['element_17_1[]'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
if (selObj.options[i].selected) {
totalChecked++;
}
}
f.element_9.value = totalChecked;
}
You're trying to get an element named element_17_1[], but your select box is named element_17_1[ ]. JavaScript just sees the name as a bunch of characters, and that space makes a difference.
In your HTML you have:
> <select name="element_17_1[ ]"
> size="7" multiple="multiple"
> class="element select medium"
> id="element_17_1[ ]"
> onfocus="selectCount(this.form);"
> onClick="selectCount(this.form);"
> >
Note that in the listener, this references the element itself, so just pass that:
onfocus="selectCount(this);"
onClick="selectCount(this);"
So a reference to the element is passed directly to the function, which can be:
function selectCount(selObj) {
// The following line isn't needed now
// var selObj = myForm.elements['element_17_1[]'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
totalChecked += selObj.options[i].selected? 1 : 0;
}
// The next line needs the form, so
selObj.form.element_9.value = totalChecked;
}
Now you don't care what the select element is called. :-)
Edit
To click element_9 you might do:
<input name="element_9" onclick="
this.value = selectCount(this.form['element_17_1[ ]']);
">
Then the function is modified to:
function selectCount(selObj) {
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
totalChecked += selObj.options[i].selected? 1 : 0;
}
return totalChecked;
}
Enough homework for now. ;-)
Change your select's name name="element_17_1"and id id="element_17_1" and in also you don't have myForm in your function so var selObj = myForm.elements['element_17_1']; should be var selObj = f.elements['element_17_1']; and also you can use only on event as follows
onChange="selectCount(this.form);"
instead of
onfocus="selectCount(this.form);"
onClick="selectCount(this.form);"
Complete function:
function selectCount(f) {
var selObj = f.elements['element_17_1'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
if (selObj.options[i].selected) {
totalChecked++;
}
}
f.element_9.value = totalChecked;
}
Update:
For your php scriptyou can keep your select's name name="element_17_1[]" and so in the function it should be var selObj = f.elements['element_17_1[]']; but without space like[ ]
DEMO.
I have a select dropdownlist with 1 item selected at page load in html.
<select name = "options">
<option value = "1">Item1</option>
<option value = "2" selected>Item2</option>
<option value = "3">Item3</option>
<option value = "4">Item4</option>
</select>
Now I want to capture new select option when user press shift and select another option such as "Item 3".
I have the following code to find all the selections in the list
var value = "";
for (var intLoop = 0; intLoop < Form.elements[index].length; intLoop++) {
if(Form.elements[index][intLoop].selected )
value = value + Form.elements[index][intLoop].value;
}
I can see the "Item 2" and "Item 3" are selected but i want to get capture "Item 3" only. Is it possible?
Here's code that will tell you what has been selected and what has been deselected http://jsfiddle.net/8dWzB/
It uses Array.prototype.indexOf, and it's not the fastest way to do it. But it should get you going in the right direction.
HTML
<select id="options" multiple="multiple">
<option value = "1">Item1</option>
<option value = "2" selected>Item2</option>
<option value = "3">Item3</option>
<option value = "4">Item4</option>
</select>
JS
function getSelectedIndexes(select) {
var selected = [];
for (var i = 0; i < select.options.length; i++) {
if(select.options[i].selected ) {
selected.push(i);
}
}
return selected;
}
var select = document.getElementById("options");
var prevSelected = getSelectedIndexes(select);
select.onchange = function(e) {
var currentlySelected = getSelectedIndexes(this);
for (var i =0; i < currentlySelected.length; i++) {
if (prevSelected.indexOf(currentlySelected[i]) == -1) {
console.log("Added to selection ", this.options[currentlySelected[i]].text);
}
}
for (var i =0; i < prevSelected.length; i++) {
if (currentlySelected.indexOf(prevSelected[i]) == -1) {
console.log("Removed from selection ", this.options[prevSelected[i]].text);
}
}
prevSelected = currentlySelected;
};
If you really only want to know which item was last clicked, you can use the following code. I'll use jQuery so I can easily set a handler on all the option objects. Remember this won't work if you change the selection with the keyboard
$('option').click(function(e){
var parentNode = this.parentNode;
for (var i=0; i < this.parentNode.options.length; i++) {
if (parentNode.options[i] == this) {
console.log('Clicked item with index', i);
break;
}
}
});
You could check the value of the selected options before a change event (e.g. item 1 and 2 are selected) and then again after the event (e.g. item 1, 2 and 3 are selected), and compare the difference.
Here is an example.
Fiddle here: http://jsfiddle.net/FnAuz/4/
I modified your select to allow multiple selections since I take it that's the crux of the problem.
HTML:
<form id="my-form">
<select name = "options" id="options" multiple>
<option value = "val1">Item1</option>
<option value = "val2">Item2</option>
<option value = "val3">Item3</option>
<option value = "val4">Item4</option>
</select>
</form>
JS:
var oldValue = "";
document.getElementById('options').onchange = function() {
var myForm = document.getElementById ('my-form');
var value = "";
for (var intLoop = 0; intLoop < myForm.elements[0].length; intLoop++) {
if(myForm.elements[0][intLoop].selected) {
value = value + myForm.elements[0][intLoop].value;
}
}
for (var intLoop = 0; intLoop < myForm.elements[0].length; intLoop++) {
var optionVal = myForm.elements[0][intLoop].value;
if(myForm.elements[0][intLoop].selected && value.indexOf(optionVal) !== -1 && oldValue.indexOf(optionVal) === -1) {
console.log('Last clicked was ' + myForm.elements[0][intLoop].value)
}
}
oldValue = value;
};
EDIT: I just noticed that my example works when the user makes command/ctrl selections, but if they make a shift selection then ALL the new values will be counted as the 'last clicked item'. So my code would need some work to account for this scenario. I'm out of time, but hopefully my code is useful in its current state nevertheless!
Try this :
var e = document.getElementById("ID_of_Select_Element");
var _selectedValue= e.options[e.selectedIndex].value;
It started looking messy so I'm posting it as an answer:
<html>
<head>
<script type="text/javascript">
<!--
var value = '0';
document.getElementById('options').onchange = function() {
value = parseInt(value) + parseInt(this.value);
alert(value);
}
-->
</script>
</head>
<body>
<select name="options" id="options">
<option value = "1">Item1</option>
<option value = "2" selected>Item2</option>
<option value = "4">Item3</option>
<option value = "8">Item4</option>
</select>
</body>
</html>
Edition for selecting multiple items:
well, if you want to accumulate items you can assign binary IDs to each product and then you can extract all the selected products from the total. for example, if the total is: 7 you can easily translate it to a binary string "111" which means they selected items 1,2,4. Sounds a bit crazy, I know, just an idea ;)
I am trying to make auto complete to select option according to input from the user
something like
<input type=text onkeyup=findit()>
<select id="sel">
<option value="s0001">Adams</option>
<option value="s0002">Alder</option>
.
.
.
<select>
I found this code 'but it only work on one select in the page( I need multi select)
<html>
<head>
<script type="text/javascript">
//initialize some global variables
var list = null;
function fillit(sel,fld) {
var field = document.getElementById("entry");
var selobj = document.getElementById("sel");
if(!list)
{
var len = selobj.options.length;
field.value = "";
list = new Array();
for(var i = 0;i < len;i++)
{
list[i] = new Object();
list[i]["text"] = selobj.options[i].text;
list[i]["value"] = selobj.options[i].value;
}
}
else
{
var op = document.createElement("option");
var tmp = null;
for(var i = 0;i < list.length;i++)
{
tmp = op.cloneNode(true);
tmp.appendChild(document.createTextNode(list[i]["text"]));
tmp.setAttribute("value",list[i]["value"]);
selobj.appendChild(tmp)/*;*/
}
}
}
function findIt(sel,field)
{
var selobj = document.getElementById("sel");
var d = document.getElementById("display");
var len = list.length;
if(field.value.length > 1)
{
if(!list)
{
fillit(sel,field);
}
var op = document.createElement("option");
selobj.options.length = 1
var reg = new RegExp(field.value,"i");
var tmp = null;
var count = 0;
var msg = "";
for(var i = 0;i < len;i++)
{
if(reg.test(list[i].text))
{
// d.childNodes[0].nodeValue = msg;
tmp = op.cloneNode(true);
tmp.setAttribute("value",list[i].value);
tmp.appendChild(document.createTextNode(list[i].text));
selobj.appendChild(tmp);
}
}
}
else if(list && len > selobj.options.length)
{
selobj.selectedIndex = 0;
fillit(sel,field);
}
}
</script>
</head>
<body onLoad="fillit(sel,entry)">
<div>Enter the first three letters of a street and select a match from the menu.</div>
<form>
Street
<input type="text" name="Street" id="entry" onKeyUp="findIt(sel,this)"><br>
<select id="sel">
<option value="s0001">Adams</option>
<option value="s0002">Alder</option>
<option value="s0003">bol</option>
<option value="s0004">col</option>
<option value="s0005">dol</option>
<option value="s0007">Cooper</option>
<!--and so on and so forth-->
</select>
</form>
</body>
Any Ideas How to make it work on multi select on the page?
Thanks
Baaroz
Not sure if this would work for you, but chosen.js has a really nice autocomple multi select
http://harvesthq.github.com/chosen/
Usually Autocomplete is for single values, but the jQuery UI autocomplete does have a multiple select function. Perhaps try that? Minimum effort coding for you that way.
An odd way to do that is to change the ID in the script and copy it the number of times you want to use this options in the page. so for example:
select id="sel1"
select id="sel2"
select id="sel3"
and then. copy the script and replace every (sel) with sel1 past it again and replace (sel) with sel2 and so on.
not the best solution but it will work.
Good Luck