Local Storage multiple fields with one field overwriting the second - html

I am creating a Chrome extension that restricts off-limits TV content. I have two roll-down menu forms that store values to Local Storage.
Javascript (external files):
ratings.js
window.onload=function (){
document.getElementById('saveRatings').onsubmit=saveRatings;
}
function saveRatings() {
var selectedRatings = document.forms["ratings_form"]["ratings"].value;
// store selectedRatings to local storage
localStorage.storedRatings = selectedRatings;
}
age.js
window.onload=function (){
document.getElementById('saveAge').onsubmit=saveAge;
}
function saveAge() {
var selectedAge = document.forms["age_form"]["age"].value;
// store selectedAge to local storage
localStorage.storedAge = selectedAge;
}
HTML
<summary>Select Content to Allow</summary><br>
<form name = "ratings_form" id="saveRatings">
<select name="ratings" multiple="multiple">
<option value="G">G only</option>
<option value="G/PG">G/PG only</option>
<option value="G/PG/PG13">G/PG/PG-13 only</option>
<option value="G/PG/PG13/R">G/PG/PG-13/R</option>
</select>
<div></div>
<input type="submit" value="Save"> </form>
<summary>Select Age Group to Deter</summary><br>
<form name = "age_form" id="saveAge">
<select name="age" multiple="multiple">
<option value="e">Everyone</option>
<option value="ct">Children & Teens;</option>
<option value="c">Children</option>
<option value="0">Turn off</option>
</select>
<div></div>
<input type="submit" value="Save">
</form>
The key-value pair for age_form stores correctly. However, ratings_form always gives me undefined. If I switch up the order (age first and ratings next), then the key-value pair for ratings_form would give me the correct value whereas age_value would give me undefined. It seems like the second form values are overwriting the first form values. How can I prevent this overwriting from occurring.
Thanks for your help.

Of course, your problem is that you're overwriting the window.onload function with whichever code runs last! All you need is a simple console.log(); in each function to see that the first one is not being called. You can remedy this with addEventListener() or by using jQuery's $(document).ready().
window.addEventListener('load', function() {
console.log('1');
});
window.addEventListener('load', function() {
console.log('2');
});
Just remember onload is a property of window and acts just like any variable/property would. Consider this:
var foo = 'bar';
foo = 'baz';
console.log(foo); // displays 'baz', of course! You changed the value!
That is just what you did with the onload function. You changed it to something else.

Related

Jquery returned 'undefined'(s) when try to get the ID of the 'select' tag through class

