Here is a simple html5 form with two select controls. Changing the selection in the first select generates a new list of options for the second select. Both have the "required" attribute, and an initially selected blank option. The odd bit is that I get a red validation outline around the second select control, without submitting the form. No tool-tip with an error message, just the outline.
<!DOCTYPE html>
<BODY>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
function select_update(srcCtrlId, DstCtrlId)
{
//alert(srcCtrlId+','+DstCtrlId+','+url);
sel1 = document.getElementById(srcCtrlId);
srcValue = sel1.value;
sel2 = document.getElementById(DstCtrlId);
while(sel2.options.length > 0) {
sel2.remove(0);
}
if (srcValue == '')
{
var oOption = new Option( '(no matches)', '', true, true );
sel2.add(oOption);
}
else
{
var oOption = new Option( '-- Select2 --', '', true, true );
sel2.add(oOption);
for(i=1; i<=5; ++i)
{
v = srcValue * 10 + i;
s = 'Select2, Option'+v;
var oOption = new Option( s, v, false, false );
sel2.add(oOption);
}
}
}
function jsValidatePage1()
{
alert('onSubmit');
return false;
return true;
}
</script>
<form onSubmit="return jsValidatePage1();">
<select name="select1" id="select1" size="1" onChange="select_update('select1','select2');" required>
<option value="" selected="selected">-- Select1 --</option>
<option value="1">Select1, Option1</option>
<option value="2">Select1, Option2</option>
<option value="3">Select1, Option3</option>
<option value="4">Select1, Option4</option>
<option value="5">Select1, Option5</option>
</select>
<br><br>
<select name="select2" id="select2" size="1" required>
<option value="" selected="selected">-- Select2 --</option>
<option value='' DISABLED>(empty)</option>
</select>
<br><br>
<select name="select3" id="select3" size="1" required>
<option value="" selected="selected">-- Select3 --</option>
<option value="1">Select3, Option1</option>
<option value="2">Select3, Option2</option>
<option value="3">Select3, Option3</option>
<option value="4">Select3, Option4</option>
<option value="5">Select3, Option5</option>
</select>
<br><br>
<input type="text" name="dummy" value="" required="">
<br><br>
<input type="submit">
</form>
</html>
fiddle here: https://jsfiddle.net/afg57g0u/1/
Run the code, and then select any option in the first select control.
The second lights up red immediately, but the other required controls do not, so it's not validating the whole form, just the second select control (sort-of).
This happens in Firefox 36.0.4. This does not happen on IE 11.0.17, Opera 28.0, Chrome 41.0.2272.101, or Safari 5.1.7 (duh). (on Win8 box)
I can find no other mention online of a similar problem. I have tried numerous approaches to disable or work-around this problem, but no luck.
Does anyone have any ideas? Is this a Firefox bug?
Remove required attribute from select before changing options. Add a mousedown listener to submit button and set the required attribute back on the select then. With id given to submit button:
submit = document.getElementById('submitbtn');
submit.addEventListener('mousedown',function() {
sel2.setAttribute('required',true);
});
working fiddle: https://jsfiddle.net/afg57g0u/2/
note, you should also add a listener for keydown where keycode is the enter button, and touchstart for touch devices. they should call the same function as the mousedown event.
Related
I have a datalist that looks like :
<datalist id="foodlist">
<option value="one" ></option
<option value="two" ></option>
<option value="three" ></option>
</datalist>
<input type="text" list="foodlist" autocomplete=true id="inputItem"/>
I want an event to fire when user selects on of the option in the list using JavaScript.
How to achieve it?
onClick, onChange does not seem to work.
I know this is kind of old, but I thought I should document it somewhere. If you're trying to detect input from a dropdown selection rather than a click per se, you can use the "input" event and check the type of the passed event object - cut/paste/keypress input will pass an "InputEvent" object, whereas a datalist selection will pass a generic "Event" object.
var textbox = document.getElementById("inputItem");
textbox.addEventListener("input", function(e){
var isInputEvent = (Object.prototype.toString.call(e).indexOf("InputEvent") > -1);
if(!isInputEvent)
alert("Selected: " + e.target.value);
}, false);
<datalist id="foodlist">
<option value="one" ></option>
<option value="two" ></option>
<option value="three" ></option>
</datalist>
<input type="text" list="foodlist" autocomplete=true id="inputItem"/>
<datalist id="foodlist">
<option value="one" ></option>
<option value="two" ></option>
<option value="three"></option>
</datalist>
<input id="txt" type="text" list="foodlist" autocomplete=true id="inputItem"/>
document.getElementById('txt').addEventListener('input', function () {
console.log('changed');
var val = document.getElementById("txt").value;
alert(val);
});
The datalist tag is only supported in some browsers. Here's simple trick to get selected value.
While this is 4 years old, I stumbled across it today, and ran into the cross browser issues that others have reported. I was able to solve this by listening to the keyup event on the input field, and then checking the event type.
<input type="text" name="field_name" id="field_id" list="fields_list">
<datalist id="fields_list"></datalist>
<script>
var fieldInput = document.getElementById("field_id");
fieldInput.addEventListener('keyup', function(e) { if (isKeyboardEvent(e)) { myFunction(); } });
function isKeyboardEvent(e) {
return (e instanceof KeyboardEvent);
}
function myFunction() {
/* function that does something only on keyboard input */
}
</script>
Actual key strokes will be KeyboardEvent while a datalist option click will be simply be an Event.
Confirmed working in Chrome, Firefox, and Edge.
enter image description hereI want to pass the option value to another page. For this purpose I have some options. Besides there is an "other" option where an input field is hidden. My javascript code works i.e; selection of "others" appear the desired text input. But while passing the value (submitting) the "other" option (input field) pass the value but not the regular option.
function CheckColors(val) {
var element = document.getElementById('color_change');
if (val == 'pick a color' || val == 'others')
element.style.display = 'block';
else
element.style.display = 'none';
}
<form action="action_dropdown.php" method="post">
<select name="color" onchange='CheckColors(this.value);'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type="text" name="color" id="color_change" style='display:none;' />
<input value="calculation" type="submit">
</form>
$myVariable = $_POST["color"];
echo $myVariable;
I expect my output would be red/ blue/ (while selecting any of them).
Again I want my output would be yellow (when I choose "ohters" and input "yellow".)
Being a novice I Hope your cordial cooperation.
You need to rename your input element by any other as below:
<form action="action_dropdown.php" method="post">
<select name="color" onchange='CheckColors(this.value);'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type="text" name="othercolor" id="color_change" style='display:none;' />
<input value="calculation" type="submit">
</form>
And when your form is submitted, you need to check whether othercolor is set or not. Thus you can get color value like below:
$selectedColor = ($_POST['color'] == "others" ) ? $_POST['othercolor']: $_POST['color'];
Thus, you will be able to access both select and input values. Hope it helps you!
enter image description here
This error message keeps opening on console.
And I am using Ember.js
I am trying to make a drop-down and whenever on option from a drop-down is clicked, a form should be made based on what an option is chosen. For example, there are 3 options on dropdown: name, text, drop-down. When a user click a text, a text form should be created below. I already made an dropdown and tried to implement by writing document.write(" < /h1>"), but it keeps saying uncaught syntax error. Can someone help me please?
<script type="text/javascript">
function clicking(option) {
if (option === "name")
//document.write("<h1>Hello<h1>");
}
</script>
<h1>Data Form Test</h1>
<div id="dropdown">
<form>
<select id="selectBox" onchange="clicking(this)">
<option value="" disabled="disabled" selected="selected" style="display:none">Please select a option</option>
<option value="name">Name</option>
<option value="title">Title</option>
<option value="text">Text</option>
<option value="check-box">Check-box</option>
<option value="drop-down">Drop-down</option>
<option value="calendar">Calendar</option>
</select>
</form>
</div>
<div id="div1"></div>
<script type="text/javascript">
function clicking(option) {
if (option == "name"){
//document.write("<h1>Hello<h1>");
}
}
</script>
and on html
onchange="clicking(this.value)"
You can't access your selected value via option, you need to use property value instead. In my example I changed option with event.
To write some HTML/text into div/selector use .innerHTML method instead of document.write.
See working example.
function clicking(event) {
if (event.value === "name")
document.getElementById('div1').innerHTML = "<h1>Hello<h1>";
}
<h1>Data Form Test</h1>
<div id="dropdown">
<form>
<select id="selectBox" onchange="clicking(this)">
<option value="" disabled="disabled" selected="selected" style="display:none">Please select a option</option>
<option value="name">Name</option>
<option value="title">Title</option>
<option value="text">Text</option>
<option value="check-box">Check-box</option>
<option value="drop-down">Drop-down</option>
<option value="calendar">Calendar</option>
</select>
</form>
</div>
<div id="div1"></div>
If you would like to use your form to perform for example an ajax request. Here is another example I created for you.
I used addEventListener to show to different approach of handling your clicking function.
Read my comments.
// Our selectors
var form = document.getElementById('example-form');
var select = document.getElementById('selectBox');
var result = document.getElementById('result');
// Let's add an event listener to our form, we will listen whenever we submit the form
form.addEventListener('submit', function(e) {
var elements = this.querySelectorAll('input, select');
var formData = {};
for(i = 0; i < elements.length; i++) {
var element = elements[i];
Object.assign(formData, { [element.name] : element.value })
}
console.log(formData);
// Now you can perform some ajax call eg.
// I've commented it out, but code works, you just need to replace url
//$.ajax({
// url: 'http://example.com/action/url/',
// type: 'post',
// data: formData, // our form data
// success: function(response) {
// result.innerHTML = response;
// }
//})
// Prevent Page from autoreloading
e.preventDefault();
return false;
});
// Another approach of handling your clicking function is by passing eventListener to select
select.addEventListener('change', function(e) {
// Log
//console.log(e.target.value);
// We can use switch here for example
// Code becomes more readable
switch (e.target.value) {
case 'name':
case 'title':
case 'text':
result.innerHTML = '<h1>Hello ' + e.target.value + '</h1>';
default:
break;
}
});
<form id="example-form">
<select id="selectBox" name="selectBox">
<option value="" disabled="disabled" selected="selected" style="display:none">Please select a option</option>
<option value="name">Name</option>
<option value="title">Title</option>
<option value="text">Text</option>
<option value="check-box">Check-box</option>
<option value="drop-down">Drop-down</option>
<option value="calendar">Calendar</option>
</select>
<input name="example1" value="" placeholder="example input 1" />
<input name="example2" value="" placeholder="example input 2" />
<button type="submit">Submit me</button>
</form>
<div id="result"></div>
I have a select form element with various options. One of the options is "other". So when "other" is selected a hidden field is displayed for the user to enter the value not on the list. All that works fine. The problem is when a user selects any of the other options and submits the form, the value is not passed. Whereas, if the "other" option is selected and fills the text box then submits the form, the value of the text box is passed.
this is the select and the hidden text field:
<select name="memo" required class="newtxtbox" id="memo" onchange='checkvalue()'>
<option disabled="disabled" selected="selected">Select</option>
<option value="Donation for Bulletin">Bulletin</option>
<option value="Donation for Care Ministry">Care Ministry</option>
<option value="Donation for Cathedral Choir">Cathedral Choir</option>
<option value="Donation for Other">Other - (please specify below) </option>
</select>
<input type="text" style="display:none" name="memo" id="other">
and this is JavaScript:
function checkvalue()
{
if(document.getElementById('memo').value == 'Donation for Other') {
document.getElementById('other').style.display='block';
}
else {
document.getElementById('other').style.display='none';
}
}
I am sure i am missing something small but can't figure out what it is.
Here is a visual example of a small workaround. What I did was simply changing the name attribute of each element. I have added a CSS rule that displays the element with name="memo" as blue. The element that is blue will be sent to the server.
I have also expanded the javascript code so that you can test it out here on SO. You don't have to include the code after // added for testing purpose in your code. Click on "run code snippet" and try the submit button.
function checkvalue() {
var select = document.getElementById('memo');
var input = document.getElementById('other');
if (select.value == 'Donation for Other') {
document.getElementById('other').style.display = 'block';
select.name = '';
input.name = 'memo'; // form `memo` will now contain this input
} else {
document.getElementById('other').style.display = 'none';
select.name = 'memo';
input.name = '';
}
}
// added for testing purpose
document.getElementById('test').addEventListener('submit', function(e) {
e.preventDefault(); // no no submit
// FormData is HTML5 js object that contains ... data from the form ...
var fd = new FormData(this);
// .entries() isn't widely supported yet.
for (var tuple of fd.entries()) {
console.log(tuple[0] + ' contains value "' + tuple[1] + '"');
}
});
/*
added this for visibility of changes
element that is blue is being sent
*/
input[name="memo"],
select[name="memo"] {
background-color: lightblue;
}
<form id="test">
<select name="memo" required class="newtxtbox" id="memo" onchange='checkvalue()'>
<option disabled="disabled" selected="selected">Select</option>
<option value="Donation for Bulletin">Bulletin</option>
<option value="Donation for Care Ministry">Care Ministry</option>
<option value="Donation for Cathedral Choir">Cathedral Choir</option>
<option value="Donation for Other">Other - (please specify below) </option>
</select>
<input type="text" style="display:none" id="other">
<input type="submit" value="submit" />
</form>
I have the following HTML Select Box
<select id="orderByItem" name="orderByItem">
<option selected="" value="Status">Status</option>
<option value="ABCD">ABCD</option>
</select>
'Status' option is selected. Now when I remove the 'ABCD' option through javascript it gets replaced by None
This is the javascript I use
$("#orderByItem option[value='ABCD']").remove();
I am not sure how 'None' gets into the select, and this is causing major problems.
Try this http://jsfiddle.net/1q97q8z6/1/
HTML
<select id="orderByItem" name="orderByItem">
<option selected="" value="Status">Status</option>
<option value="Status2">Status2</option>
<option value="ABCD">ABCD</option>
</select>
<input type="button" name="but" id="but" Value="click"/>
JS
$( "#but" ).click(function() {
$("#orderByItem option[value='ABCD']").remove();
$("#orderByItem").get(0).selectedIndex = 1;
var tempVal = $("#orderByItem").val();
alert(tempVal);
});
var x = document.getElementById("orderByItem");
x.remove(x.selectedIndex);
Reference w3schools