I am trying t create dynamic dropdown using a value of array but values are appending inline in option
<body onload="getdata()">
<select class="form-control" id="focusedinput" name="sBranchName" required>
<option name="sBranchName" id="branch_list" ></option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" ></script>
<script>
function getdata () {
var data =['rajkot','surat','delhi']
var mySelect = $('#branch_list');
for(let value of data){
console.log(value)
mySelect.append("<option>" + value + "</option>")
}
};
</script>
</body>
Can anyone suggest the proper way?
See this line:
mySelect.append("<option>" + value + "<option>")
You're missing a /.
You're also appending to the option rather than to the select. Try selecting the select instead:
$('#focusedinput').append("<option>" + value + "</option>")
function getdata() {
const data = ['rajkot', 'surat', 'delhi']
const mySelect = $('#focusedinput');
data.forEach((value) => {
mySelect.append("<option>" + value + "</option>");
});
}
getdata();
<select class="form-control" id="focusedinput" name="sBranchName" required>
<option name="sBranchName" id="branch_list" ></option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related
I want to read the value selected in a dropdown list using jQuery.
My HTML:
<select id="selectValue">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
My jQuery:
$(document).ready(function () {
var Value = $("#selectValue option:selected").text();
alert(Value);
});
Can anyone tell me what is wrong with my code?
here is a snapp withresult in debbuger
Try val() method:
$(document).ready(function () {
var Value = $("#selectValue").val();
alert(Value);
});
Just try this
$('#yourDropdownId').change(function(){
var selectedid=$('#yourDropdownId').val();
alert(selectedid);
});
Try this
$(document).ready(function () {
var Value = $("#selectValue").find(":selected").text();
alert(Value );
});
$('button').click(function() {
var value = $('#selectValue').val();
var text = $('option[value="' + value + '"]', $('#selectValue')).text();
console.log(value);
console.log(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectValue">
<option value="YesKey">Yes</option>
<option value="NoKey">No</option>
</select>
<button>get selected value</button>
Or you can extend jQuery:
jQuery.fn.extend({
valText: function() {
return jQuery('option[value="' + jQuery(this).val() + '"]', jQuery(this)).text();
}
});
$('button').click(function() {
console.log($('#selectValue').valText());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectValue">
<option value="YesKey">Yes</option>
<option value="NoKey">No</option>
</select>
<button>get selected value</button>
I have this code below. Trying to get the value of selected option but first one give error that test.parent is not a function and second variable get an empty string. How can I make this work?
<select unselectable="on" name="gender">
<option value="Male" unselectable="on">Male</option>
<option value="Female" unselectable="on">Female</option>
</select>
<input value="Submit" onclick="addItem(this)" type="button">
<script>
function addItem(test){
var selected_val1 = test.parent('#gender option:selected').val();
var selected_val2 = $("#gender option:selected").text();
}
</script>
You're passing this to the addItem() function, and caching it as test, and that's not a jQuery object, but a native DOM node.
Then you're doing test.parent('#gender option:selected').val();, but test had no parent method, nor does it have a parent select element.
The select is the previous element, so you should be using prev
$(test).prev('[name="gender"]').find('option:selected').val();
or just
$(test).prev('select').val();
seems easier
var selected_val1 = $(test).parent().find('select[name="gender"] option:selected').val();
Here's an example: http://jsfiddle.net/z96c7025/
Inline JS is not recommended, so I would go with something like:
$('#mybutton').on('click', addItem);
function addItem() {
//in this callback 'this' refers to the button that was clicked and,
//as #adeneo has rightly pointed out, it should be wrapped in $()
var selected_val1 = $(this).prev().val(),
selected_val2 = $(this).prev().find('option:selected').text();
alert( 'value: ' + selected_val1 + ' text: ' + selected_val2 );
}
$('#mybutton').on('click', addItem);
function addItem() {
var selected_val1 = $(this).prev().val(),
selected_val2 = $(this).prev().find('option:selected').text();
alert( 'value: ' + selected_val1 + ' text: ' + selected_val2 );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select unselectable="on" name="gender">
<option value="Male" unselectable="on">Male</option>
<option value="Female" unselectable="on">Female</option>
</select>
<input value="Submit" type="button" id="mybutton">
As others have said, inline JS is not always a good choice, but if you choose to do so, these modifications should help. The javascript can be much, much more simple.
HTML
<form>
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<input value="Submit" onclick="addItem(this.form)" type="button"> </form>
</form>
JS
function addItem(form) {
console.log(form.gender.value)
}
JS Extended
function addItem(form) {
var gender = form.gender;
for ( var i=0; i<gender.length; i++) {
console.log('Option ' + i + ': ' + form.gender[i].value)
}
console.log('Selected option: ' + form.gender.value);
var unselectedIndex = ( form.gender.selectedIndex + (form.length - 1))
console.log('Unselected option: ' + form.gender[unselectedIndex].value)
}
I'm trying to fill a select list with the values entered in an input text box when the user clicks on a button. For eg:
HTML:
<form>
<h2>Add EVENT/MARKET/SELECTION ID </h2>
<select id="id_type">
<option value="sEVENT">Event</option>
<option value="sEVMKT">Market</option>
<option value="sSELCN">Selection</option>
</select>
<input id="entered_id" type="number"/>
<button id="add_id" onclick="populateList()">Add</button>
</form>
<form>
<h2>Entered IDs</h2>
<select id="list_id" size="10" multiple="true"></select>
</form>
JS:
function populateList() {
var events_id = document.getElementById('entered_id').value;
/*I want this events_id to be entered to the select list "list_id"*/
}
I tried $("#list_id").append(events_id) but that didn't work.
Any help is appreciated.
Thanks
since its <select> you need to append <option> tag, as:
$("#list_id").append("<option value='"+events_id+"'>"+events_id+"</option>");
Try FIDDLE
$("#add_id").click(function () {
var value = $("#entered_id").val();
$("#list_id").append("<option value =" + value + " >" + value + "</option>");
});
using JavaScript
var option = document.createElement("option");
option.text = document.getElementById('entered_id').value;
option.value = document.getElementById('entered_id').value;
var select = document.getElementById("list_id");
select.appendChild(option);
Doing everything the jQuery way you can bind a click handler to the button instead of the inline method.
$('#add_id').click(function() {
$('<option/>', { text: this.value }).appendTo('#list_id');
});
i have little problem with ddslike jquery lib
I have two select box like this:
<select id="from">
<option value="1" data-imagesrc="img.png" data-description="USD">Dollar</option>
<option value="2" data-imagesrc="img.png" data-description="EUR">Euro</option>
</select>
<select id="to">
<option value="1" data-imagesrc="img.png" data-description="USD">Dollar</option>
<option value="2" data-imagesrc="img.png" data-description="EUR">Euro</option>
</select>
Javascript of SELECT BOX (Want just the design from ddslike):
<script type="text/javascript">
$(document).ready(function () {
$('#from_fees').ddslick({
width: 100,
});
$('#to_fees').ddslick({
width: 100,
});
});
</script>
Here my script that i wanted to fetch value of select's options:
$(function(){
$("#from").change(function(event){
//alert("Click event on Select has occurred!");
$("option:selected", $(this)).each(function(){
var obj = document.getElementById('from').value;
alert("selected value"+obj);
});
});
});
But i get no results !
I want get the two value from the two select in the same time.
Thank you.
First, you've got to be consistent with your IDs. You've got id="from" in the html, but you call .ddslick() on the element with id "from_fees".
If I understand, you'd like to get the values of each whenever either one changes. How about:
<script>
$('select').change(function(){
var to = $('#to').val();
var from = $('#from').val();
// alert("To: " + to + " and from: " + from + ".");
});
</script>
You don't need to use "this", because you want the value out of both of them.
I have select box with default value,i want to retrieve default value and changed value using javascript,Below is my Html Select box:
<SELECT ID="TEST" NAME="TEST" ONCHANGE="TEST()">
<OPTION ID="1" VALUE="TEST1" SELECTED/>
<OPTION ID="2" VALUE="TEST2"/>
</SELECT>
Regards,
Raj
You can set custom attribute of the element in the onload event of the document:
window.onload = function() {
var oDDL = document.getElementById("TEST");
oDDL.setAttribute("default_value", oDDL.value);
};
Then to read it:
function Test() {
var oDDL = document.getElementById("TEST");
var strCurrentValue = oDDL.value;
var strDefaultValue = oDDL.getAttribute("default_value");
alert("Default value is: " + strDefaultValue + "\n Current value is: " + strCurrentValue);
}
Complete code and test case: http://jsfiddle.net/yahavbr/MbnH7/
Edit: to support more than one drop down, first pass reference in the onchange event like this:
<select id="TEST" name="TEST" onchange="Test(this);">
Then set the custom attribute in a loop:
window.onload = function() {
var arrDDLs = document.getElementsByTagName("select");
for (var i = 0; i < arrDDLs.length; i++) {
var oDDL = arrDDLs[i];
oDDL.setAttribute("default_value", oDDL.value);
}
};
And the test function also need minor change as it's not getting the drop down as argument:
function Test(oDDL) {
var strCurrentValue = oDDL.value;
var strDefaultValue = oDDL.getAttribute("default_value");
alert("Default value is: " + strDefaultValue + "\n Current value is: " + strCurrentValue);
}
Updated test case: http://jsfiddle.net/yahavbr/MbnH7/1/
Edit II: to show the previously selected value some name changes are required, plus storing the value every time it's changing. The onload becomes this:
window.onload = function() {
var arrDDLs = document.getElementsByTagName("select");
for (var i = 0; i < arrDDLs.length; i++) {
var oDDL = arrDDLs[i];
oDDL.setAttribute("previous_value", oDDL.value);
}
};
(Only change is the custom attribute name)
And the function becomes:
function Test(oDDL) {
var strCurrentValue = oDDL.value;
var strPreviousValue = oDDL.getAttribute("previous_value");
alert("Previous value is: " + strPreviousValue + "\n Current value is: " + strCurrentValue);
oDDL.setAttribute("previous_value", strCurrentValue);
}
(Name change plus setting the custom attribute)
Updated and hopefully final test case: http://jsfiddle.net/yahavbr/MbnH7/4/
why not have the onfocus event (vs. onload) store the current value. one solution might be to do something like this:
$(t).data("prev",$(t).val())
and then have the onchange use that:
var oldVal = $(t).data("prev");
thus when someone clicks on, or tabs into, the ui element it stores the current state, and then can use that if there is a resulting change. also it would need to change the value if the change was accepted so that if focus was not changed (ie: they stayed in the pulldown and changed the value again) and they changed their mind and chose another option that the state was preserved.
many of the examples that i have seen of this store state in a that seemed to be vulnerable to change/events elsewhere.
HTML:
<SELECT ID="TEST" NAME="TEST" ONCHANGE="TEST(this)">
<OPTION ID="1" VALUE="TEST1" SELECTED>TEST 1</OPTION>
<OPTION ID="2" VALUE="TEST2">TEST 2</OPTION>
</SELECT>
javascript:
// store currently selected value
var previousValue = document.getElementById('TEST').value;
function TEST(e) {
alert('old value = ' + previousValue);
alert('new value = ' + e.value);
// store new value
previousValue = e.value;
}
example here
EDIT - I answered wrong before - Here's a sample HTML page that does it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>untitled</title>
<script type="text/javascript" language="javascript">
function showOptionValue(oSelect) {
var def;
for (var i=0; i<oSelect.options.length; ++i) //loop through select options
if (oSelect.options[i].defaultSelected){ //this option's defaultSelected property is set to true (from HTML: selected="selected")
def = oSelect[i].text; //or .value
}
var sel;
sel = oSelect[oSelect.selectedIndex].text;
alert (sel + ' : ' + def);
}
function resetSelect(oSelect) {
for (var i=0; i<oSelect.options.length; ++i) //loop through select options
if (oSelect.options[i].defaultSelected) //this option's defaultSelected property is set to true (from HTML: selected="selected")
oSelect.options[i].selected = true; //so, set its selected property to true, selecting it
showOptionValue(oSelect); //reset status
}
</script>
</head>
<body>
<form>
<!-- call handler function, pass Select object (represents drop-down list) -->
<SELECT NAME="cbo" onchange="showOptionValue(this)">
<OPTION VALUE="not_default">Not DEFAULT VALUE</OPTION>
<OPTION VALUE="1">Small</OPTION>
<!-- default value, preselected -->
<OPTION VALUE="2" selected="selected">Medium</OPTION>
<OPTION VALUE="3">Large</OPTION>
</SELECT>
<!-- call handler function, pass Select object using its name as a variable -->
<input type="button" value="Reset Drop-down" onclick="resetSelect(cbo)">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
<script type="text/javascript">
function fn(){
var select = document.getElementById("selectbox");
alert(select.options[select.selectedIndex].value)
}
</script>
</head>
<body>
<header style="margin-left: 50%;">Welcome</header>
<select id="selectbox">
<option value="number 01">Number 01</option>
<option value="number 01">Number 02</option>
<option value="number 01">Number 03</option>
<option value="number 01">Number 04</option>
</select>
<button style="margin-top:10px; margin-left:15px;" onclick="fn()">Click me</button>
</body>
</html>