How to dynamically change the selected option and update without reloading? - javascript

It was hard to find terms for a good search (so please excuse me if the topic has already been discussed) as well as an explicit title for this post.
I'm working on this external web page : https://espacepersonnel.bnf.fr/views/mes_notices.jsf (need to be logged)
and I'm trying to override the default selected option with the one which value="0". The custom js code I wrote does submit the form but only after the page has been loaded. Nevertheless I'd like to change the select value before this.
Here's the concerned code's part of this page (that of course I can't edit) :
<form id="noticeComp:mainForm" name="noticeComp:mainForm" method="post" action="/views/mes_notices.jsf" class="noticeForm" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="noticeComp:mainForm" value="noticeComp:mainForm">
<input type="hidden" name="noticeComp:mainForm:j_idt253" value="">
<input type="hidden" name="noticeComp:mainForm:j_idt254" value="false">
<!-- <div id="site"> -->
<!-- <div class="moncatagen"> -->
<!-- <div class="col2"> -->
<h1 class="h1small">
<span>
<select name="noticeComp:mainForm:j_idt256" size="1" onchange="submit()">
<option value="0">Toutes les notices</option>
<option value="1" selected="selected">Notices biblio.</option>
<option value="2">Notices d'autorités</option>
</select>
Notices
</span>
</h1>
</form>
And here's my own 'content_script' :
var elm;
var evt;
elm = document.getElementsByName('noticeComp:mainForm:j_idt256')[0];
evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
while(!document.getElementsByName('noticeComp:mainForm:j_idt256')[0].options[0].selected){
document.getElementsByName('noticeComp:mainForm:j_idt256')[0].options[0].selected="selected";
elm.dispatchEvent(evt);
}
Can you see a solution for me ? (Better if JS only)
Thank you very much for reading this post and answering it if you can.
Bigindian.
P.S : Pardon my english
N.B :
Result page :
result page

You can try the following:
get a reference to the select
loop over its options
if the value of the option is '0', select it. Otherwise, deselect it.
Example code:
var elm = document.getElementsByName('noticeComp:mainForm:j_idt256')[0];
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
for (var i = 0; i < elm.options.length; i++) {
var option = elm.options[i];
if (option.value === '0') {
option.setAttribute('selected', 'selected');
} else {
option.removeAttribute('selected');
}
}
elm.dispatchEvent(evt);
function submit() {
// code
console.log('gogo');
}
demo

Related

How to change button URL through JS?

I have been spending a lot of time researching how to change a button href dynamically in my website using JS. I have a functioning Wordpress website, but would like to add some small additional functionality using JS to change a button's link based on a few user options.
I have researched this and found answers, but I absolutely cannot get the solutions to work on my site.
One of the simplest solutions that should work was found here:
How to make option selection change button link?
I can't understand what is different between what I am trying to accomplish and what the accepted answer proposed. I added window.onload() to prevent the JS from running before elements were loaded.
I am trying to do something similar with the following HTML & JS code:
HTML Code:
<input type="hidden" id="input-book-type" value="GlassCrystal">
<br><br>
<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>
<br><br>
<input id="input-project-title" value="Optional Project Title">
<br><br>
<a class="button" id="design-button" href="http://">Design Now</a>
JS Code:
window.onload = function() {
document.getElementById("design-button").onclick = function() {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var projtitle = document.getElementById("input-project-title");
this.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/";
};
}
JS Fiddle:
https://jsfiddle.net/w65c9x2d/
I think your code to change the href is correct. However, the onload function is not immediately invoked for the code to work.
window.onload = function(e) {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var pagenum = document.getElementById("select-page-num");
var projtitle = document.getElementById("input-project-title");
document.getElementById("design-button").onclick = function() {
this.href = "http://design.framesmile.com/?sessionid=guest&ref=" + booktype.value + pagesize.value + "*projectName=" + projtitle.value + " / ";
console.log(this.href);
};
}();// invoke the function
<input type="hidden" id="input-book-type" type="" value="GlassCrystal">
<br>
<br>
<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>
<br>
<br>
<select id="select-page-num">
<option value="20">20</option>
<option value="22">22</option>
</select>
<br>
<br>
<input id="input-project-title" type="" value="Optional Project Title">
<br>
<br>
<a class="button" id="design-button" href="http://test/">Design Now</a>
Here is example code:
jhg
jhhghj
<script type="text/javascript">
document.getElementById("myLink").onclick = function() {
document.getElementById("abc").href="xyz.php";
return false;
};
</script>
I took this from here
Change your button to this:
<button class="button" id="design-button" onclick="redirect()">Design Now</button>
Now instead of using a link, simply do a function that will take the inputs and change the window.location.href (or whatever method you prefer) to change the page.
redirect(obj) {
window.location.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/"
}
Obviously change it to your liking :)
I recommend using jQuery.
$("#submit").on('click', function(event) {
event.preventDefault();
data = $("#link").val();
$("#frame").attr({
src: "http://"+data});
});
When the submit button is clicked, it changed the iframe url which changed the content of the iframe automatically.
I don't really understand what you are trying to ask, but try to modfiy the code above :)