I'm trying to check if my select box is empty or not by using class. However, based on the code below, the alert returned not only the id but also another 2 'undefined'. Anyone who can tell me why is this happening?
<script>
$('.test-input').each(function () {
var el = [];
if ($(this).val() === "") {
var target = $(this).attr('id');
alert(target); *// return media_type | underfined | underfined*
el.push(target);
}
})
</script>
<div class="form-group col-sm-4">
<label class="">Type:</label>
<select class="form-control required-input test-input" id="media_type" placeholder="Choose a media">
<option value="">Select a state</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="lizard">Lizard</option>
<option value="snake">snake</option>
</select>
</div>
$('.test-input').each(function () will iterate through each element in your HTML that has the "test-input" class name, so when there you are cycling through those and getting an undefined from pulling its id via var target = $(this).attr('id');, what this means is that somewhere else in the file you must have two other classes named "test-input" without an ID.
I would console.log("Iteration"); in the loop and check your console to see how many times the loop is being run and go from there.

How to use form select value to action method (without query)

I'm using pug to render some pages for my nodeJS server. In this case I'm trying to use the value captured in the form select in order to change the action method.
So, the idea is use the group name selected to go to that page:
form.w3-container(action="http://localhost:5004/groups/" + (option selected down below) method="GET")
select.form-control(data-toggle='select' class="form-control" data-placeholder='Disabled results')
option group1
option group2
option group3
button.btn.btn-success(type='submit') Go
Any suggestion on how can I do this, if possible without jquery (if it is not possible without I, an explanation on how to "use" it would be very much appreciated).
From what Shoaib said in this post, it should be possible, but I dint't quit understand his suggestion, poor context :/
HTML code:
<form id="myForm" class="w3-container" action="" method="POST">
<select id="mySelector" data-toggle='select' class="form-control" data-placeholder='Disabled results'>
<option value="">Select</option>
<option value="group1">group1</option>
<option value="group2">group2</option>
<option value="group3">group3</option>
</select>
</form>
ECMAscript code:
var selector = document.getElementById("mySelector");
selector.addEventListener("change", function() {
changeAction();
});
function changeAction() {
var finalAction = document.getElementById("myForm").action = "http://localhost:5004/groups/" + selector.value;
}
JSFiddle: https://jsfiddle.net/ytvhqrs0/1/

Smilar to datalist

I'am searching something similar to datalist in html. While I'm typing something in html input it shows me similar titles in database. When i type something more, ajax show me better matching titles to my text. And i have this ajax script but my question is here: How can I present this titles under the input text?
I saw on google it's only ul and li tags, and it's all ?
google search example
But on w3schools example we can see propably better solution.
Which one is better ? Or if you know other techniques please tell me about it. Don't know which one to use in my search tool.
I think i find the solution by the comment with helpful link, don't remember who is it because he delete his comment.
By this link i started to seraching datalist and found article:
blog link
And here we have some phrases about datalist and very useful example:
<div id="page-wrapper">
<h1>Datalist Element Demo</h1>
<label for="default">Pick a programming language</label>
<input type="text" id="default" list="languages" placeholder="e.g. JavaScript">
<datalist id="languages">
<option value="HTML">
<option value="CSS">
<option value="JavaScript">
<option value="Java">
<option value="Ruby">
<option value="PHP">
<option value="Go">
<option value="Erlang">
<option value="Python">
<option value="C">
<option value="C#">
<option value="C++">
</datalist>
<label for="ajax">Pick an HTML Element (options loaded using AJAX)</label>
<input type="text" id="ajax" list="json-datalist" placeholder="e.g. datalist">
<datalist id="json-datalist"></datalist>
</div>
<script>
// Get the <datalist> and <input> elements.
var dataList = document.getElementById('json-datalist');
var input = document.getElementById('ajax');
// Create a new XMLHttpRequest.
var request = new XMLHttpRequest();
// Handle state changes for the request.
request.onreadystatechange = function(response) {
if (request.readyState === 4) {
if (request.status === 200) {
// Parse the JSON
var jsonOptions = JSON.parse(request.responseText);
// Loop over the JSON array.
jsonOptions.forEach(function(item) {
// Create a new <option> element.
var option = document.createElement('option');
// Set the value using the item in the JSON array.
option.value = item;
// Add the <option> element to the <datalist>.
dataList.appendChild(option);
});
// Update the placeholder text.
input.placeholder = "e.g. datalist";
} else {
// An error occured :(
input.placeholder = "Couldn't load datalist options :(";
}
}
};
// Update the placeholder text.
input.placeholder = "Loading options...";
// Set up and make the request.
request.open('GET', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/html-elements.json', true);
request.send();
</script>
I get this from codepen link in article. Pen created by Matt West.

Chosen select not calling a function on ng-click

I'm working with a chosen select, i added a function call when the event ng-click happens, but it's not doing anything, when i make the call to the same function in a button it works, why is this?
ng-change doesn't work either, even worse, it eats my options and leaves only the first one.
my select code:
<select ng-model="ind_oferta" multiple class="control-group chosen-select" chosen >
<optgroup label="Oferta">
<option value=""> </option>
<option ng-click="aplicarFiltro()" ng-repeat="menuOpcion in menu[0].opciones.oferta" value={{menuOpcion.id}}>
{{menuOpcion.tipo}}</option>
</optgroup>
</select>
the function is very simple, it's just a javascript alert
$scope.aplicarFiltro = function(){
alert("hello");
}
and i think is not worth put the button code, that one works so...
EDIT: i changed the select code to this, still not making the call to the function, help!
<select multiple class="control-group chosen-select" chosen style="width:250px;"
ng-model="ind_oferta" ng-click="aplicarFiltro();"
ng-options="menuOpcion.id as menuOpcion.tipo for menuOpcion in menu[0].opciones.oferta">
<option>--</option>
</select>
You should use the ng-options directive together with ng-model (you can still add a single <option> as the default value). It would probably look something like this:
<select ng-options="menuOpcion.tipo for menuOpcion in menu[0].opciones.oferta"
ng-model="selected"
ng-change="aplicarFiltro()" chosen multiple>
<option value=""></option>
</select>
There is a lot of customization options, so it is best if you check out the documentation.
To get the option which was removed by the user you could do something like this in your controller:
var previousSelection = [];
$scope.changedSelection = function () {
// Check if the current selection contains every element of the previous selection
for (var i = 0; i < previousSelection.length; i++) {
if ($scope.selectModel.indexOf(previousSelection[i]) == -1) {
// previousSelection[i] was deselected
}
}
// Set the previous selection to the current selection
previousSelection = $scope.selectModel;
}

Dynamic HTML Form Entry

Is it possible to make an HTML form that responds to the number of things the user wants to send over?
That is, what I have now is:
<form ...>
<select ...>
<option>1</option>
<option>2</option>
...
</select>
***
</form>
When the user selects one of the options, *** should have
<input type="text" ...>
appear the number of times the user selected.
That is, if the user selected 5 from the options, then the user should see 5 input options. If he changes his mind selected 2 instead, then the page should update accordingly to show only 2 input options.
=====[EDIT]=====
I've changed the code to have the input just be text. The code I have does not work. It doesn't update the number of input fields.
<script type="text/javascript">
<!--
function updateOptions(nvars)
{
var n = nvars;
while(n>0) {
var newdiv1 = "<div>Var name: <input type=\"text\" name=\"var-name\"><br></div>";
var newdiv2 = "<div>Var type: <input type=\"text\" name=\"var-type\"><br></div>";
newdiv1.appendTo("#bloo");
newdiv2.appendTo("#bloo");
n--;
}
}
//-->
</script>
<h3>Create a table in the test db!<h3>
<form name="f1" method="POST" action="createTable.php">
Name of Table: <input type="text" name="table-name"><br>
No of vars: <input type="text" name="numvars" onChange="updateOptions(this.value)"><br>
<div id="bloo"></div>
</form>
It worked when I had a document.write instead of an appendTo, but I essentially want the page the remain the same save for the extra input fields after the user changes the value in the numvars field.
That's a good idea when you want the user to be able to upload an arbitrary number of files or something like that. You can do it with Javascript:
Have an empty DIV near the SELECT
Bind a function to the "onchange" event on the select element
In the function, read the value of the SELECT element and:
Empty the DIV
Create an equivalent number of <INPUT type="text"> inside the DIV
Do you need code? If you do, is Prototype OK?
OK, sorry for the delay, lots of work to do lately.
The following should be enough for you to get an idea. You'll have to study JS though, I don't even know what you're doing with the appendTo stuff in your question.
<html>
<head>
</head>
<body>
<form>
<select id="num" value="1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<div id="container">
<p>
<input type="text" name="var-name" />
<input type="text" name="var-type" />
</p>
</div>
</form>
<script type="text/javascript">
var selectElm = document.getElementById('num');
var containerElm = document.getElementById('container');
var update = function () {
containerElm.innerHTML = '';
for (var i = 0, l = selectElm.value; i < l; ++i) {
containerElm.innerHTML += '<p><input type="text" name="var-name" /><br /><input type="text" name="var-type" /></p>';
} // add a number of couples of <input> equal to selectElm.value
}
//the following stuff says that when <select> changes the function called "update" must fire. Most of the code is for compatibility across browsers.
var listen, evt;
if (document.attachEvent) {
listen = 'attachEvent';
evt = 'onchange' ;
} else {
listen = 'addEventListener';
evt = 'change';
}
try {
selectElm[listen](evt, update);
} catch (e) {
selectElm[listen](evt, update, false);
}
// You do the same in Prototype with a single line:
// selectElm.observe('change', update);
// jQuery also requires only a single line of code.
</script>
</body>
</html>
Yes use onChange event of your dropdown input field and show/hide your input fields.