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
Related
I have a simple form with chosen as jquery library. I require that the input values are in a single variable idb as they are utilized later in a regex expression on that variable. Currently the way it works is that they are placed in separate variables idb like this: &idb=02&idb=03&idb=04 and I want them to appear like this: idb=05%2C+06%2C+07.
here is my code:
<form action="./index.html" method="GET">
Device Id: <select data-placeholder="Input here device id" multiple class="chosen-select" name="idb">
<option value=""></option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
</select>
<input type="submit" value="Submit"/>
</form>
<script type="text/javascript">
$('.chosen-select').chosen({}).change( function(obj, result) {
console.debug("changed: %o", arguments);
console.log("selected: " + result.selected);
});
</script>
You can get your expected output by using a hidden input that stores the value for you.
You just need to listen for the change event on the <select /> and update the hidden input accordingly.
Short example:
$(function() {
$('.chosen-select').chosen({}).change(function() {
let selectedOptions = [].slice.call(this.selectedOptions);
let optionValues = selectedOptions.map(o => o.value);
$(".idb").val(optionValues.join(","));
});
// to show the output in demo, remove this
$('form').submit(function(ev) {
ev.preventDefault();
console.log($('form').serialize());
});
});
.chosen-select { width: 300px; }
<link href="https://unpkg.com/chosen-js#1.8.7/chosen.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/chosen-js#1.8.7/chosen.jquery.min.js"></script>
<form action="./index.html" method="GET">
Device Id:
<input type="hidden" value="" name="idb" class="idb" />
<select data-placeholder="Input here device id" multiple class="chosen-select">
<option value="" hidden></option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
</select>
<input type="submit" value="WyĆlij" />
</form>
If you want the result as an array rather then a comma-separated string, you could try using idb[] instead of idb as the input name.
(If your backend supports this)
$(function() {
$('.chosen-select').chosen({}).change(function(el) {
let selectedOptions = [].slice.call(this.selectedOptions);
let optionValues = selectedOptions.map(o => o.value);
$(".idb").val(optionValues.join(","));
});
// to show the output
$('form').submit(function(ev) {
ev.preventDefault();
console.log($('form').serialize());
});
});
Here is what I want to achieve. I have a requirement in which there is one dropdown for country codes and another input field for mobile number. I want to send country code and mobile input value as combined value so for that I am using a hidden field. When not using a hidden field it is easy to change value of a third tag element but that will not send value when form is submitted. So hidden field has to be used. So I have tried doing this but it is not changing value of hidden field.
<html>
<head>
<script language="javascript">
var dropdown = '';
var mobilenum = '';
function calldropdown()
{
dropdown = document.getElementById("country_code_id").value;
return dropdown;
}
function calltxtfield()
{
mobilenum = document.getElementById("mobileid").value;
return mobilenum;
}
function codemobile()
{
document.getElementById("codemobileid").value = calldropdown() + ' ' + calltxtfield;
alert(document.getElementById("codemobileid").value);
}
</script>
</head>
<body>
<form>
<select name="country_code" id="country_code_id" onchange="calldropdown()">
<option value="">Select</option>
<option value="+975">Bhutan</option>
<option value="+977">Nepal</option>
<option value="+94">Sri Lanka</option>
</select>
<input type="text" name="mobile" id="mobileid" onchange="calltxtfield()" />
<input type="hidden" name="codemobile" id="codemobileid" value="" />
<input type="submit" name="submit" value="Submit" onclick="return codemobile();" />
</form>
</body>
</html>
I can not explain it right now, but name="codemobile" seems to silently shadow function codemobile(). Rename one of the two and it works.
Also note that right now you are concatenating the function body (... + calltxtfield;), it should rather be ... + calltxtfield();
The code I am currently trying to work out is I have one drop down box that is a required drop-down. If "Complete" is selected from that drop down box a text box appears. If "Abandon" is selected from that drop down box a second drop down box appears with other options.
I am trying to add validation onto those 2nd options after the first drop down is selected. In my code I have the first drop down box "ActionDD" marked as a required field. But I can not do that with the textbox "REMtextBox" or the "ReasonDD" drop down box since they will never appear at the same time.
Here is the code for my form
<form name=StudentForm action="javascript:window.close();">
<div class="DDbox">
<select name="Action" id="ActionDD" required onchange="showHide()">
<option value="">Action:</option>
<option value="complete">Complete</option>
<option value="abandon">Abandon</option>
<option value="transfer">Transfer</option>
</select>
</div>
<br>
<div class="COMPLETEbox" id="COMPLETEbox" >
<input class="hidden-items" type="text" name="RemNUM" id="REMtextBox" placeholder="Remedy Number" min="1" maxlength="10" style="display:none;"/><br>
<select class="hidden-items" name="Reason" id="ReasonDD" style="display:none;">
<option value="">Reason:</option>
<option value="NoShow">No Show</option>
<option value="Unfixable">Unfixable</option>
<option value="other">Other</option>
</select><br><br>
<br>
<input type="submit" value="submit" onclick="checkform();">
</div>
</form>
Then here is the code I have been working on for my JavaScript to check conditions when the Submit button is pressed.
function checkform() {
if (document.getElementById('ActionDD').value ="abandon" && (document.getElementById('ReasonDD').value =""))
{
validationMessage = validationMessage + 'Enter Reason';
valid = false;
}
else valid = true;
}
</script>
I am looking for a solution for how to check if the first drop down has a value selected, then whatever corresponding textbox or drop down appears from the choice that was made in the first drop down has a value selected.
Thanks in advance for any help.
Try the below code.
Idea is to set/remove the 'required' attribute during onchange of the ActionDD drop-down. Hope it helps.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>HTML code with text-boxes and drop-downs</title>
<script type="text/javascript">
var actionBox,
reasonBox,
completeBox,
remTextBox,
selectedAction,
isFormValid,
validationMessage = "Not all required fields are filled in; ";
function init() {
actionBox = document.getElementById('ActionDD');
reasonBox = document.getElementById('ReasonDD');
completeBox = document.getElementById('COMPLETEbox');
remTextBox = document.getElementById('REMtextBox');
selectedAction = actionBox.value;
remTextBox.style.display = 'none';
remTextBox.removeAttribute("required");
reasonBox.style.display = 'none';
reasonBox.removeAttribute("required");
isFormValid = false;
}
function checkform() {
// Include other logic if needed here...
}
function showHide() {
init();
if (selectedAction == 'complete') {
remTextBox.style.display = 'block';
remTextBox.setAttribute("required", "required");
}
else if (selectedAction == 'abandon') {
reasonBox.style.display = 'block';
reasonBox.setAttribute("required", "required");
}
}
</script>
<style>
</style>
</head>
<body>
<form name="StudentForm">
<div class="DDbox">
<select name="Action" id="ActionDD" required onchange="showHide()">
<option value="">Action:</option>
<option value="complete">Complete</option>
<option value="abandon">Abandon</option>
<option value="transfer">Transfer</option>
</select>
</div>
<br>
<div class="COMPLETEbox" id="COMPLETEbox">
<input class="hidden-items" type="text" name="RemNUM" id="REMtextBox" placeholder="Remedy Number" min="1" maxlength="10" style="display:none;" /><br>
<select class="hidden-items" name="Reason" id="ReasonDD" style="display:none;">
<option value="">Reason:</option>
<option value="NoShow">No Show</option>
<option value="Unfixable">Unfixable</option>
<option value="other">Other</option>
</select>
<br>
<br>
<br>
<input type="submit" value="submit" onclick="checkform();">
</div>
</form>
</body>
</html>
You have a little mistake in your JavaScript validation function,
instead of a comparison (x==y) you did an assignment (x=y).
In addition to that, there is a slightly different technique for getting aselectbox selected value.
This is your code with a little change:
function checkform() {
var action = document.getElementById('ActionDD'),
reason = document.getElementById('ReasonDD');
if (action.options[action.selectedIndex].value =="abandon" && reason.options[reason.selectedIndex].value =="")
{
validationMessage = validationMessage + 'Enter Reason';
valid = false;
}
else valid = true;
}
Hope it helps a bit.
Try this.
function checkform() {
if (document.getElementById('ActionDD').value =="abandon" && (document.getElementById('ReasonDD').value ==""))
{
//Your validation message
return false;
}
else return true;
}
</script>
onchange()
function showHide() {
if(document.getElementById('ActionDD').value =="abandon")
{
document.getElementById("ReasonDD").style.display= 'block';
document.getElementById("ReasonDD").required = true;
}
else
document.getElementById("ReasonDD").style.display= 'none';
}
Change your html little bit.Remove checkform() from button and add to form as shown below.
<form name=StudentForm onsubmit="return checkform()" action="javascript:window.close();">
i want to move the selected item of a select tag (list box) into a text box after clicking a button. i am using the below code
<html>
<head>
<script type="text/javascript">
function copy()
{
var sel = document.getElementById('lb').value;
document.getElementById('FileName').value = sel;
}
</script>
</head>
<body>
<form name="frm1" id="frm1">
<select id="lb" name="lb" size="5">
<option value="abc.txt">abc.txt</option>
<option value="def.txt">def.txt</option>
</select>
<input type="button" value=">>" name="btn_move" id="btn_move" onclick="copy()">
<input type="text" name="FileName" id="FileName">
</form>
</body>
</html>
the above code works properly in google chrome browser but it does not work when i run the page in IE. can anyone tell me whats the problem in the code and kindly suggest a javascript or any other code which is compatible ith both google chrome and IE.
above code works after i allow the pop up that comes but
actually the below code is not working.
<html>
<head>
<title>FILE</title>
<style>
body{background-color:#b0c4de;}
#OutBound{text-align:center;}
#btn_sbmt{position:absolute;top:150px;left:700px;}
#div_text_label{position:absolute;top:50px;left:200px;}
#lbl2{position:absolute;top:80px;left:200px;}
#selected_list{position:absolute;width:300px;top:80px;left:335px;}
#btn_move{position:absolute;top:100px;left:650px;}
#FileName{position:absolute;width:300px;top:100px;left:700px;}
</style>
<script type="text/javascript">
function load_list()
{
document.getElementById('div_main_select').style.display="none";
var textbox = document.getElementById('pattern');
var listbox = document.getElementById('selected_list');
var mainListbox = document.getElementById('lb');
listbox.innerHTML = '';
for (var childIndex = 0; childIndex < mainListbox.children.length; childIndex++)
{
var child = mainListbox.children[childIndex];
option = document.createElement('option');
option.innerHTML = child.innerHTML;
listbox.appendChild(option);
}
alert (load_list_1);
}
function get_list()
{
var textbox = document.getElementById('pattern');
var listbox = document.getElementById('selected_list');
var mainListbox = document.getElementById('lb');
listbox.innerHTML = '';
for (var childIndex = 0; childIndex < mainListbox.children.length; childIndex++)
{
var child = mainListbox.children[childIndex];
if (child.innerHTML.search(textbox.value) != -1)
{
option = document.createElement('option');
option.innerHTML = child.innerHTML;
listbox.appendChild(option);
}
}
alert (get_list_1);
}
function copy()
{
var sel = document.getElementById('selected_list').value;
document.getElementById('FileName').value = sel;
alert (copy_1);
}
</script>
</head>
<body style="color: black; background-color: rgb(255, 255, 255); background-image: url(background-1204x927.jpg);" BGCOLOR="#ffffff" text="black" link="#B03060" vlink="#B03060" onload="load_list()">
<hr>
<form id="OutBound" name="OutBound" action="" method="GET">
<div style="text-align:center;" id="div_text_label" name="div_text_label">
<label id="lbl1" name="lbl1">search :</label>
<input type="text" name="pattern" id="pattern" onKeyUp="get_list()">
</div>
<div style="text-align:center;" id="div_main_select" name="div_main_select">
<select id="lb" name="lb" size="5">
<option value="abc.txt">abc.txt</option>
<option value="def.txt">def.txt</option>
</select>
</div>
<label id="lbl2" name="lbl2">File List:</label>
<select id="selected_list" name="selected_list" size="5">
</select><br>
<input type="button" value=">>" name="btn_move" id="btn_move" onclick="copy()">
<input type="text" name="FileName" id="FileName">
<input type="submit" name="btn_sbmt" id="btn_sbmt" value="MOVE FILES">
</form>
</body>
</html>
the page works like this..
1) there is a list box (lb) populated with some items.
2) there is 1 more empty list box (selected_list).
3) when the page form is loaded load_list() function is called which loads the empty list box (selected_list) with the contents of the original list box (lb).
4) when someone enters a word or a letter in the search text box then get_list() function is called which filters the files according to the words entered.
5) when a filename is selected in the selected_list and >> button is pressed, the copy() function is called and the filename is copied to the FILENAME text box.
but this all is not working in IE but it works in google chrome. can anyone fix the code so that it works with IE also.
Try this:
function copy() {
var sel = document.getElementById('lb');
document.getElementById('FileName').value = sel.options[sel.selectedIndex].text;
}
The code works fine (see fiddle in IE)
If you are opening the file from local file system, the IE may ask your permission to run script. You should click "Allow Blocked Content" for it to work
See image below
Try this using jQuery (1.10.1)
function copy()
{
$("#FileName").val($("#lb").val());
}
http://jsfiddle.net/7Axu8/
Update
http://jsbin.com/onayow/1
I can read out text field values, but when I try to find the selected radio button, I get nothing.
$(document).ready(function(){
$("form#create_form").submit(function() {
var title = $('#title').attr('value');
var owner = $('#owner').attr('value');
var users = $('#users').attr('value');
var groups = $('#groups').attr('value');
var begin_date = $('#begin_date').attr('value');
var end_date = $('#end_date').attr('value');
// get selected radio button
var type = '';
for (i=0; i<document.forms[0].type.length; i++) {
if (document.forms[0].type[i].checked) {
type = document.forms[0].type[i].value;
}
}
HTML:
<div class="create-new">
<form id="create_form" name="create_form" action="" method="post">
...
<input name="type" id="type" value="individuel" type="radio" /> Individuel <br/>
<input name="type" id="type" value="course" type="radio" /> Course <br/>
<button class="n" type="submit">Create</button>
</form>
What am I doing wrong?
I would suggest an alternative method to getting the selected radio button (since you are already using jQuery):
$('input:radio[name=type]:checked').val();
This solution is an example on .val().
The above solution is much more succinct, and you avoid any conflicts in the future if other forms are added (i.e you can avoid the potentially hazardous document.forms[0]).
Update
I tested your original function with the following fiddle and it works:
http://jsfiddle.net/nujh2/
The only change I made was adding a var in front of the loop variable i.