I'm trying to show a child element property from 'select' tag and I using document.getElementsByTagName command to do that, the display that I expect is 'john dalton' look source bellow!, but browser not display as I expect just undefined message in alert. my source like this:
<select style="" name="provinsi_id" class="form-control crud-edit
lookup-refresh" onchange="showoption();">
<option>john dalton</option>
<option>john rambo</option>
<script>
alert(document.getElementsByTagName('select')[0].childNodes[0].value);
<script>
try this,
alert(document.getElementsByTagName('select')[0].childNodes[1].value);
0th element is a text element.
Note: Whitespace inside elements is considered as text, and text is considered as nodes. Comments are also considered as nodes.
When you have a <select> you can access to the options easily.
document.getElementsByTagName('select')[0].options
The "options" is an array of all the options in your select, so you can acces to your value this way:
document.getElementsByTagName('select')[0].options[0].value
You also have a shortcut by doing this:
document.getElementsByTagName('select')[0][0].value
every answer runing well, if I write static code as Nannakuhtum's sample, unfortunately in my case I use javascript to fill option value dynamicly like this,
<html>
--------
<select style="" name="provinsi_id"
class="form-control crud-edit
lookup-refresh" onchange="tampilkota();">
</select>
------------
</html>
<script>
var dataprovinsi = <?php echo json_encode($dataprovinsi); ?>;
for (i=0; i< dataprovinsi.length; i++){
var option = document.createElement("option");
option.text = dataprovinsi[i]['nama'];
option.value = dataprovinsi[i]['nama'];
var select = document.getElementById("psg_provinsi_id");
select.appendChild(option);
}
function tampilkota(){
alert(document.getElementsByTagName('select')[0].childNodes[1].value);
}
Related
I'm trying to create a string variable to append on a multiselect with jquery.
This is the fiddle example: https://jsfiddle.net/o2gxgz9r/47084/
$(document).ready(function() {
var group = "<optgroup></optgroup>";
$(group).attr("value", 1);
$(group).attr("label", "test group");
var t = "<option></option>";
$(t).attr("value", 4);
$(t).text("Test option");
$(t).attr("selected", true);
$(group).append(t);
$("#a").html(group);
});
body {
padding: 5px;
}
label {
font-weight: bold;
}
input[type=text] {
width: 20em
}
p {
margin: 1em 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
RESULT TEST PURPOSE:
<br><br>
EXPECTED:
<br>
<textarea rows="5" cols="72">
<optgroup value="1" label="test group">
<option value="4" selected>Test option</option>
</optgroup>"
</textarea>
<br><br>
GET:
<br>
<label id="a"></label>
Next step is to append the string created dinamically in a select with
$("#select").append(group);
But the string is not created...it result empty
There's a few issues here. Firstly you're attempting to append an optgroup element to a label. This is impossible as optgroup can only be children of select elements.
Secondly, optgroup elements do not have a value attribute.
Finally, you're repeatedly creating new jQuery objects for group and t, which means that all previous amendments are lost. To fix this create the jQuery objects once and store them in variables which you can then reference whenever you want to make a change. Try this:
$(document).ready(function() {
var $group = $('<optgroup></optgroup>');
$group.prop("label", "test group");
var $t = $('<option></option>');
$t.val(4);
$t.prop("selected", true);
$t.text("Test option");
$group.append($t);
$("#a").html($group);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select id="a"></select>
Note the use of val() to set the value attribute, and the use of prop() over attr() where possible.
There are several issues:
var group = "<optgroup></optgroup>";
$(group).attr("value", 1);
You are referring to the JQuery element incorrectly. What goes inside $() needs to be a string representing an element, a class, or an id. So if you want to change all existing optgroups, it should look like this:
var group = "optgroup";
$(group).attr("value", 1);
However, based on the rest of your code that doesn't seem to be your intention. If you are wanting to create a new optgroup, then you'll need to reference an element already in the DOM to add it to (i.e. your #select).
Second, your optgroup element cannot have a value, that is invalid HTML. An optgroup is a non-selectable "label" that helps break up options in a dropdown.
Third, you are creating your <option> element incorrectly. As mentioned before, you can't create a JQuery element with a string of an open/close for an element. You'd be better off doing something like this:
var t = "<option value='4' selected='selected'>Test option</option>";
$(group).append(t);
So your code should actually look something like this:
var group = "<optgroup label='test group'>";
group += "<option value='4' selected='selected'>Test option</option>";
group += "</optgroup>";
$("#select").append(group);
If you have at least JQuery 1.8, you can change it to this:
var group = $( "<optgroup/>", { "label" : "test group"});
var option = $( "<option/>", { text : "Test option", "value" : 4, "selected" : "selected" });
group.appendTo( "#select" );
option.appendTo(group);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select id="select"></select>
Hi guys so I'm trying to set attributes using jquery, but the code is not setting the attributes. What am I doing wrong. This is what I have tried :
HTML
<select id="track_type_selected">
<option value="0" >51 Track 3m</option>
<option value="1" >64 Track 3m</option>
<option value="2" >103 Track 3m</option>
</select>
Javascript
var e = document.getElementById("track_type_selected");
var selectedIndex = e.options[e.selectedIndex].value;
if(selectedIndex==0){
$("#required_tracks_id").setAttribute("sku","TRACK3");
}
if(selectedIndex==1){
$("#required_tracks_id").setAttribute("sku","TRK30");
}
if(selectedIndex==2){
$("#required_tracks_id").setAttribute("sku","TRACK-1033");
}
In JQuery you can use attr function to get or set any element Attribute to get an element attribute like this.
$("#required_tracks_id").attr("sku");
and to set an element attribute
$("#required_tracks_id").attr("sku", "Value");
in your case use code as bellow
var e = document.getElementById("track_type_selected");
var selectedIndex = e.options[e.selectedIndex].value;
if(selectedIndex==0){
$("#required_tracks_id").attr("sku","TRACK3");
}
if(selectedIndex==1){
$("#required_tracks_id").attr("sku","TRK30");
}
if(selectedIndex==2){
$("#required_tracks_id").attr("sku","TRACK-1033");
}
The reason it didn't work was because you were mixing vanilla JS with jQuery. You obtained the #required_tracks_id via jQuery selector, but setAttribute() is a JS function. So, you could do either of these:
document.querySelector("#required_tracks_id").setAttribute("sku", "xxx");
Or
$("#required_tracks_id").attr("sku", "xxx");
This is my jspPage.
<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="Class(this.id)">
<option id="1">Manager</option>
<option id="2">Supervisor</option>
</select>
And here is javascript
function Class(str)
{
alert(str);
}
i want to get the id of Option on onchange Event. Thanks :)
You can do this if you are trying to get the id of the option which has been selected
function Class(str)
{
var select = document.getElementById("class_Teacher");
var option = select.options[select.selectedIndex];
alert(option.id);
}
Your onchange event will look like this. Just remove the .id as that will return the id of the select box itself not the option
onchange="myFunction(this)"
and your javascript function like this, which will alert the ID of the selected option
function myFunction(ele){
alert(ele.options[ele.selectedIndex].id);
}
Broken down ele represents the select box (a dom object). .options accesses the options within the select box. the [] brackets are a way of accessing a specific option. Like an array myArr[1] etc. and ele.selectedIndex returns a number representing the selected option i.e if the first option is chosen - ele.selectedIndex will be equivalent to 0.
HTML (you should use "value" attribute instead of "id")
<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="onChange()">
<option id="1" value="ID1">Manager</option>
<option id="2" value="ID2">Supervisor</option>
</select>
JS
var selectElement = document.getElementById("class_Teacher");
selectElement.onchange=function(){
alert(selectElement.options[selectElement.selectedIndex].id); // id in the html element
alert(selectElement.selectedIndex); // index starting from 0
alert(selectElement.value); // value of the selected element
};
Fiddle
Use selsectedIndex Property of GetElementByID
<script>
function val() {
d = document.getElementById("select_id").selectedIndex;
alert(d);
}
</script>
<select onchange="val()" id="select_id">
Here is the code:
$('#date').append(
'<select id="date">'+
'<option value="0">- - SELECT - -</option>');
for(var i in data){
$('#date').append(
'<option value="">'+data[i]['date_time']+'</option>');
});
$('#date').append('</select>');
</select> is always added above for loop. If i replace it with just work select for example, it is appended at the end, where it should be. Why is this happening and how can i fix it?
I believe that jQuery will generate the DOM like this:
<div id="date">
<select id="date">
<option value="0">- - SELECT - -</option>
</select>
<option value="">foo</option>
<option value="">bar</option>
etc...
</div>
Since it is automatically closing the <select> after the first .append(). What you are doing afterwards is appending the options to the <div id="#date"/> rather than the <select> that was appended. I don't think the final closing </select> will actually do anything either.
If you really want to use append the following JavaScript will add the options to the correct node:
// dummy data object for example
var data = new Array(new Array(), new Array());
data[0].date_time = 2011;
data[1].date_time = 2012;
var options = new Array();
$.each(data, function(index, option) {
options.push('<option value="' + index + '">'+ option.date_time +'</option>');
});
$('<select id="date"/>').append(options.join('')).appendTo('#date');
Assuming the existing HTML:
<div id="date"></div>
However this does incur an overhead since appending is occurring twice. The faster approach is to build up the options markup as already answered by ShankarSangoli
It is not the right way to create html dynamically. You should create the complete markup all at once by putting it into an array and then provide it to jQuery. Try this
var html = [];
html.push('<select id="date">');
html.push('<option value="0">- - SELECT - -</option>');
for(var i in data){
html.push('<option value="">'+data[i]['date_time']+'</option>');
}
html.push('</select>');
//This selector should be some container like dateContainer
//because you have already give date as id to the above select element
$('#dateContainer').html(html.join(''));
$('#date').append($("<select/>", { name: "name"+i})
.find('select')
.append($("<option/>", { value: "abc"+i}).text('cell'))
.append($("<option/>", { value: "abc"+i}).text('home'))
.append($("<option/>", { value: "abc"+i}).text('work'));
all options should wrap inside select
I imagine the base HTML you have looks something like this:
<div id="date"></div>
then after the first $('#date').append('<select id="date">... in your code, you will have this:
<div id="date"><select id="date">...</div>
which is 2 elements with the same ID attribute.
The ID attribute is like the highlanders, there must only be one of them (in each page).
The seccond $('#date').append... works unexpectedly, and the 3rd one, also unexpectedly, doesn't work. Because you can't predict to which #date they are referring.
Also, as the other answers say, it will be better if you build it to do only 1 append, because calling the selectors so many times (especially inside the loop) it's a performance hit.
If you want to do it in your way - create, for example, string variable with html code in it and than append it.
data = [1, 2, 3];
var html = '<select id="date">'+
'<option value="0">- - SELECT - -</option>';
for(var i in data){
html += '<option value="">'+data[i]+'</option>';
}
$('#date').append(html)
or look here
What is the best way to add options to a select from an array with jQuery?
ps: the first append tries to create a valid DOM structure inside of document, closing select tag automatically. that is why the second one will not insert options into the created select.
another possible way, based on the link above, is
var sel = $('<select id="date">');
$.each(data, function(key, value) {
sel.append($('<option>').text(key['date_time']));
});
$('#date').append(sel);
<td>
<select name="ad_category" id = "ad_category" onchange="select_sub_cat(this.value)" >
<option value="#"></option>
<option value="jobs" id="jobs">Jobs</option>
<option value="sales" id="for_sale">For sale</option>
<option value="services" id="services">Services</option>
<option value="real_estate" id="real_e">Real estate/housing</option>
</select>
<span id="cat_help">Help</span>
</td>
IN the above code , in <a href=""> I want to pass the id or any information of the option selected , so that clicking on help will show only the help for the particular option . But my question is is it possible to get the id of the option selected ?
You should be using a button or some other element that doesn't suggest navigation. An inline handler might be:
<... onclick="alert(document.getElementById('ad_category').value);" ...>
More generally, once you have a reference to the select element:
var select = document.getElementById('ad_category');
you can access various properties defined by the HTMLSelectElement interface:
select.selectedIndex // index of selected option
select.options // collection of all options
select.options[select.selectedIndex] // the selected option (if there is one)
and so on.
Edit
You might also want to implement a more generic help system based on class values. Give your form controls a class depending on the help that should be shown. Then the help button can just get the previous form control, grab its class and show it.
e.g.
<style type="text/css">
.helpLink {
color: #CC00FF;
cursor: pointer;
}
</style>
<script type="text/javascript">
var showHelp = (function() {
var help = {
firstName: 'Enter your first name',
lastName: 'Enter your last name'
}
return function (el) {
var helpType;
var node;
do {
el = el.previousSibling;
} while (el && el.nodeType != 1)
if (el) {
helpType = el.className.match(/(^|\s)help-\w+/);
if (helpType) {
helpType = helpType[0].replace('help-','');
// Show help
alert(help[helpType]);
}
}
}
}());
</script>
<form name="form0" action="">
first name: <input type="text" class="help-firstName" name="firstName">
<span class="helpLink" onclick="showHelp(this)">?</span>
<br>
last name: <input type="text" class="help-lastName" name="lastName">
<span class="helpLink" onclick="showHelp(this)">?</span>
<br>
</form>
The above is just a trivial demo.
Yes, you can get the selected option's id:
//Place in event handler
var element = document.getElementById("ad_category");
element.options[element.selectedIndex].id
Related SO post.
If you are using jQuery, you can use the change() function on the selector, to let you know when the selector changes, and capture the ID of the selected item.
Once you have that, you can use jQuery's attr on the anchor to change the href.
Yes it is and you even have several options how to get the job done.
Since the select has an ID, you can get the value like this:
var select = document.getElementByID('ad_category'),
value = select.value;
alert(value);
But also, since the select is a sibling to the parent of the a element, you can also find it like this:
// This example is assuming quite a lot, so it's not really the best option and is
// provided merely for entertainment or trivia.
// Namely, this code requires that it is run in context of the a-element
// (means: 'this' refers to the 'a' -element)
// and also that the markup is exactly as in the example because of traversal.
var select = this.parentNode.previousElementSibling,
value = select.value;
alert(value);