How to change "size" of select when click on select? - javascript

sorry for my bad english, i have a problem with select :
<form name="reg" style="width:700px;" action="#" method="post">
<p align="center">
<select onChange="reg(this.options[this.selectedIndex].value)" size="1">
<option selected value="250">Select the Reg</option>
<option value="0">Reg 1</option>
<option value="1">Reg 2</option>
<option value="2">Reg 3</option>
<option value="3">Reg 4</option>
<option value="4">Reg 5</option>
<option value="5">Reg 6</option>
<option value="6">Reg 7</option>
<option value="7">Reg 8</option>
<option value="8">Reg 9</option>
<option value="9">Reg 10</option>
</select>
</p>
</form>
I would like that when i click on select, the size of select changes in size="5", because when the document load the size is size="1" (and this is good) but if i click on select, it shows all ten options, and this is the problem...
While, if i click on select, the size changes, is most beautiful.
EDIT
In future the form could have more 250 options, so is important that when the document load size is 1, and when i click the size is 5 ....
the size must be "5" only when the select show options, and when an option is selected the size must be 1.
The problem is that i don't know how made it, maybe with jquery? or only with css?
Can you help me?
Thanks!

Here is a working solution for your problem:
add focus event handler to the select list with id='selRegs'
set the size attribute to 6 (5 will show 4 options + the "Select the Reg" option)
after option is changed the size will be reset to 1
remove focus from select
https://jsfiddle.net/juaxo8zm/8/
$(document).ready(function () {
var initPos = $("#yourDiv").position();
console.log("init: ");
console.log(initPos);
$('#selRegs').focus(function () {
$('#selRegs').attr("size", "6");
$("#yourDiv").css({
position: "absolute",
top: initPos.top,
left: initPos.left
});
});
$('#selRegs').change(function () {
console.log("selected");
$('#selRegs').attr("size", "1");
$("#selRegs").blur();
$("#yourDiv").css({
position: "static"
});
});
});
I use jQuery for this:
.change()
.focus()
.attr(param1, param2)
.blur()
.position()

Try this:
<select size="1"
onfocus='this.size=5;'
onblur='this.size=1;'
onchange='this.size=1; this.blur();'
>

Use the HTML onclick="myFunction()" event tag from the HTML select tag, or use jQuery click() handler if you want to declare the event handler at the javascript level (I mean if you want add the additional event from javascript).
I mean you have a choice - add the extra event dispatch code in the HTML tag source code or add it from the javascript/jQuery level.
The problem is that onChange() event dispatch doesn't get called until too late for your need (it gets called after a user selects a value).
You need to get notified the moment the button for the drop-down menu is clicked so you can change the selected value (default) value.
In your click function handler change the selectedIndex property and set it to the the index of the line that contains "5"

You should use click event on select
$('select').on('click',function(){
$(this).attr('size',5)
});

Just use javascript :
<select id='sel' onfocus='changesize();' onchange='changesize2();' size='1'>
<option selected value="250">Select the Reg</option>
<option value="0">Reg 1</option>
<option value="1">Reg 2</option>
<option value="2">Reg 3</option>
<option value="3">Reg 4</option>
<option value="4">Reg 5</option>
<option value="5">Reg 6</option>
<option value="6">Reg 7</option>
<option value="7">Reg 8</option>
<option value="8">Reg 9</option>
<option value="9">Reg 10</option>
</select>
<script>
function changesize(){
document.getElementById('sel').size = '5';
}
function changesize2(){
document.getElementById('sel').size = '1';
document.getElementById('sel').blur();
}
</script>
Demo : http://codepen.io/anon/pen/zxbRZb

Related

How can i put an option value in a input text after clicking a button?