Condtionally disable button by Radio and Checkbox

I would like to conditionally disable a button based on a radio and checkbox combination. The radio will have two options, the first is checked by default. If the user selects the second option then I would like to disable a button until at least one checkbox has been checked.
I have searched at length on CodePen and Stack Overflow but cannot find a solution that works with my conditionals. The results I did find were close but I couldn't adapt them to my needs as I am a Javascript novice.
I am using JQuery, if that helps.
If needed:
http://codepen.io/traceofwind/pen/EVNxZj
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
(Please excuse the code, it is in short hand for example!)
The form element IDs are somewhat fixed. The IDs are generated by OpenCart so I believe the naming convention is set by group, rather than unique. I cannot use IDs such as radio_ID_1 and radio_ID_2, for example; this is an OpenCart framework facet and not a personal choice.
Finally, in pseudo code I am hoping someone can suggest a JQuery / javascript solution along the lines of:
if radio = '2' then
if checkboxes = unchecked then
btn = disabled
else
btn = enabled
end if
end if
Here is a quick solution and I hope that's what you were after.
$(function() {
var $form = $("#form1");
var $btn = $form.find("#btn");
var $radios = $form.find(":radio");
var $checks = $form.find(":checkbox[name='optionals']");
$radios.add($checks).on("change", function() {
var radioVal = $radios.filter(":checked").val();
$btn.prop("disabled", true);
if (radioVal == 2) {
$btn.prop("disabled", !$checks.filter(":checked").length >= 1);
} else {
$btn.prop("disabled", !radioVal);
}
});
});
Here is a demo with the above + your HTML.
Note: Remove all the IDs except the form ID, button ID (since they're used in the demo) as you can't have duplicate IDs in an HTML document. an ID is meant to identify a unique piece of content. If the idea is to style those elements, then use classes.
If you foresee a lot of JavaScript development in your future, then I would highly recommend the JavaScript courses made available by Udacity. Although the full course content is only available for a fee, the most important part of the course materials--the videos and integrated questions--are free.
However, if you don't plan to do a lot of JavaScript development in the future and just need a quick solution so you can move on, here's how to accomplish what you are trying to accomplish:
$(document).ready(function(){
$('form').on('click', 'input[type="radio"]', function(){
conditionallyToggleButton();
});
$('form').on('click', 'input[type="checkbox"]', function(){
conditionallyToggleButton();
});
});
function conditionallyToggleButton()
{
if (shouldDisableButton())
{
disableButton();
}
else
{
enableButton();
}
}
function shouldDisableButton()
{
if ($('div#input-option1 input:checked').val() == 2
&& !$('form input[type="checkbox"]:checked').length)
{
return true;
}
return false;
}
function disableButton()
{
$('button').prop('disabled', true);
}
function enableButton()
{
$('button').prop('disabled', false);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
Note that the JavaScript code above is a quick-and-dirty solution. To do it right, you would probably want to create a JavaScript class representing the add to cart form that manages the behavior of the form elements and which caches the jQuery-wrapped form elements in properties.

Get selected option ID with Javascript

I have a tabs with select option in each tab and I want it to be submitted in a specific URL assigned to them when I hit submit button. I'm doing this in javascipt. I'm really a newbie in javascript that's why I need your generous help.
I divided my select option according to their category using tabs, so my code is like this:
HTML
<ul class="ut-nav-tabs clearfix">
<li class="active">Corporate Services
</li>
<li class="">
Digital Marketing
</li>
</ul>
<div id="t1Tab" class="tab-pane clearfix active">
<form method="post" action="/trendstatic15/#wpcf7-f3409-o1">
<select id="id_corporateservices">
<option value="Can a foreign investors open his own company in the Philippines?">Can a foreign investors open his own company in the Philippines?</option>
<option value="What are the business regulations currently used in the Philippines?">What are the business regulations currently used in the Philippines?</option>
</select>
</div>
<input class="wpcf7-form-control wpcf7-submit" type="submit" value="Submit">
</form>
</div>
<div id="t2Tab" class="">
<form method="post" action="/trendstatic15/#wpcf7-f3409-o1">
<select id="id_digitalservices">
<option value="Should I add online video to my web sites?">Should I add online video to my web sites?</option>
<option value="What works best in Internet marketing?">What works best in Internet marketing?">What works best in Internet marketing?">What works best in Internet marketing?</option>
</select>
</div>
<input class="wpcf7-form-control wpcf7-submit" type="submit" value="Submit">
</form>
</div>
JAVASCRIPT
<script type="text/javascript">
function redirect() {
var filename_corporate = document.getElementById('id_corporateservices').value;
var filename_digital = document.getElementById('id_digitalservices').value;
var url ='';
if (filename_digital == 'What works best in Internet marketing?')
{
url= 'http://localhost/testsite/digital-page';
}
else if(filename_corporate == 'Can a foreign investors open his own company in the Philippines?')
{
url= 'http://localhost/testsite/corporate-page';
}
else
{
url= 'http://anyurlpage.com';
}
window.location = url;
}
</script>
Why is that when I selected any in the option and then submitted it always direct to the first url condition http://localhost/testsite/digital-page?
Because you are always referring to the one element with id "id_digitalservices" that never changes? It does not matter if you change tabs visibility it still remains in DOM.
You can get the actually changed option value by using the following code:
<script type="text/javascript">
function selectmenuOnchange(selectMenuId) {
//Get the selectmenu element by Id
var selectmenuID = document.getElementById(selectMenuId);
//Get selected options value
var optionValue = selectmenuID.options[selectmenuID.selectedIndex].value;
//this should return the selectmenu's id
alert(this.id);
redirect(optionValue);
}
function redirect(optionValue) {
var url ='';
if (optionValue === 'What works best in Internet marketing?')
{
url= 'http://localhost/testsite/digital-page';
}
else if(optionValue === 'Can a foreign investors open his own company in the Philippines?')
{
url= 'http://localhost/testsite/corporate-page';
}
else
{
url= 'http://anyurlpage.com';
}
window.location = url;
}
</script>
You need to edit both of your selectmenus to include my onchange function like this:
HTML
<select onchange="selectmenuOnchange(this.id);">

Onchange inside onchange jquery

Im having trouble having code onchange inside onchange event.
some works and some dont work due to that.
<script>
$(document).on('change', '.sellkop', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#text_container").after(price_option());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").css({"display": 'none'
});
};
});
$('#category_group').on('change', function() { // this is select options
if ($(this).val() == 101) {
$("#underKategory").css({"display": 'none'});
$("#modelcontainer").remove();
$(".toolimage").css({ "display": 'block'});
$('.sellkop').on('change', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").css({"display": 'block'});
$(".toolimage").css({"display": 'block' });
} else {
$(".toolimage").css({"display": 'none'});
}
});
} else {
$(".bilar").remove();
$(".toolimage").css({ "display": 'none'});
}
if ($(this).val() == 102) {
$(".houses_container").remove();
$(".toolimage").css({"display": 'none'});
$("#underKategory").css({"display": 'inline-block'});
$("#modelcontainer").remove();
}
///............many other values continue
});
</script>
i know there is better way to manage this code and simplify it , how can i do it ?
EDIT:
what i want is : if i select an option , then get values to that option, then under this category option there is radio buttons , then every check button i need to get some data displayed or removed
here is a fiddle there looks my problem by jumping from categories when i select buy or sell , so
if i select category-->check buy -->then select others . i dont get same result as if i select directly cars ---> buy
I have never resorted to even two answers before (let alone three), but based on all the comments, and in a desire to keep things simple another solution is to data-drive the visibility of other items based on selections, using data- attributes to store the selectors on the options and radio buttons.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/28/
e.g the HTML for the select becomes
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101' data-show="#sellbuy,.cars,.toolimage,#licenscontainer">cars</option>
<option value='102' id='cat102' data-show="#sellbuy,#underKategory">others</option>
</select>
and the radio buttons like this:
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' data-show="#price_container,.cars,.toolimage"/>
The code becomes very simple then, simply applying the filters specified in the selected items.
$(document).on('change', '.sellkop', function () { // this is radio button
// Hide defaults
$("#price_container,.cars,.toolimage").hide();
// Show the items desired by the selected radio button
$($(this).data("show")).show();
});
$('#category_group').on('change', function () { // this is select options
// Get the various possible data options and decide what to show/hide based on those
var $this = $(this);
var value = $this.val();
// Get the selected option
var $li = $('option[value='+ value+']', $this);
// Hide all the defaults first
$('#licenscontainer,.cars,.toolimage,.sell,#underKategory').hide();
// Now show any desired elements
$($li.data('show')).show();
// Fire change event on the radio buttons to ensure they change
$('.sellkop:checked').trigger('change');
});
This is a very generic solution that will allow very complex forms to turn on/off other elements as required. You can add data-hide attributes and do something similar for those too if required.
Note: This was an attempt to fix the existing style of coding. I have posted an alternate answer showing a far simpler method using hide/show only.
A few problems.
If you must nest handlers, simply turn them off before you turn them on. Otherwise you are adding them more than once and all the previously recorded ones will fire as well.
Your HTML strings are invalid (missing closing </div>)
You can simply use hide() and show() instead of all the css settings. You should use css styling for any specific element styling requirements (e.g. based on classes).
You need to replace specific divs, rather than keep using after, or you progressively add more html. For now I have use html to replace the content of the #text_container div.
HTML in strings is a maintenance nightmare (as your example with missing </div> shows). Instead use templates to avoid the editing problems. I use dummy script blocks with type="text/template" to avoid the sort of problems you have found. That type means the browser simply ignores the templates.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/17/
HTML (with templates)
<script id="saljkop">
<div class='sex sell' id='sellbuy' >
<label ><input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked'/> Sell </label>
<label ><input id='rk' type='radio' class='radio sellkop' value='k' name='type'/>buy</label>
</div>
</script>
<script id="price_option">
<div class="container" id = "price_container">
<div>
<label><input class="price_option" name="price_opt" value="1" type="radio"/> Fix </label>
<label class="css-label"><input class="price_option" name="price_opt" value="2" type="radio"/> offer </label>
</div>
</div>
</script>
<script id="cars">
<div class="cars" >
<div id="licenscontainer" ><div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</script>
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">textttttt</div>
New jQuery code:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#sellbuy").after($('#cars').html());
$("#text_container").html($('#price_option').html());
$("#underKategory").hide();
$(".toolimage").show();
$('.sellkop').off('change').on('change', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").show();
$(".toolimage").show();
} else {
$(".toolimage").hide();
}
});
} else {
$(".cars").remove();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#text_container").html($('#price_option').html());
$(".toolimage").hide();
$("#underKategory").show();
}
///............many other values continue
});
Now if you prefer to not nest handlers (recommended), just add to your existing delegated event handler for the radio buttons:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
$("#licensenumber_c").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
$(".toolimage").hide();
};
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/20/
Note: This was a second answer, hoping to simplify the overall problem to one of hiding/showing existing elements. I have posted a third(!) answer that takes it to an even simpler scenario using data- attributes to provide the filter selections.
I am adding a second answer as this is a complete re-write. The other answer tried to fix the existing way of adding elements dynamically. I now think that was simply a bad approach.
The basic principal with this one is to have very simple HTML with the required elements all present and simply hide/show the ones you need/ Then the selected values are retained:
This uses the multi-structure to effectively hide.show the licence field based on two separate conditions.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/23/
Html (all element s present, just the ones you do not need hidden):
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
<div class='sex sell' id='sellbuy' style="display: none">
<label>
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' />Sell</label>
<label>
<input id='rk' type='radio' class='radio sellkop' value='k' name='type' />buy</label>
</div>
<div class="cars" style="display: none">
<div id="licenscontainer">
<div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">
<div class="container" id="price_container" style="display: none">
<div>
<label>
<input class="price_option" name="price_opt" value="1" type="radio" />Fix</label>
<label class="css-label">
<input class="price_option" name="price_opt" value="2" type="radio" />offer</label>
</div>
</div>
</div>
jQuery:
$(document).on('change', '.sellkop', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#price_container").show();
$(".cars").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").hide();
$(".cars").hide();
$(".toolimage").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").hide();
$("#sellbuy").show();
$(".cars").show();
$("#underKategory").hide();
$(".toolimage").show();
$('#licenscontainer').show();
} else {
$('#licenscontainer').hide();
$(".cars").hide();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").hide();
$("#sellbuy").show();
$(".toolimage").hide();
$("#underKategory").show();
$(".cars").hide();
}
$("#price_container").toggle($("#rs").is(':checked'));
///............many other values continue
});

