basic JS - innerHTML only working inline - javascript

I'm new to JavaScript and I've searched this site and other for hours for a solution, but can't get this to work. I'm probably making a basic mistake here.
If I call innerHTML inline like this it works perfectly:
<select id="myselect" onchange="this.innerHTML = '<option value="1">1</option><option value="100">100</option>'"></select>
But if I try to call it from an external JavaScript file or HEAD it doesn't work:
<script type="text/javascript">
function addSomeOptions(obj) {
obj.innerHTML = '<option value="1">1</option><option value="100">100</option>'
}
</script>
<select id="myselect" onchange="addSomeOptions(this)"></select>
I really would like to add the javascript in an external file rather than inline, since there may be hundreds of options. I also realise there are JS functions for adding Option tags, but because of the way the options are generated, I think it is preferable in this case to use the innerHTML function.

You can try following code in your html page,
<script type="text/javascript">
function addSomeOptions(obj) {
obj.innerHTML = '<option value="1">1</option><option value="100">100</option>'
}
</script>
<select id="myselect" onchange="addSomeOptions(this)">
<option>TestFirstValue</option>
<option>TestSecondValue</option>
</select>

innerHTML is a really crude tool to add dynamic HTML.
The DOM API offers a much more reliable interface for dynamically modifying HTML.
Your example:
function addSomeOptions(obj) {
var option = document.createElement("option");
option.setAttribute("value", 1);
option.appendChild(document.createTextNode("1"));
obj.appendChild(option);
/* repeat for all options */
}
Now, as you can see, this is really clunky (but reliable). There exist frameworks that try to do a better job. It's worth taking a look at those.

Your problem is most likely appears because the object you are trying to access in head is not yet loaded. Try to wrap your js calls inside onload, like this:
window.onload = function () {
function addSomeOptions(obj) {
obj.innerHTML = '<option value="1">1</option><option value="100">100</option>'
}
}
If you try to access an object before it was created, it won't work. You need to either do it after the page loads (see the code above) or, if you like script tags, place the code inside a script tag after the html declaration of your div / input / etc.
Edit: as Frits pointed out, you are doing the call on the onchange event, so it's ok.
However, looking at your code, you need to have some options inside the select tag in order to be able to trigger it:
The code below works just fine for me:
<html>
<head>
</head>
<body>
<script type="text/javascript">
function addSomeOptions(obj) {
obj.innerHTML = '<option value="1">1</option><option value="100">100</option>'
}
</script>
<select id="myselect" onchange="addSomeOptions(this)">
<option value="1">2</option><option value="100">200</option>
</select>
</body>
</html>

Related

how to choose selected option in select/option in HTML?

I need to display two select lists with the same options (there are many).
I have the index.html:
<body>
<select class="c_select1"></select>
<select class="c_select2"></select>
</body>
and in another html file (options.html) all the options (only the options):
<option value='AED' title='United Arab Emirates Dirham'>AED</option>
<option value='AFN' title='Afghan Afghani'>AFN</option>
<option value='ALL' title='Albanian Lek'>ALL</option>
<option value='AMD' title='Armenian Dram'>AMD</option>
<option value='ANG' title='Netherlands Antillean Guilder'>ANG</option>
...
<option value='AOA' title='Angolan Kwanza'>AOA</option>
<option value='ARS' title='Argentine Peso'>ARS</option>
<option value='AUD' title='Australian Dollar'>AUD</option>
<option value='AWG' title='Aruban Florin'>AWG</option>
<option value='AZN' title='Azerbaijani Manat'>AZN</option>
Then, using jQuery, I load options inside the two select tags with the same instruction with different class selector:
$(".c_select1").load("options.html");
I'd like to display as default selected option two different values (since I need to show a currency converter).
I've tried in 2 different ways, but any of these works fine (I show the code for just one).
<script type="text/javascript">
$(".c_select1").load("options.html");
$(".c_select1 option[value=ARS]").prop("selected", true);
</script>
or
$(".c_select1").val("ARS");
I don't know why, but I think there is a problem with the .load() of jQuery.
The only solutions that work are 2:
set a timer and execute the second jQuery statement after this timer
use 2 different options.html files one for each select tag, but I think it is not so clever.
Is there a better way to do this dynamically?
Try this:
$(".c_select1").load("options.html", function(){
$(".c_select1").val("ARS");
});
Explained:
The .load() jQuery method requires some time to get the contents of options.html (even if its just a few milliseconds). The browser doesn't wait for it before continuing to run the rest of the javascript logic. The function(){ I added to your .load( method call is some javascript logic that runs AFTER the results have returned (aka a "callback").
Use a callback :
$(".c_select1").load("options.html", function() {
$(".c_select1").val("ARS");
});
$(".c_select2").load("options.html", function() {
$(".c_select2").val("ARS");
});
Actually there is a delay of load method that is why selected item is not working. Like #Joulss said use callback method that should work. You can see the here.
$(function(){
$(".c_select1").load("option.html", function() {
$(".c_select1").val("AFN");
});
$(".c_select2").load("option.html", function() {
$(".c_select2").val("ANG");
});
});
Demo