I'm not familiar with javascript and jQuery and I'm asking you.
I would like the code of a product to be selected, once I have selected it from the select dropdown, I click the button and it should add the value in an input box text, that I have created, so that I can also accumulate more codes of more products.
Keep in mind that once the button is clicked, the same value is no longer added indefinitely but that it is possible to choose another code and add it next to the one already present in the input text.
I don't know if it is more practical to use the <input type = "submit"> tag instead of the button tag to send or in this case transfer the selected text from the select to a text form.
You would save my life if you could please complete this action for me with javascript or jQuery :)
<select class="select" id="select-code">
<option value="">Select a code</option>
<option value="value1">Code 1</option>
<option value="value2">Code 2</option>
<option value="value3">Code 3</option>
<option value="value4">Code 4</option>
</select>
<button id="code-btn">submit to form</button>
<input name="my-quote" type="text" placeholder="code1,code2...">
First of all, it seems that you are complete beginner. so you should learn DOM api to learn how to manipulate the window.
Anyway here is the code to do so which you want;
document.getElementById('code-btn').onclick = () => {
let e = document.getElementById('select-code');
document.getElementById('input').value = e.options[e.selectedIndex].text;
}
<select class="select" id="select-code">
<option value="">Select a code</option>
<option value="value1">Code 1</option>
<option value="value2">Code 2</option>
<option value="value3">Code 3</option>
<option value="value4">Code 4</option>
</select>
<button id="code-btn">submit to form</button>
<input id='input' name="my-quote" type="text" placeholder="code1,code2...">
document.getElementById('code-btn') gets the element with id 'code-btn'. As that is a button, we can use onclick property which will will take a function and that function will be called when it is clicked.
Inside that function, i am simply getting the input field and setting its value to the text of the selected option from dropdown.
I think the code here is self-documented.
This isn't a direct answer to your question, but an alternative solution. If possible for your situation, I would consider using <select multiple>: the select tag with the "multiple" attribute. It's a native HTML feature that allows the user to select multiple options from the list. I don't know how you're submitting the form data, but if using a <form> tag then the form's data will include which values have been selected.
Tutorial about select multiple
<label for="select-code">Select a code</label>
<select class="select" id="select-code" multiple>
<option value="value1">Code 1</option>
<option value="value2">Code 2</option>
<option value="value3">Code 3</option>
<option value="value4">Code 4</option>
</select>
<button id="code-btn">submit to form</button>
<input id='input' name="my-quote" type="text" placeholder="code1,code2...">
This is actually very simple and might be used as beginers excercise, so I'm gonna give you a brief walkthrough of how I would solve it:
register button onClick event
read selected value
add it to the placeholder attribute
so something like this (not tested at all)
//button click event
$("#code-btn").click(function (event) {
//in element #select-code
var textToAdd = $('#select-code')
//find element with pseudo selector :selected
.find(":selected")
//get its inner text
.text();
//check if input already contains the text here, if not
if (!$("input").attr("placeholder").includes(textToAdd)) {
//into input element
$("input")
//into attribute placehoder
.attr("placeholder",
//insert original text //insert colon //insert new text
$("input").attr("placeholder") + ", " + textToAdd)
}
});
function myFunction() {
var newText = document.getElementById('select-code').value
var input = document.getElementById('my-quote')
if (input.value == '') input.value = newText
else input.value = input.value + ', ' + newText
}
<select class="select" id="select-code" onchange='myFunction()'>
<option value="">Select a code</option>
<option value="Code 1">Code 1</option>
<option value="Code 2">Code 2</option>
<option value="Code 3">Code 3</option>
<option value="Code 4">Code 4</option>
</select>
<button id="code-btn">submit to form</button>
<input id="my-quote" type="text" placeholder="code1,code2...">

preventDefault() not working on a particular option select

