Skip to content Skip to sidebar Skip to footer

About Script Tags Inside Form Tags

i have added a script tag in side a select tag which creates options dynamically. The function works fine but the W3C validator gives me 4 errors regarding this syntax. It will be

Solution 1:

1) the only tags that <select> can have are <option> and <optgroup> tags the validator is complaining because <script> is not one of those things -- the browser is doing its best to take your invalid markup and turn it into something valid, so despite the fact that it works, that's why you get the error, if you're actually putting <script> tags inside of a <select>

2) your script tags should be at the bottom of your page, and instead of using document.write to put option tags there, use DOM methods to add options to the select element after the fact

<select name="select-box"></select>
<!-- ...rest of page... -->
<script src="external-script.js"></script>

/* contents of external-script.js */
var select_box = document.querySelector("select[name=select-box]"),
    bob_opt  = document.createElement("option"),
    doug_opt = document.createElement("option");

bob_opt.value  = "Bob";
doug_opt.value = "Doug";
bob_opt.appendChild(document.createTextNode("Bob"));
doug_opt.appendChild(document.createTextNode("Doug"));

select_box.appendChild(bob_opt);
select_box.appendChild(doug_opt);

There are faster and neater, or more-elaborate or more flexible ways of doing this, but this is closer to the "right way" than something like:

<select>
    <script>document.write("<option value=\"" + i + "\">one</option>");</script>
</select>

Or whatever you might currently have there. JS is not meant to be templated like that, without using/writing a templating library for that purpose.


Solution 2:

1) Script tags should be located in head, or perhaps elsewhere in the document, but not inside select tags

2) Looks like you are missing a tag, or perhaps its having problems finding it because of the first error.


Solution 3:

You can put your JavaScript out side the select tag, and you can append option tags later, when select tag is rendered on the page, after page load using $(document).ready.

You can standardize your code by placing JavaScript in separate file, there you can do like

$(document).ready(function(){
//Your code to init all things,
//e.g. load options in select box etc..
//so It will be easy later to maintain the code, all init code will go here
});

Or if you are not using jquery, you can use below code

function your_function(){
//your init code will go here
}
document.getElementsByTagName("body")[0].onLoad = your_function;

that's it, place your code in your_function()


Post a Comment for "About Script Tags Inside Form Tags"