PHP Javascript cant access echoed element id outside php mode

Humble appologies if this is a stupid question but I cant for the life of me figure out what is wrong here.
I have an echoed element inside php mode:
echo'<select name="picks" id="winner">';
echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
echo'</select>';
Now outside php
I try to do a basic javascript GET:
document.getElementById("winner");
However the elemnt is not accessible am I missing something here, is it not possible to get echoed elements Ids?
You should make sure your DOM has at least loaded before performing element selects. If you can use jQuery, then this is as easy as the following, and you can place this script in the head section, or anywhere in the body:
$(document).ready(function() {
// Perform any selects on the DOM
});
JS
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
// The DOM is loaded and ready to be selected
var select = document.getElementById("winner");
var optionText = select.options[select.selectedIndex].text;
var optionValue = select.options[select.selectedIndex].value;
});
</script>
Of course you can also perform DOM selects using jQuery:
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
// The DOM is loaded and ready to be selected
var optionText = $("#winner option:selected").text();
var optionValue = $("#winner option:selected").val();
});
</script>
Another possibility
If $row, $team1 or $team2 are not defined and you have PHP errors and notices turned on, then the HTML will render like so:
<select name="picks" id="winner"><b>E_NOTICE : </b> type 8 -- Undefined variable: row -- at line 4<br /><b>E_NOTICE : </b> type 8 -- Undefined variable: team1 -- at line 4<br />
<option value=""></option><b>E_NOTICE : </b> type 8 -- Undefined variable: row -- at line 5<br /><b>E_NOTICE : </b> type 8 -- Undefined variable: team2 -- at line 5<br />
<option value="" selected="selected"></option>
</select>
However, if you have PHP errors and warnings turned off, you would see something like this instead:
<select name="picks" id="winner">
<option value=""></option>
<option value="" selected></option>
</select>
If you are unable to access the value of options in your select HTML (because they are empty), this would be a good pace to start investigating.
Using JQUERY you can try following:
// I have used mouse down event for demo purpose.
$(document).delegate('#winner', 'mousedown', function ()
{
alert('hi');
});
Try accessing the value of the selected id
I am giving a demo fiddle
Demo fiddle
document.getElementById("winner").value;
Echoing JS codes is common but there are these possibilities:
1-You put document.getElementById("winner"); before php creating that element.
2-There is a syntax error in script tag which cause error and there for your select does not work.
since the php part will be available before page load you can simply do like this:
<?php
$row['team1']=1;$team1='India';$row['team2']=2; $team2='SA';
echo'<select name="picks" id="winner">';
echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
echo'</select>';
?>
<script>
console.log(document.getElementById("winner"));//see this in console.
</script>

cannot invoke bootstrap plugin from javaScript

