I've been spending the past couple of days researching on W3C and SO (this being the closest issue I found to mine), to dynamically load a "static" JSON into a dynamically created datalist.
More details on what I'm trying to achieve - I'm trying to create a form to add records to a database; default form allows to add one record, but there's a button to dynamically add another set of empty fields to submit multiple records at once. Once all form is filled in, this is sent to PHP for processing. I'm using bootstrap for the frontend (though I'll try to clean the code for readability).
Load page for the first time, save the JSON into a "HTML variable". Note the page has already one datalist.
Should the user click on the button to add another set of fields, these appear (including an additional datalist)
Objective: this newly created datalist should be populated with the JSON saved in the HTML Variable in point no. 1
Two questions:
Is this doable? As in, do HTML vars have a persistent scope even if I change the DOM?
If so, what am I doing wrong in the code below?
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?do=addnewstructure" enctype="multipart/form-data">
<input list="datalistOptions" id="datalisttype1" name="deftype_ent[]" placeholder="Type to search..." onFocus="populate_datalist(types_json);">
<datalist id="datalistOptions">
<option value="first">First persistent option</option>
</datalist>
</div>
<div>
<label for="value_ent">Name</label>
<input type="text" name="defvalue_ent[]" id="value_ent">
</div>
<div>
<label for="relevance_ent">Relevance</label>
<select id="relevance_ent" name="relevance_ent">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<script>
var types_json = document.createElement("list_of_types");
var dataList = document.getElementById("datalisttype1");
var types_json = [<?php
echo json_encode($results_json); // This is coming from backend, it is valid JSON
?>];
// Loop over the JSON array.
function populate_datalist(which_dl)
{
which_dl.forEach(function(item) {
var option = document.createElement('option');
option.value = item.type_id;
option.text = item.name;
dataList.appendChild(option);
});
}
</script>
<button type="submit">Add</button>
</form>
I know this may be a noob question as I just started with js, only did BE languages so far. Thanks for your help! :)
For anyone stumbling upon this code in the future - I got it work and there are a variety of reasons why it wasn't working previously.
In brief:
function appendChild wasn't attaching options to the datalist but to the input
the JSON, although valid, didn't have single quotes
some of the variables weren't initialised, and failed when called for a function
the function was declared after the datalist (e.g. called before it was declared)
some others
TLDR; do not rely on the code above, even as an inspiration :)
Related
So basically I have an HTML form that uses a dropdown box. When the form is submitted it calls a function I wrote. However after this form is submitted it proceeds to another HTML page where the data form the form needs to be used but it is no longer available and I don't know why.
<body>
<h1>Select your input:</h1>
<form id="customize" name="customize" method="get" action="index.html" onSubmit="return checkInfo();">
<p>Please select the right value</p>
<select id="val1" name="val1">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
<input type="submit" value="submit" />
</form>
</body>
function checkInfo() {
var1 = document.getElementById('var1').value;
return true;
}
I left out some of the javascript code that involved other variables and was irrelevant for this issue which is why it always returns true because I did not show the option for returning false. I suspect this either has to do with a variable that isn't global or for some reason this var1 cannot be accessed from a different function within the same Javascript file. Basically the form is submitted, the function is called, the variable is created and assigned the data, and then when the function returns true another HTML page is loaded which calls a separate function in the same Javascript file that uses that var1 to make a calculation.
I ended up using a local storage API recommended to my by a user below. Here's the link I used: https://www.w3schools.com/html/html5_webstorage.asp
State does not persist when new pages are loaded. If you assign data to a variable on one page, and then navigate to a new page, the script (even if it is the same file) is reloaded.
You can, however, use APIs like localStorage or sessionStorage to persist data across pages, or you can look at a Single Page Application solution that uses in-page routing to maintain the same state/context by merely simulating page navigation.
First of all:
document.getElementById('var1').value;
should be
document.getElementById('val1').value;
Also, I don't know what you try to do, but as far as I know onSubmit() does not send data with the request so letting it return something should do nothing (considering that what you wish to do is to send a http request, meaning to load a new page)
You are using the GET method to pass variables using the URL (see HTTP Methods).
Javascript has an experimental URLSearchParams interface which define utility methods to work with the query string of a URL... Mozilla Docs. You can use this alongside getElementById to set the value on load in index.html.
<html>
<body>
<h1>Select your input:</h1>
<form id="customize" name="customize" method="get" action="index.html" onSubmit="return checkInfo();">
<p>Please select the right value</p>
<select id="selectVal" name="val1">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
<input type="submit" value="submit" />
</form>
<script>
let params = new URLSearchParams(document.location.search.substring(1))
let value = params.get('val1')
var element = document.getElementById('selectVal');
element.value = value
</script>
</body>
I have a project in which I must do something like this:
when a user's page loads, he gets a personalized select box (with some options generated by PHP for him) and then, when he changes the option, I must change the rest of the content (on the same page).
for example, let the select box for a kind of user be:
Main content
Tools
Now, my idea was to have a
<form action="processing.php">
<select name="choice" onChange="submit();"> etc. which should pass the user's choice to processing.php. The problem is, I want the first option to be automatically selected and the content for that option to appear when the page loads - somehow like the first option to be automatically submitted.
Also, different kind of users should get different options, and I thought I can use a single page to process these requests. Is this achievable?
Can you please help me with an idea on how to submit that form automatically with the first generated option? Thank you.
You can use the onChange Event of the selection. In the handler you can then do the redirect
let sel = document.getElementById('yourselect');
let form = document.getElementById('yourform');
sel.onchange = function() {
form.submit()
}
You can easily bind the select change with Javascript. Here is the example with jQuery:
$('#mySelect').on('change', function(){
// Do your staff
$('#myForm').submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<select id="mySelect" method="post" action="processing.php" name="select_name">
<option value="">Select One</option>
<option value="http://google.com">Google</option>
</select>
</form>
I have a form which has a select input
<select class="form-control" id="taskSelect" name="taskSelect" >
<option value="" name="task" id="task">Select One</option>
<option value="1" name="task">1</option>
<option value="2" name="task">2</option>
</select>
Now depending on what is selected, a sub form appears. I have set up an example JSFiddle
Now I need to pass any data that has been completed to a function
submitHandler: function(form){
var params = $(form).serialize();
generatePDF(params);
}
Normally to get the input I would do something like this
$('#someInput').val();
But in my situation I dont know what will be inputted so I am serializing things. If selection 1 is selected, then I only need the inputs for the fields it displays, not the fields for selection 2. Serializing seems to capture all inputs, not the ones that I want.
What is the best way to only pass the inputted data to the function?
Thanks
Maybe you can try splitting the form into 2 parts. Once this is done you can serialize only the selected form. This is assuming you don't have any other form elements outside the two tasks you mentioned above
I have a project im working on, that needs a javascript OnChange Script for a dropdown box on media upload page.
I have a drop-down box with 2 options -'Yes' and 'No'. If the user selects 'No' i don't want the form to submit and possibly display a message saying why.
Is anyone able to provide a script to do this? I have to enter this on the attribute itself (eah attribute has the ability to have a OnChange script), i can change the attribute references to the specific ones needed. More of a general 'formula' for the script is needed.
Maybe i'm too vague and its not possible to make on the information i have given you.
Thanks in advance,
T.
first, write javascript code like this
<script>
function output()
{
var input = document.getElementById('input').value;
if(input==0){
alert("WHY???");
document.getElementById("out").value="why?";
}else{
document.getElementById("out").value="Ok";
}
}
</script>
and for the html code
<form>
<select name="input" id="input" onchange="output()">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
<input type="text" id="out" name="out">
</form>
note: javascript not java
I was working on a script that grabs the value from the selected option in a drop down select list and assigns it to an object. The only problem I'm having is that it's saying I have a null object.
The .js is as follows:
var s = document.getElementById('mode');
alert(s.options[s.options.selectedIndex].value);
function selectValue(){
yo.newSelect(s.options[s.options.selectedIndex].value);
return true;
}
The HTML is as follows:
<div id="text_editing">
<form action="javascript:;" method="post" onsubmit="editHomePage()">
<select name="CYD" id="mode" onchange="selectValue()">
<option value="Home">Home</option>
<option value="About">About</option>
<option value="Contact">Contact</option>
</select>
<textarea name="sexyText" row="500" col=500">
</textarea>
<input value="submit" name="text_submit" type="submit" onclick="selectValue()">
</form>
I'm just looking for a solution in plain js. I not interested in using jQuery for such a small site.
If all your options have a value, you can simply write:
alert(s.value);
which will return the value of the first selected option (so not suitable for multiple selects with more than one selected).
Incidentally, from your listener you could do:
<input type="submit" onclick="selectValue(this)">
then in the function:
function selectValue(el) {
alert(el.form.mode.value);
}
It looks like initially, none of the options are selected; therefore, s.options[s.options.selectedIndex] would be null when the page first loads.
I would recommend using the Firebug plugin for Firefox to step through your code; you can easily identify these kinds of issues using the debugger.