enforce values in html5 datalist with javascript

How can I get this working on my website - not just jsfiddle?
I am trying to make it so users can only submit an entry from the datalist - if they type it wrong then there is an error message and the form will not submit.
I have this working in jsFiddle ( http://jsfiddle.net/9DG5m/1/ ), but can't get it to work on my website ( http://austinsamsel.com/test/vanity/index-form.html ) . I looked for errors with firebug and didn't find anything. Been stuck on this a couple hours. ~noob
the script and form:
<script type="text/javascript">
// Find all inputs on the DOM which are bound to a datalist via their list attribute.
var inputs = document.querySelectorAll('input[list]');
for (var i = 0; i < inputs.length; i++) {
// When the value of the input changes...
inputs[i].addEventListener('change', function() {
var optionFound = false,
datalist = this.list;
// Determine whether an option exists with the current value of the input.
for (var j = 0; j < datalist.options.length; j++) {
if (this.value == datalist.options[j].value) {
optionFound = true;
break;
}
}
// use the setCustomValidity function of the Validation API
// to provide an user feedback if the value does not exist in the datalist
if (optionFound) {
this.setCustomValidity('');
} else {
this.setCustomValidity('Spelling counts.');
}
});
}
</script>
<form id="type_form" method="post" >
<input id="nav" list="optionzzz" maxlength="10" class="mustbe" type="text" autocomplete="off" name="nav" placeholder="TYPE YOUR CHOICE... (spelling counts)" autofocus required>
<datalist id="optionzzz">
<option value="OPTION1">
<option value="OPTION2">
<option value="OPTION3">
<option value="OPTION4">
<option value="OPTION5">
</datalist>
<script type="text/javascript">
if (!("autofocus" in document.createElement("input"))) {
document.getElementById("nav").focus();
}
</script>
<button class="send" type="submit">SEND</button></form>
Another way to enforce choosing from a datalist is to have every item of the datalist appear in the pattern property of the input as well. Example:
<form>
<input required list="datalist" pattern="one|two|three" name="me">
<datalist id="datalist">
<option value="one">
<option value="two">
<option value="three">
</datalist>
<button type="submit">Submit</button>
</form>
The solution is to move your inline script to end of page so it would be
<script type="text/javascript">
// Find all inputs on the DOM which are bound to a datalist via their list attribute.
var inputs = document.querySelectorAll('input[list]');
....
</script>
</body>
</html>
because the script is executing on elements which are not loaded yet, so during this
var inputs = document.querySelectorAll('input[list]');
there are no inputs yet loaded.
You can also include the function in
$(document).ready(function () { .. //your function will come here }
so this will be executed when dom is ready

Categories