I have this <select> list that takes different options and reroutes based on the one clicked. The html code is:
<select id="pageSelect" name="Choose Page" onchange="location = this.value">
<option value='' disabled selected hidden>Choose Page</option>
<option value='/page-1'>Page 1</option>
<option value='/page-2'>Page 2</option>
<option value="allPages" >Custom Page</option>
</select>
The rerouting of the first 2 pages work as expected. However, the third option is going to be handled using a custom Javascript function instead of being handled by the onchange function declared at the <select> element.
The custom function for the last <option> is:
$('#pageSelect').change(function(event) {
event.preventDefault()
var pagesvalueselect = $(this).val();
if(pagesvalueselect=="allPages"){
$('#siteSaleModal').modal("show"); //Open Modal
}
});
The function works and when a user clicks on the last option, it triggers the modal to pop up but it still redirects the user to another page based on value="allPages" even though I am using the preventDefault() function.
The preventDefault() call only stops the current change event handler. The one you've assigned via the onchange attribute will still run regardless as it's entirely separate.
To fix this, and improve your code, remove the onchange attribute (as they are outdated and now considered bad practice) and combine them in to one unobtrusive event handler.
$('#pageSelect').change(function(event) {
event.preventDefault()
var pagesvalueselect = $(this).val();
if (pagesvalueselect == "allPages") {
console.log('open modal...');
//$('#siteSaleModal').modal("show"); //Open Modal
} else {
console.log('redirecting to ' + pagesvalueselect + '...');
//window.location.assign(pagesvalueselect);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="pageSelect" name="Choose Page">
<option value="" disabled="true" selected="true" hidden>Choose Page</option>
<option value="/page-1">Page 1</option>
<option value="/page-2">Page 2</option>
<option value="allPages">Custom Page</option>
</select>
Your code code works fine without event.preventDefault() and onchange attribute.
<select id="pageSelect" name="Choose Page">
<option value='' disabled selected hidden>Choose Page</option>
<option value='/page-1'>Page 1</option>
<option value='/page-2'>Page 2</option>
<option value="allPages" >Custom Page</option>
</select>
$('#pageSelect').change(function(event) {
var pagesvalueselect = $(this).val();
if(pagesvalueselect=="allPages"){
$('#siteSaleModal').modal("show"); //Open Modal
} else {
location = pagesvalueselect;
}
});
Codepen

How to use getElementByID in JavaScript to connect to my HTML drop down box?

I have a drop-down box in HTML showing three options. I am also using javaScript and want to use the getElementById tool to connect the two. However, I only have one ID for the drop-down box. How does javascript recognize that I have three different options?
There's actually a demo on w3schools.com showing exactly what you're asking. To get the number of options, you could do something like
document.getElementById("mySelect").options.length
Here is an example of how to retrieve the value of a dropdown: https://jsfiddle.net/ykcwgnm8/
You use getElementBy* functions to get the element, however value attribute denotes which item is currently selected.
HTML:
<select id="dropdown">
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third option</option>
</select>
JS:
function onChangeHandler(e)
{
alert("you have selected item with value "+this.value);
}
document.getElementById("dropdown").addEventListener("change", onChangeHandler);
You can listen for change like this
var list = document.getElementById("mySelect")
list.addEventListener('change', function(e){
console.log(e.target.selectedIndex)
console.log(e.target.options[e.target.selectedIndex].text)
})
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
You can do something like this, here is an example:-
html
<select id="selectBox">
<option value="1">option 1</option>
<option value="2" selected="selected">option 2</option>
<option value="3">option 3</option>
</select>
js
var e = document.getElementById("selectBox");
var selectedValue = e.options[e.selectedIndex].value;
// this will give selectedValue as 2
Hope you find this useful!!

Change "value" of combobox option JS

So, as the title says I want to change the value of a certain option using JS. I have already looked for it but every answer refers to changing the selected option not the value of a specifical option.
<select class="form-control">
<option value="0" selected>Ver</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
I want to change "Ver" option value from 0 to 1. I don´t know if it is possible but thanks in advance.
Have you tried assigning it an id and then changing it in your js file?
Something like this:
<option value='0' id='opt1' selected>Ver</option>
and in javascript:
document.getElementById("opt1").value = "1";
You can select the option with value 0 using
let opt = document.querySelector('select.form-control option[value="0"]')
You can then change the value by reassigning it
opt.setAttribute('value', '1')
If you have more than one select with class form-control this could be a problem, and you might want to give it/them a unique id — then the selector would be
let opt = document.querySelector('select#your-id option[value="0"]')
Here is a stack snippet doing this, where I've combined the select and the assignment into a single statement. I've also added a change event listener to show the value in the console, so if you switch to 20 then switch to Ver again it would print 20 and then 1 to the console, showing you that the value is indeed 1, not 0
document.querySelector('select.form-control')
.addEventListener('change', function(e) {
console.log(this.value);
});
document.querySelector('select.form-control option[value="0"]')
.setAttribute('value', '1');
select {
min-width: 10em;
}
<select class="form-control">
<option value="0" selected>Ver</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
Hello you can assign the value with the following instruction
$("#SelectID").val("value option");
document.getElementById("SelectID").value = "value option";
reference in this url Set value of combobox or select

JQuery - how to select dropdown item based on value

I want set a dropdown(select) to be change based on the value of the entries.
I have
<select id="mySelect">
<option value="ps">Please Select</option>
<option value="ab">Fred</option>
<option value="fg">George</option>
<option value="ac">Dave</option>
</select>
And I know that I want to change the dropdown so that the option with the value of "fg" is selected. How can I do this with JQuery?
You should use
$('#dropdownid').val('selectedvalue');
Here's an example:
$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
<option value=''>- Please choose -</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='selectedvalue'>There we go!</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
$('#yourdropddownid').val('fg');
Optionally,
$('select>option:eq(3)').attr('selected', true);
where 3 is the index of the option you want.
Live Demo
$('#mySelect').val('fg');...........
$('#mySelect').val('ab').change();
// or
$('#mySelect').val('ab').trigger("change");
You can use this jQuery code which I find it eaiser to use:
$('#your_id [value=3]').attr('selected', 'true');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="your_id" name="name" class="form-control input-md">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
<option value="3">Option #3</option>
<option value="4">Option #4</option>
<option value="5">Option #5</option>
<option value="6">Option #6</option>
<option value="7">Option #7</option>
</select>
You can simply use:
$('#select_id').val('fg')
In your case $("#mySelect").val("fg") :)
May be too late to answer, but at least some one will get help.
You can try two options:
This is the result when you want to assign based on index value, where '0' is Index.
$('#mySelect').prop('selectedIndex', 0);
don't use 'attr' since it is deprecated with latest jquery.
When you want to select based on option value then choose this :
$('#mySelect').val('fg');
where 'fg' is the option value
$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
<option value=''>- Please choose -</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='selectedvalue'>There we go!</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
This code worked for me:
$(function() {
$('[id=mycolors] option').filter(function() {
return ($(this).text() == 'Green'); //To select Green
}).prop('selected', true);
});
With this HTML select list:
<select id="mycolors">
<option value="1">Red</option>
<option value="2">Green</option>
<option value="3">Blue</option>
</select>
I have a different situation, where the drop down list values are already hard coded. There are only 12 districts so the jQuery Autocomplete UI control isn't populated by code.
The solution is much easier. Because I had to wade through other posts where it was assumed the control was being dynamically loaded, wasn't finding what I needed and then finally figured it out.
So where you have HTML as below, setting the selected index is set like this, note the -input part, which is in addition to the drop down id:
$('#project-locationSearch-dist-input').val('1');
<label id="lblDistDDL" for="project-locationSearch-input-dist" title="Select a district to populate SPNs and PIDs or enter a known SPN or PID." class="control-label">District</label>
<select id="project-locationSearch-dist" data-tabindex="1">
<option id="optDistrictOne" value="01">1</option>
<option id="optDistrictTwo" value="02">2</option>
<option id="optDistrictThree" value="03">3</option>
<option id="optDistrictFour" value="04">4</option>
<option id="optDistrictFive" value="05">5</option>
<option id="optDistrictSix" value="06">6</option>
<option id="optDistrictSeven" value="07">7</option>
<option id="optDistrictEight" value="08">8</option>
<option id="optDistrictNine" value="09">9</option>
<option id="optDistrictTen" value="10">10</option>
<option id="optDistrictEleven" value="11">11</option>
<option id="optDistrictTwelve" value="12">12</option>
</select>
Something else figured out about the Autocomplete control is how to properly disable/empty it. We have 3 controls working together, 2 of them mutually exclusive:
//SPN
spnDDL.combobox({
select: function (event, ui) {
var spnVal = spnDDL.val();
//fire search event
$('#project-locationSearch-pid-input').val('');
$('#project-locationSearch-pid-input').prop('disabled', true);
pidDDL.empty(); //empty the pid list
}
});
//get the labels so we have their tool tips to hand.
//this way we don't set id values on each label
spnDDL.siblings('label').tooltip();
//PID
pidDDL.combobox({
select: function (event, ui) {
var pidVal = pidDDL.val();
//fire search event
$('#project-locationSearch-spn-input').val('');
$('#project-locationSearch-spn-input').prop('disabled', true);
spnDDL.empty(); //empty the spn list
}
});
Some of this is beyond the scope of the post and I don't know where to put it exactly. Since this is very helpful and took some time to figure out, it's being shared.
Und Also ... to enable a control like this, it's (disabled, false) and NOT (enabled, true) -- that also took a bit of time to figure out. :)
The only other thing to note, much in addition to the post, is:
/*
Note, when working with the jQuery Autocomplete UI control,
the xxx-input control is a text input created at the time a selection
from the drop down is picked. Thus, it's created at that point in time
and its value must be picked fresh. Can't be put into a var and re-used
like the drop down list part of the UI control. So you get spnDDL.empty()
where spnDDL is a var created like var spnDDL = $('#spnDDL); But you can't
do this with the input part of the control. Winded explanation, yes. That's how
I have to do my notes or 6 months from now I won't know what a short hand note means
at all. :)
*/
//district
$('#project-locationSearch-dist').combobox({
select: function (event, ui) {
//enable spn and pid drop downs
$('#project-locationSearch-pid-input').prop('disabled', false);
$('#project-locationSearch-spn-input').prop('disabled', false);
//clear them of old values
pidDDL.empty();
spnDDL.empty();
//get new values
GetSPNsByDistrict(districtDDL.val());
GetPIDsByDistrict(districtDDL.val());
}
});
All shared because it took too long to learn these things on the fly. Hope this is helpful.
You can select dropdown option value by name
// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
$('select#myselect option[value="ab"]')
either can be used to get the selected option value
$('#dropdownID').on('change', function () {
var dropdownselected=$("#dropdownID option:selected").val();
});
or
$('#dropdownID').on('change', function () {
var dropdownselected=this.selectedOptions[0].value;
});

Categories

Resources