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 :)
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 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
My question is about java script, i want to put or add a div or button or input inside select tag using java script.
I using jquery.sumoselect plugin that make you multiple checkbox, but when i want to add some DIVs inside select tag is showing outside the list.
i want the div inside select element like this picture : http://i.stack.imgur.com/Xd6FX.jpg
this is my html code
<div class="select-box-style right">
<div class="your-list-title">Your Lists</div>
<select multiple="multiple" class="md_what_get right SlectBox">
<option selected value="electronics">Electronics</option>
<option value="games">Video Games</option>
<option value="books">Books</option>
<option value="others">Others</option>
<option value="others"><input type="text" name="lname"></option>
</select>
<div class="add-list-box">
<input type="text" class="input-add-list"/>
<label class="label-spcbtn-blue spr" >Add</label>
</div>
</div>
and this how to call the plugin:
<script type="text/javascript">
$(document).ready(function () {
$('.SlectBox').SumoSelect();
});
</script>
thank you for helping!
....
Update!
see this link http://wenzhixin.net.cn/p/multiple-select/docs/
On The Filter1 you can see the input search inside select element, how can i do that?
Neither SumoSelect or MultipleSelect (as is) supports the feature you are looking at. But, first, some clarification needed:
<select> boxes are a standard HTML tag, that accepts no other tags than <optgroup> or <option>. see here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select
SumoSelect and MultipleSelect are both Javascript plugins that “converts” real selects into custom built <div> tags, with javascript to handle the logic.
That said, you can either modify/extend those plugins to create the desired <div> or you can build your own “<select> into <div> converter”.
But, for the sake of simplicity, you could just create a <div> with all the desired functionality, using regular plain old checkboxes, and hiding/displaying the whole <div> according to your UX flow/needs.
I have a select form field that I want to mark as "readonly", as in the user cannot modify the value, but the value is still submitted with the form. Using the disabled attribute prevents the user from changing the value, but does not submit the value with the form.
The readonly attribute is only available for input and textarea fields, but that's basically what I want. Is there any way to get that working?
Two possibilities I'm considering include:
Instead of disabling the select, disable all of the options and use CSS to gray out the select so it looks like its disabled.
Add a click event handler to the submit button so that it enables all of the disabled dropdown menus before submitting the form.
Disable the fields and then enable them before the form is submitted:
jQuery code:
jQuery(function ($) {
$('form').bind('submit', function () {
$(this).find(':input').prop('disabled', false);
});
});
<select disabled="disabled">
....
</select>
<input type="hidden" name="select_name" value="selected value" />
Where select_name is the name that you would normally give the <select>.
Another option.
<select name="myselect" disabled="disabled">
<option value="myselectedvalue" selected="selected">My Value</option>
....
</select>
<input type="hidden" name="myselect" value="myselectedvalue" />
Now with this one, I have noticed that depending on what webserver you are using, you may have to put the hidden input either before, or after the <select>.
If my memory serves me correctly, with IIS, you put it before, with Apache you put it after. As always, testing is key.
I`ve been looking for a solution for this, and since i didnt find a solution in this thread i did my own.
// With jQuery
$('#selectbox').focus(function(e) {
$(this).blur();
});
Simple, you just blur the field when you focus on it, something like disabling it, but you actually send its data.
I faced a slightly different scenario, in which I only wanted to not allow the user to change the selected value based on an earlier selectbox. What I ended up doing was just disabling all the other non-selected options in the selectbox using
$('#toSelect').find(':not(:selected)').prop('disabled',true);
it dows not work with the :input selector for select fields, use this:
jQuery(function() {
jQuery('form').bind('submit', function() {
jQuery(this).find(':disabled').removeAttr('disabled');
});
});
Same solution suggested by Tres without using jQuery
<form onsubmit="document.getElementById('mysel').disabled = false;" action="..." method="GET">
<select id="mysel" disabled="disabled">....</select>
<input name="submit" id="submit" type="submit" value="SEND FORM">
</form>
This might help someone understand more, but obviously is less flexible than the jQuery one.
The easiest way i found was to create a tiny javascript function tied to your form :
function enablePath() {
document.getElementById('select_name').disabled= "";
}
and you call it in your form here :
<form action="act.php" method="POST" name="form_name" onSubmit="enablePath();">
Or you can call it in the function you use to check your form :)
I use next code for disable options in selections
<select class="sel big" id="form_code" name="code" readonly="readonly">
<option value="user_played_game" selected="true">1 Game</option>
<option value="coins" disabled="">2 Object</option>
<option value="event" disabled="">3 Object</option>
<option value="level" disabled="">4 Object</option>
<option value="game" disabled="">5 Object</option>
</select>
// Disable selection for options
$('select option:not(:selected)').each(function(){
$(this).attr('disabled', 'disabled');
});
Just add a line before submit.
$("#XYZ").removeAttr("disabled");
Or use some JavaScript to change the name of the select and set it to disabled. This way the select is still submitted, but using a name you aren't checking.
I whipped up a quick (Jquery only) plugin, that saves the value in a data field while an input is disabled.
This just means as long as the field is being disabled programmaticly through jquery using .prop() or .attr()... then accessing the value by .val(), .serialize() or .serializeArra() will always return the value even if disabled :)
Shameless plug: https://github.com/Jezternz/jq-disabled-inputs
Based on the solution of the Jordan, I created a function that automatically creates a hidden input with the same name and same value of the select you want to become invalid. The first parameter can be an id or a jquery element; the second is a Boolean optional parameter where "true" disables and "false" enables the input. If omitted, the second parameter switches the select between "enabled" and "disabled".
function changeSelectUserManipulation(obj, disable){
var $obj = ( typeof obj === 'string' )? $('#'+obj) : obj;
disable = disable? !!disable : !$obj.is(':disabled');
if(disable){
$obj.prop('disabled', true)
.after("<input type='hidden' id='select_user_manipulation_hidden_"+$obj.attr('id')+"' name='"+$obj.attr('name')+"' value='"+$obj.val()+"'>");
}else{
$obj.prop('disabled', false)
.next("#select_user_manipulation_hidden_"+$obj.attr('id')).remove();
}
}
changeSelectUserManipulation("select_id");
I found a workable solution: remove all the elements except the selected one. You can then change the style to something that looks disabled as well.
Using jQuery:
jQuery(function($) {
$('form').submit(function(){
$('select option:not(:selected)', this).remove();
});
});
<select id="example">
<option value="">please select</option>
<option value="0" >one</option>
<option value="1">two</option>
</select>
if (condition){
//you can't select
$("#example").find("option").css("display","none");
}else{
//you can select
$("#example").find("option").css("display","block");
}
Another option is to use the readonly attribute.
<select readonly="readonly">
....
</select>
With readonly the value is still submitted, the input field is grayed out and the user cannot edit it.
Edit:
Quoted from http://www.w3.org/TR/html401/interact/forms.html#adef-readonly:
Read-only elements receive focus but cannot be modified by the user.
Read-only elements are included in tabbing navigation.
Read-only elements may be successful.
When it says the element may be succesful, it means it may be submitted, as stated here: http://www.w3.org/TR/html401/interact/forms.html#successful-controls