I am trying to invoke bootstrap plugin for my webpage.
This is the plugin I am talking about:
Select Picker
Select Picker 2
When I invoke the plugin from my html file like this:
<html>
<head></head>
<body>
<select class="selectpicker show-tick" id="tag" ata-style="btn-primary">
<option>stocks</option>
<option>bank</option>
<option>card</option>
</select>
<script type="text/javascript">
$(window).on('load', function () {
$('.selectpicker').selectpicker('hide');
});
</script>
</body>
</html>
The output is fine; the select boxes come with all CSS loaded as showed in the links above.
However, when I create the boxes dynamically from a JS file, the select boxes come up as plain Select boxes with no effects.
var selectElement1_act = document.createElement("select");
selectElement1_act.setAttribute("class", "selectpicker");
Any help would be appreciated.
This is because you're invoking the function on the window load event, and when elements are created dynamically, they do not necessarily exist in the DOM at that point.
Since you're using jQuery, you'd be better to utilise the following code in your JS file instead:
$(function() {
var selectPicker = $('<select class="selectpicker" />');
selectPicker.appendTo('body');
selectPicker.selectpicker('hide');
});

Auto select based on option value

I was googling around and saw a tutorial on YouTube that uses JavaScript to auto select options based on the select value.
The JavaScript code looks like this:
$("select[value]").each(function() {
$(this).val(this.getAttribute("value"));
});
And the code that is in the HTML is this (after PHP gets the data)
<select name="group" id="group" value="4">
<option value="1">Administrator</option>
<option value="2">Member</option>
<option value="3">Developer</option>
<option value="4">Moderator</option>
<option value="5">Donator</option>
</select>
The value in the select is supposed to tell the JavaScript what is to be selected, but it's not working for me, help me please? (I'm new to JavaScript/PHP/MySQL)
That code uses the jQuery library. Given you haven't tagged your question with jQuery, I suspect maybe you don't realise that it is needed and haven't included the jquery.js file?
Add this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
(To load it from Google's CDN.)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
then try like mine, may be can help you
$(function(){
var val = $("select[name=group]").val();
$("select[name=group]").change(function(){
val = $(this).val();
});
}

dijit.byId() returns undefined even in dojo.addOnLoad()

i have recently started to work in dojo.
dijit.byId() returns undefined even if i put this call inside dojo.onLoad().
<script type="text/javascript">
dojo.require("dijit.form.Select");
function myhandler(ev)
{
var mydiv = dojo.byId('mydivid');
if (ev == 'Disable') {
mydiv.style.display = 'none';
} else {
mydiv.style.display = 'block';
}
}
function regHandler()
{
var item = dijit.byId("myState");
alert(item);//shows undefined
dojo.connect(dijit.byId("myState"), 'onChange', myhandler);
}
dojo.addOnLoad(regHandler);
</script>
<select input class="dialogInputElement" dojoAttachPoint="myState" dojoType=dijit.form.Select name="myState" id="myState" value='Enable' style="margin-bottom:5px">
<option value="Enable">Enable</option>
<option value="Disable">Disable</option>
</select>
it works fine if i delay dijit.byId() call with setTimeout().
dojo version is 1.4.2
Any solution or workaround will be appreciated.
Thanks in advance.
If this is verbatim from your code, it looks like you are missing double-quotes from around your dojoType declaration. If your input is never declared as a dijit widget, it will never be retrievable by dijit.byId().
If you want a more general node selector, use dojo.byId() instead, it will select any node with an id, not just dijit widgets.
Have you tried adding the attribute djConfig="parseOnLoad: true" to the dojo configuration?
When you include the dojo.js library file you can set the attribute like this:
<script type="text/javascript" src="dojo/dojo.js"
djConfig="parseOnLoad: true">
</script>
In my tests, this seems to solve the problem. In this jsfiddle note if you remove the djconfig tag attribute (on the left nav bar) and run it, you get the behavior you are describing.

Categories

Resources