I am a novice at JavaScript and jQuery. I want to show one combobox-A, which is an HTML <select> with its selected id and contents at the other place on onChange().
How can I pass the complete combobox with its select id, and how can I pass other parameters on fire of the onChange event?
function getComboA(selectObject) {
var value = selectObject.value;
console.log(value);
}
<select id="comboA" onchange="getComboA(this)">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
The above example gets you the selected value of combo box on OnChange event.
Another approach wich can be handy in some situations, is passing the value of the selected <option /> directly to the function like this:
function myFunction(chosen) {
console.log(chosen);
}
<select onChange="myFunction(this.options[this.selectedIndex].value)">
<option value="1">Text 1</option>
<option value="2">Text 2</option>
</select>
For how to do it in jQuery:
<select id="yourid">
<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</select>
<script src="jquery.js"></script>
<script>
$('#yourid').change(function() {
alert('The option with value ' + $(this).val() + ' and text ' + $(this).text() + ' was selected.');
});
</script>
You should also know that Javascript and jQuery are not identical. jQuery is valid JavaScript code, but not all JavaScript is jQuery. You should look up the differences and make sure you are using the appropriate one.
JavaScript Solution
<select id="comboA">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
<script>
document.getElementById("comboA").onchange = function(){
var value = document.getElementById("comboA").value;
};
</script>
or
<script>
document.getElementById("comboA").onchange = function(evt){
var value = evt.target.value;
};
</script>
or
<script>
document.getElementById("comboA").onchange = handleChange;
function handleChange(evt){
var value = evt.target.value;
};
</script>
I found #Piyush's answer helpful, and just to add to it, if you programatically create a select, then there is an important way to get this behavior that may not be obvious. Let's say you have a function and you create a new select:
var changeitem = function (sel) {
console.log(sel.selectedIndex);
}
var newSelect = document.createElement('select');
newSelect.id = 'newselect';
The normal behavior may be to say
newSelect.onchange = changeitem;
But this does not really allow you to specify that argument passed in, so instead you may do this:
newSelect.setAttribute('onchange', 'changeitem(this)');
And you are able to set the parameter. If you do it the first way, then the argument you'll get to your onchange function will be browser dependent. The second way seems to work cross-browser just fine.
jQuery solution
How do I get the text value of a selected option
Select elements typically have two values that you want to access.
First there's the value to be sent to the server, which is easy:
$( "#myselect" ).val();
// => 1
The second is the text value of the select.
For example, using the following select box:
<select id="myselect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:
$( "#myselect option:selected" ).text();
// => "Mr"
See also
.val() jQuery API Documentation
This is helped for me.
For select:
$('select_tags').on('change', function() {
alert( $(this).find(":selected").val() );
});
For radio/checkbox:
$('radio_tags').on('change', function() {
alert( $(this).find(":checked").val() );
});
You can try bellow code
<select onchange="myfunction($(this).val())" id="myId">
</select>
Html template:
<select class="staff-select">
<option value="">All</option>
<option value="196">Ivan</option>
<option value="195">Jon</option>
</select>
Js code:
const $staffSelect = document.querySelector('.staff-select')
$staffSelect.onchange = function () {
console.log(this.value)
}
Just in case someone is looking for a React solution without having to download addition dependancies you could write:
<select onChange={this.changed(this)}>
<option value="Apple">Apple</option>
<option value="Android">Android</option>
</select>
changed(){
return e => {
console.log(e.target.value)
}
}
Make sure to bind the changed() function in the constructor like:
this.changed = this.changed.bind(this);
this code once i write for just explain onChange event of select you can save this code as html and see output it works.and easy to understand for you.
<html>
<head>
<title>Register</title>
</head>
<body>
<script>
function show(){
var option = document.getElementById("category").value;
if(option == "Student")
{
document.getElementById("enroll1").style.display="block";
}
if(option == "Parents")
{
document.getElementById("enroll1").style.display="none";
}
if(option == "Guardians")
{
document.getElementById("enroll1").style.display="none";
}
}
</script>
<form action="#" method="post">
<table>
<tr>
<td><label>Name </label></td>
<td><input type="text" id="name" size=20 maxlength=20 value=""></td>
</tr>
<tr style="display:block;" id="enroll1">
<td><label>Enrollment No. </label></td>
<td><input type="number" id="enroll" style="display:block;" size=20 maxlength=12 value=""></td>
</tr>
<tr>
<td><label>Email </label></td>
<td><input type="email" id="emailadd" size=20 maxlength=25 value=""></td>
</tr>
<tr>
<td><label>Mobile No. </label></td>
<td><input type="number" id="mobile" size=20 maxlength=10 value=""></td>
</tr>
<tr>
<td><label>Address</label></td>
<td><textarea rows="2" cols="20"></textarea></td>
</tr>
<tr >
<td><label>Category</label></td>
<td><select id="category" onchange="show()"> <!--onchange show methos is call-->
<option value="Student">Student</option>
<option value="Parents">Parents</option>
<option value="Guardians">Guardians</option>
</select>
</td>
</tr>
</table><br/>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
function setMyValue(v) {
console.log(v);
}
<select onchange="setMyValue(this.value)">
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select>
This worked for me onchange = setLocation($(this).val())
Here.
#Html.DropDownList("Demo",
new SelectList(ViewBag.locs, "Value", "Text"),
new { Class = "ddlStyle", onchange = "setLocation($(this).val())" });
Simply:
function retrieve(){
alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
function retrieve_other() {
alert(myForm.SMS_recipient.options[document.getElementById('SMS_recipient').selectedIndex].text);
}
function retrieve() { alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
<HTML>
<BODY>
<p>RETRIEVING TEXT IN OPTION OF SELECT </p>
<form name="myForm" action="">
<P>Select:
<select id="SMS_recipient">
<options value='+15121234567'>Andrew</option>
<options value='+15121234568'>Klaus</option>
</select>
</p>
<p>
<!-- Note: Despite the script engine complaining about it the code works!-->
<input type="button" onclick="retrieve()" value="Try it" />
<input type="button" onclick="retrieve_other()" value="Try Form" />
</p>
</form>
</HTML>
</BODY>
Output:
Klaus or Andrew depending on what the selectedIndex is. If you are after the value just replace .text with value. However if it is just the value you are after (not the text in the option) then use document.getElementById('SMS_recipient').value
//html code
<select onchange="get(this)">
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select>
//javscript code
function get(select) {
let value = select.value;
console.log(value);
}
Related
I want to display the value in a "select > option" in an based on the location selected from my tag.
Here is the html:
<select name="stateCoord" id="stateCoord" autocomplete="off">
<option selected="selected">SELECT STATE</option>
<option value="lg">Lagos</option>
<option value="abj">Abuja</option>
</select>
<input type="text" name="stateCoordInfo" value="" id="stateCoordInfo" readonly>
And here is the javascript:
$(document).ready(function() {
$("#stateCoord option").filter(function() {
return $(this).val() == $("#stateCoordInfo").val();
}).attr('selected', true);
$("#stateCoord").live("change", function() {
$("#stateCoordInfo").val($(this).find("option:selected").attr("value"));
});
});
I'm still getting the hang on javascript so a detailed explanation won't hurt. Thanks in advance.
If I assume correctly, you want this:
1) initialization of the select option at document ready, that strange thing the code with filter() was trying to do.
2) Capture the change event on the select and show the value of the current selected option on the input. This is what the live() (deprecated) part was trying to do.
$(document).ready(function()
{
$("#stateCoord").val("").change();
$("#stateCoord").change(function()
{
$("#stateCoordInfo").val($(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="stateCoord" id="stateCoord">
<option value="" selected>SELECT STATE</option>
<option value="lg">Lagos</option>
<option value="abj">Abuja</option>
</select>
<input type="text" name="stateCoordInfo" value="" id="stateCoordInfo">
$(document).ready(function() {
$("body").on("change","#stateCoord",function() {
$("#stateCoordInfo").val($(this).find("option:selected").val());
});
$("#stateCoord").trigger("change");
});
From what I understand, you want to update the text shown in the readonly text box with the value attribute of the selected option from the dropdown.
To do this, you just need to update the val of your read-only text box to the val of the drop-down whenever change event is fired.
$(document).ready(function() {
$('#stateCoord').change(function(e) {
$('#stateCoordInfo').val($(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="stateCoord" id="stateCoord" autocomplete="off">
<option selected="selected">SELECT STATE</option>
<option value="lg">Lagos</option>
<option value="abj">Abuja</option>
</select>
<input type="text" name="stateCoordInfo" value="" id="stateCoordInfo" readonly>
I am not sure, if this is what you need, but I think it should be: JSfiddle
Here is the JS code:
$(document).ready(function() {
$("#stateCoord").change(function() {
var value = $("#stateCoord option:selected").text();
$("#stateCoordInfo").val(value);
});
});
I have researched this through Stack, W3, and others but the solutions that I fiond there don't work. Below is part of my html code, I did my best to try and keep it neat (not an expert by any means).
<select name="ctl00$ContentPlaceHolder1$ddlSearchCriteria" id="ctl00_ContentPlaceHolder1_ddlSearchCriteria" style="width:150px;">
<option value="LastName">Last Name</option>
<option value="FirstName">First Name</option>
<option value="Phone">Phone Number</option>
<option value="Department">Department</option>
<option value="Division">Division</option>
<option value="Location">Location</option>
<option value="Title">Title</option>
<option value="Email">Email Address</option>
<option value="Keywords">Keywords</option>
</select>
<div style="height:10px"></div>
<input name="ctl00$ContentPlaceHolder1$txtSearchString" type="text" id="ctl00_ContentPlaceHolder1_txtSearchString" style="width:160px;">
<button type="button" name="ctl00$ContentPlaceHolder1$Button1" id="ctl00_ContentPlaceHolder1_Button1" style="position: absolute; height:22px; " onclick="myFunction()">Go</button>
<div style="height:5px;"></div>
</td>
<td style="width:48%; height: 27px;"> </td>
</tr>
</tbody>
</table>
</div>
<script>
var GoToURL = 'http://bccportal01/webapps/agency/epdsearch/Search.aspx?op=' + dropDownChoice + '&str=' + inputText;
function myFunction()
{
var dropDownChoice = document.getElementById("ctl00_ContentPlaceHolder1_ddlSearchCriteria").value;
var inputText = document.getElementById("ctl00_ContentPlaceHolder1_txtSearchString").value;
var GoToURL = 'http://bccportal01/webapps/agency/epdsearch/Search.aspx?op=' + dropDownChoice + '&str=' + inputText;
window.open(GoToURL);
}
</script>
I'm trying to make it so that when you click enter the submit button activates. I have tried https://www.w3schools.com/howto/howto_js_trigger_button_enter.asp and Trigger function on Enter keypress as examples.
But this isn't working, all it does is break my code. Not sure if I'm putting it in the wrong spot. I added it right below var inputText in the Function.
You need to add keyup event listener on the input textfield
Add this to your javascript
var input = document.getElementById("ctl00_ContentPlaceHolder1_txtSearchString");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("ctl00_ContentPlaceHolder1_Button1").click();
}
});
Working Example
Replace type="button" with type="submit"
Add a <form onsubmit="myFunction">
Wrap your <select> with the <form>:
<form onsubmit="myFunction">
<select>...</select>
</form>
Here's what your function should do to prevent the form from submitting (we didn't include an "action" so it will submit to itself)
function myFunction(event){
// Stop the form from submitting (default functionality)
event.preventDefault();
...
}
Your code should look similar to this (added a fix for obtaining the select list value the proper way)
<form onsubmit="myFunction">
<select id="mySelect">
<option value="LastName">Last Name</option>
<option value="FirstName">First Name</option>
<option value="Phone">Phone Number</option>
<option value="Department">Department</option>
<option value="Division">Division</option>
<option value="Location">Location</option>
<option value="Title">Title</option>
<option value="Email">Email Address</option>
<option value="Keywords">Keywords</option>
</select>
<input type="text" id="myInput">
</form>
<script type="text/javascript">
function myFunction(event){
// Prevent the form from submitting (default functionality)
event.preventDefault();
var myUrl = "http://bccportal01/webapps/agency/epdsearch/Search.aspx?",
selectEl = document.getElementById('mySelect'),
inputEl = document.getElementById('myInput');
// Append the selected value
myUrl += "op=" + selectEl.options[selectEl.selectedIndex].value;
myUrl += "&str=" + inputEl.value;
window.open(myURL);
}
</script>
I tried to set readonly attribute to second select2 based on value of first select2 option.
I have my script as below:
<select name="Name" id="Name" style='width:45%'>
<option value="1">disable</option>
<option value="2">enable</option>
</select>
<select name="Name2" id="Name2" style='width:45%'>
<option value="d">David</option>
<option value="b">Bob</option>
</select>
My JS script is to set it is like below:
$(document).ready(function(){
$('#Name,#Name2').select2();
$('#Name').change(function(){
var val = $(this).val();
if(val==1)
{
$('#Name2').attr('readonly','readonly');
}else
{
$('#Name2').removeAttr('readonly');
}
})
})
However, the script above won't be working for select2 option but for textbox is fine. (Fiddlejs)
I tried to search some sources here but it did not help.
Thanks.
The above answers are not going to work with the updated versions of select2,
follow the link for the hack
https://stackoverflow.com/a/55001516/9945426
use .prop() to set disabled or not based on the value
$(document).ready(function() {
$('#Name').change(function() {
var val = $(this).val();
$('#Name2').prop('disabled', val == 1);//prop disabled
}).change();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="Name" id="Name" style='width:45%'>
<option value="1">disable</option>
<option value="2">enable</option>
</select>
<select name="Name2" id="Name2" style='width:45%'>
<option value="d">David</option>
<option value="b">Bob</option>
</select>
Use jQuery .prop() method like this
$('#Name2').prop("disabled", true) for disable and
$('#Name2').prop("disabled", false) for enabling select2.
Here is the (Fiddlejs)
I am making a form where when I select familyname of the product, its values will be display in a box (I don't know what I should use todisplay it) and the box can't be edited (only can be read).
-HTML
<select name="fnme" onchange="setText(this)" multiple>
<option value="STR12(12,YU,IO)">STR12(12,YU,IO)</option>
<option value="STR13(13,YU,IO)">STR12(13,YU,IO)</option>
<option value="STR14(14,YU,IO)">STR12(14,YU,IO)</option>
<option value="STR15(15,YU,IO)">STR12(15,YU,IO)</option>
</select>
<td><textarea rows="10" cols="30" name="textBox" id="disabled" value=""/ disabled></textarea></td>
</br>
<p><input type="submit" value="Save"></p>
-ASPCode
<%
DIM fnm,element
fnm=Split(Request("fnme"),"\n")
FOR EACH element IN fnm
Response.Write("<p>--qq-- " & trim(element) & " </p>")
Next
%>
For now I'm using text area but still have a problem in displaying many value, it display on one selected value.
-JS
<script>
function setText(obj) {
var val = obj.value;
document.getElementById('textBox').value = val;
}
</script>
I want to know it is possible to display the multiple value?
When you do:
var val = obj.value;
you're only going to get the value of the first selected option, not all of them (unless you're using something like jQuery).
And the forward slash in:
<textarea ... id="disabled" value=""/ disabled>
doesn't help either. I'll assume that's just a posting typo.
function getMultiSelectValue(select) {
return [].reduce.call(select.options, function(values, option) {
option.selected? values.push(option.value) : null;
return values;
}, []);
}
function showValues(values){
document.getElementById('ta').value = values.join('\n');
}
<select onchange="showValues(getMultiSelectValue(this))" multiple>
<option value="0">0
<option value="1">1
<option value="2">2
</select>
<textarea id="ta" rows="3" readonly></textarea>
I think this could help you.
<html>
<body>
<form action="" name="tof">
<select name="fnme" onchange="setText(this)" multiple>
<option value="STR12(12,YU,IO)">STR12(12,YU,IO)</option>
<option value="STR13(13,YU,IO)">STR12(13,YU,IO)</option>
<option value="STR14(14,YU,IO)">STR12(14,YU,IO)</option>
<option value="STR15(15,YU,IO)">STR12(15,YU,IO)</option>
</select>
<textarea id="res" readOnly></textarea>
</form>
<p id="demo"></p>
<script>
function setText(ob){
var selected_options = document.forms['tof']['fnme'].selectedOptions
var selected_options_values = []
for(i=0; i<selected_options.length; i++){
selected_options_values.push(selected_options[i].value)
}
document.getElementById('res').value = selected_options_values.join('\n')
}
</script>
</body>
</html>
I have an option for users to select if 'Yes' or 'No'. If options selected values 'y' text box 'adv1' displays 750. If else it is 0.00
<table>
<tr>
<td>Advance Required</td>
<td><select name="advReq" id="ad">
<option value="y">Yes</option>
<option value="n">No</option>
</select>
</td>
<td><input name="adv1" type="text" readonly="readonly" value="" /></td>
</tr>
</table>
<script>
function updateText(val) {
var $el = document.getElementById("adv1");
if(val == 'y'){
$el.value = "$ 750";
} else {
$el.value = "0";
}
}
</script>
<select name="advReq" id="ad" onchange="updateText(this.value)">
<option value="y">Yes</option>
<option value="n">No</option>
</select>
<input name="adv1" type="text" id="adv1" value="" />
You can achieve this by using a simple JavaScript.
HTML Markup :
<select name="advReq" id="ad" onchange="changeValue(this.value)">
<option value="y">Yes</option>
<option value="n">No</option>
</select>
<input name="adv1" type="text" id="adv" value="" />
JavaScript :
function changeValue(val){
//use comparison operator
if(val=="y")
document.getElementById('adv').value = "$ 750";
else
document.getElementById('adv').value = "0.00";
}
If you wish to change the value dynamically with values from Server at real time. You can do it by using AJAX calls.