This code works fine on IE, but fails on Chrome.
Theory: When you click on the input, the input marks with an X or when you hit again the X is deleted (just like a checkbox) , when any of these conditions are met, the script should send the forms Y ( if X is checked) or N (if X is empty ).
HTML
Note: The values are generated dynamically using the data from a external database).
<input type="text" READONLY id="65535" class="chk" iffalse="N" iftrue="Y" value=""
onclick="fchkboxclick();" />
JavaScript
function fchkboxclick() {
object = window.event.srcElement;
if (object.id == '65535') {
if (object.value == 'X') {
activevalue = object.getAttribute("iffalse");
objet.value = '';
} else {
activevalue = object.getAttribute("iftrue");
object.value = 'X';
}
} else {
if (object.value == 'X') {
sendevent(object.id, 'check', object.getAttribute("iffalse"));
} else {
sendevent(object.id, 'check', object.getAttribute("iftrue"));
}
}
}
When I run this on any version of IE, the forms (sendevent function) receive the value from the attribute (Y or N) but in Chrome I just receive X.
Any help would be appreciated. Thanks.
if you use an onclick event in an element, far easier to do this
<input onclick="dosomething(this);" />
Then your code can do
function dosomething(element) {
// element is the element that was clicked
}
Ok, i done with this:
<html>
<body>
<input type="checkbox" name="chb[]" id="pepe" class='chk' iffalse="N" iftrue="Y" value="0" onchange="validate()" />
<br/> Value sent
<input type="text" id="1234" value="" />
<script type="text/javascript">
var inputcb = document.getElementById('1234');
function validate() {
if (document.getElementById('pepe').checked) {
inputcb.value = document.getElementById('pepe').getAttribute("iftrue");
} else {
inputcb.value = document.getElementById('pepe').getAttribute("iffalse");
}
}
</script>
</body>
</html>
Related
Here's my current setup:
I have a barcode scanner in keyboard mode. I am trying to scan to a hidden and out of focus input.
The barcode I am trying to read is as follows: asterisk [barcode-info] asterisk.
<form method="post">
<input type="hidden" name="action" value="barcode-scan"/>
<input type="hidden" name="barcode-input" value="" id="barcode-input" onchange="this.form.submit()" />
</form>
When a barcode input is made, Javascript should capture it and update the "barcode-input" hidden input, which will then submit itself to the server.
Someone recommended trying to use a paste event listener, but it simply didn't seem to capture the input at all.
Update: because of wonderful suggestions below, I've been able to get the input working! The form will test to see if two specific inputs follow each other, then it will execute the next function. Otherwise, it will erase any information contained in the log const. Ultimately, yes, I got this working correctly!
document.addEventListener('keyup', function(e){
const log = document.getElementById('barcode-input');
log.textContent += ' ' + e.code;
document.getElementById('barcode-input').value = log.textContent;
if (log.textContent.startsWith(' ShiftLeft')) {
if (log.textContent.startsWith(' ShiftLeft Backslash')) {
document.getElementById('barcode-input').form.submit();
console.log('e.code, submit barcode info');
}
}
else {
log.textContent = '';
document.getElementById('barcode-input').value = '';
}
});
Without an input[type="text"] element on the screen, you will need to capture the keyboard input manually. Something along the lines of:
document.addEventListener('keydown', (ev) => {
if (ev.ctrlKey || ev.altKey) return; // Ignore command-like keys
if (ev.key == 'Enter') {
// ...submit the content here...
} else if (ev.key == 'Space') { // I think IE needs this
document.getElementById('barcode-input').value += ' ';
} else if (ev.key.length == 1) { // A character not a key like F12 or Backspace
document.getElementById('barcode-input').value += ev.key;
}
});
That should get you most of the way...
Alternatively, rather than looking for events on the input or values of the input (*'s), define an event on the value and use the input event to simply set the value.
Once input has stopped, be it 1 second (or most likely much less) then fire off the form.
If you have to place the cursor into input, then scan. your prob only option is to use autofocus attribute and hide the input as you cant focus a hidden element, though you also cant focus multiple so keep that in mind if you're looking to scan into multiple inputs, then you will have to show the inputs, no way around it.
For example
let elm = document.querySelector('input[name="barcode-input"]')
// watcher on the value, after 1 second, it invokes an event, i.e post form
let timer = 0
Object.defineProperty(window, 'barcode', {
get: function () { return this.value },
set: function (value) {
clearTimeout(timer)
this.value = value
timer = setTimeout(() => {
console.log('Post form')
}, 1000) // do some tests, tweak if much less then 1 second to input the value
}
})
// it should trigger input even if its a keyboard
elm.addEventListener("input", e => barcode = e.target.value)
// ignore, below this line..
// set a value of barcode at intervals, only when its stopped entering (>1 second), then will it fire the callback
let i = 0
let t = setInterval(() => {
barcode = (barcode || '')+"X"
if (i >= 40) clearInterval(t)
i++
}, 100)
// ignore... grab value from hidden input, put in #current
setInterval(() => document.querySelector('#current').innerHTML = barcode, 1000)
<input type="text" name="barcode-input" autofocus style="display:none" />
<div id="current"></div>
Here's demonstrator using keypress that scans the incoming key stream for *[ and captures the barcode until it sees ]*. Then it sends the code to the server. Although I've reproduced the form in your HTML, the code here doesn't use it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Working...
<form method="post">
<input type="hidden" name="action" value="barcode-scan"/>
<input type="hidden" name="barcode-input" value="" id="barcode-input" onchange="this.form.submit()" />
</form>
<p id="response"></p>
<script>
(function(){
"use strict";
const bcAst = '*';
const bcLeft = '[' ;
const bcRight = ']';
let barcodeIncoming = false;
let lastChar = 0;
let barcode = '';
document.addEventListener('keypress', function(e){
function sendCode(barcode) {
console.log(barcode);
let fd = new FormData();
fd.append('barcode', barcode);
fetch('myFile.php', {
method: 'POST',
body: fd
})
.then(resp=>{
resp.text().then(txt=>{document.getElementById('response').innerText = txt;})
});
}
console.log(e.key);
switch (e.key) {
case bcAst:
if (barcodeIncoming && (lastChar === bcRight)) {
barcodeIncoming = false;
sendCode(barcode);
}
break;
case (bcLeft):
if (lastChar === bcAst) {
barcodeIncoming = true;
barcode = '';
}
break;
case (bcRight):
break;
default:
barcode += (barcodeIncoming)?e.key:'';
break;
}
lastChar = e.key;
});
})();
</script>
</body>
</html>
The current server file is very rudimetary, but serves the purpose here:
<?php
if (isset($_POST['barcode'])) {
echo "Your barcode is {$_POST['barcode']}";
} else {
echo "No barcode found";
}
Note - this has had only basic testing. You'll want to improve its resilience against possible collisions with similar data in the key stream.
transfrom
<input type="hidden" name="barcode-input" value="" id="barcode-input" onchange="this.form.submit()" />
in
<input type="test" name="barcode-input" value="" id="barcode-input" onchange="this.form.submit()" style="display:none;" />
The issue here is that I have designed a basic website which takes in a users input on a form, what I then intend to do is print that value out to the console.log. however, when I check the console under developer tools in Google Chrome, all I get printed out is []length: 0__proto__: Array(0)
and not the value the user has inputted.
<input type="text" name="username" value="testuser">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function error() {
var error1 = [];
var list_of_values = [];
username_error = $('input[name="username"]').val();
if (!username_error){
error1.push('Fill in the username field.');
}
console.log(error1);
if (error1.length > 0){
for(let username_error of error1){
alert(username_error);
return false;
}
}
string = $('input[name="username"]').val('');
if(string.length <= 1){
for (let list_of_values of string){
string.push();
}
console.log(string);
return true;
}
}
error();
</script>
Suggestion, you can make it actually things easier with the following code.
the function below scans all input fields under fieldset element
$("fieldset *[name]").each....
the issue above is multiple alert, what if you have a lot of inputs, it would alert in every input, which wont be nice for the users :) instead you can do this
alert(error1.toString().replace(/,/g, "\n"));
to alert the lists of errors at once.
string = $('input[name="username"]').val('');
that is actually clearing your value.. so it wont give you anything in console.log().
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<input type="text" name="name" value="" placeholder="name"/><br/><br/>
<input type="text" name="username" value="" placeholder="username"/><br/><br/>
<button onclick="error()">check</button>
</fieldset>
<script>
function error() {
var error1 = [];
var list_of_values = [];
$("fieldset *[name]").each(function(){
var inputItem = $(this);
if(inputItem.val()) {
return list_of_values.push(inputItem.val());
}
error1.push('Fill in the '+inputItem.attr('name')+' field!')
});
if(error1.length > 0) {
console.log(error1);
alert(error1.toString().replace(/,/g, "\n"));
}
if(list_of_values.length > 0) {
console.log(list_of_values);
}
}
</script>
Register the <input> to the input event. When the user types anything into the <input> the input event can trigger an event handler (a function, in the demo it's log()).
Demo
Details commented in demo
// Reference the input
var text = document.querySelector('[name=username]');
// Register the input to the input event
text.oninput = log;
/*
Whenever a user types into the input...
Reference the input as the element being typed into
if the typed element is an input...
log its value in the console.
*/
function log(event) {
var typed = event.target;
if (typed.tagName === 'INPUT') {
console.log(typed.value);
}
}
<input type="text" name="username" value="testuser">
How do I enable input2 if enable 1 has input within it (basically re-enabling it), I'm still a beginner and have no idea to do this.
<form id="form1">
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
<script language="javascript">
function valid() {
var firstTag = document.getElementById("text1").length;
var min = 1;
if (firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
}
}
//once input from text1 is entered launch this function
</script>
</form>
if i understand your question correctly, you want to enable the second input as long as the first input have value in it?
then use dom to change the disabled state of that input
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
document.getElementById("text2").disabled = false;
}
Please try this code :
var text1 = document.getElementById("text1");
text1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("text2").disabled = false;
} else {
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1">
<input type="text" id="text2" disabled="disabled">
I think you should use .value to get the value. And, then test its .length. That is firstTag should be:
var firstTag = document.getElementById("text1").value.length;
And, the complete function should be:
function valid() {
var min = 1;
var firstTag = document.getElementById("text1");
var secondTag = document.getElementById("text2");
if (firstTag.length > min) {
secondTag.disabled = false
} else {
secondTag.disabled = true
}
}
Let me know if that works.
You can use the .disabled property of the second element. It is a boolean property (true/false).
Also note that you need to use .value to retrieve the text of an input element.
Demo:
function valid() {
var text = document.getElementById("text1").value;
var minLength = 1;
document.getElementById("text2").disabled = text.length < minLength;
}
valid(); // run it at least once on start
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2">
I would just change #Korat code event to keyup like this:
<div>
<input type="text" id="in1" onkeyup="enablesecond()";/>
<input type="text" id="in2" disabled="true"/>
</div>
<script>
var text1 = document.getElementById("in1");
text1.onkeyup = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("in2").disabled = false;
} else {
document.getElementById("in2").disabled = true;
}
}
</script>
I tried to create my own so that I could automate this for more than just two inputs although the output is always set to null, is it that I cannot give text2's id from text1?
<div id="content">
<form id="form1">
<input type="text" id="text1" onkeyup="valid(this.id,text2)">
<input type="text" id="text2" disabled="disabled">
<script language ="javascript">
function valid(firstID,secondID){
var firstTag = document.getElementById(firstID).value.length;
var min = 0;
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
document.getElementById(secondID).disabled = false;
}
if(firstTag == 0){
document.getElementById(secondID).disabled = true;
}
}
//once input from text1 is entered launch this function
</script>
</form>
First, you have to correct your code "document.getElementById("text1").length" to "document.getElementById("text1").value.length".
Second, there are two ways you can remove disabled property.
1) Jquery - $('#text2').prop('disabled', false);
2) Javascript - document.getElementById("text2").disabled = false;
Below is the example using javascript,
function valid() {
var firstTag = document.getElementById("text1").value.length;
var min = 1;
if (firstTag > min) {
document.getElementById("text2").disabled = false;
}
else
{
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
If I understand you correctly, what you are asking is how to remove the disabled attribute (enable) from the second input when more than 1 character has been entered into the first input field.
You can to use the oninput event. This will call your function every time a new character is added to the first input field. Then you just need to set the second input field's disabled attribute to false.
Here is a working example.
Run this example at Repl.it
<!DOCTYPE html>
<html>
<body>
<!-- Call enableInput2 on input event -->
<input id="input1" oninput="enableInput2()">
<input id="input2" disabled>
<script>
function enableInput2() {
// get the text from the input1 field
var input1 = document.getElementById("input1").value;
if (input1.length > 1) {
// enable input2 by setting disabled attribute to 'false'
document.getElementById("input2").disabled = false;
} else {
// disable input2 once there is 1 or less characters in input1
document.getElementById("input2").disabled = true;
}
}
</script>
</body>
</html>
NOTE: It is better practice to use addEventListener instead of putting event handlers (e.g. onclick, oninput, etc.) directly into HTML.
<script>
function KeepCount() {
var x=0;
var count=0;
var x;
for(x=0; x<document.QuestionGenerate.elements["questions"].length; x++){
if(document.QuestionGenerate.elements["questions"][x].checked==true || document.QuestionGenerate.elements["option"][x].checked==true || document.QuestionGenerate.elements["Description"][x].checked==true || document.QuestionGenerate.elements["fillups"][x].checked==true){
count= count+1;
document.getElementsByName("t1")[0].value=count;
}
else
{
document.getElementsByName("t1")[0].value=count;
//var vn=$('#t1').val();
// alert(vn);
//alert(vn);
//alert("value is"+count);
}
}
// var cc = document.getElementsByName("t1")[0].value;
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
}
</script>
<form action="SelectedQuestions.jsp" method="post" name="QuestionGenerate">
<input type="text" name="t1" id="t1" value="">
<input type="submit" id="fi" name="s" value="Finish" onclick="return KeepCount();">
</form>
I use the above code for checking how many check box are checked in my form my form having many check box. and if no check box are selected means it shows some message and than submit the form but for loop is working good and textbox get the value after the for loop the bellow code doesn't work even alert() is not working
**
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
This code is not working why?
**
I change my KeepCount() function code shown in bellow that solve my problem
function KeepCount()
{
var check=$("input:checkbox:checked").length;
alert(check);
if(check==0)
{
alert("You must choose at least 1");
}
return false;
}
The bug is : document.QuestionGenerate.elements["questions"] it is undefined that's why the code is not even going inside for loop use instead :
document.QuestionGenerate.elements.length
if i run the same code for IE every thing is fine i am getting the value of selectedId where as for firefox and chrome it is giving values Undefine.
----------------- code -------------------------------
<html>
<head>
<script type="text/javascript">
function createSelected()
{
var value;
var theForm = document.hell;
for (var i = 0; i < theForm.length; i++)
{
var e = theForm.elements[i];
if ((e.type == "hidden") && (e.value == "false"))
{
console.log("the value of selected IDS="+e.selectedId);
if (e.selectedId!= undefined )
{
Value = ", "+e.selectedId;
}
}
}
console.log( Value);
}
</script>
</head>
<body>
<form name="hell">
<h1>This working only with IE not with FireFox and Crome </h1>
<br/>
<br/>
<input type="hidden" selectedId="heyya1" name="item1" value="false">h1</input>
<input type="hidden" selectedId="heyya2" name="item2" value="false">h2</input>
<input type="hidden" selectedId="heyya3" name="item3" value="false">h3</input>
<input type="hidden" selectedId="heyya4" name="item4" value="false">h4</input>
<input type="hidden" selectedId="heyya5" name="item5" value="false">h5</input>
<input type="hidden" selectedId="heyya6" name="item6" value="false">h6</input>
<input type="button" onclick=createSelected() value="find the values"></input>
</form>
</body>
---------------------------code end-----------------------------------------
please help in in this why cant we use other parameter( like Selectedid inside HTML tag) in FireFox like we can do it in IE.
thanks in advance..
In Chrome (sorry, I'm using a computer that doesn't have FF, and I'm not going to install it just for this question) it works if you use .getAttribute(). So:
// replace
e.selectedId;
// with
e.getAttribute("selectedId");
Or, in your function:
var id = e.getAttribute("selectedId");
console.log("the value of selected IDS="+id );
if (id != null)
{
value += ", "+id;
}
Also, note that JavaScript is case sensitive, so your variable value is not the same as Value, and you were saying Value = where you probably meant value +=. And you may want to use quotes around your element attributes: onclick="createSelected()".
Try reading the selectedId as below. Use getAttribute method
alert("the value of selected IDS="+e.getAttribute('selectedId'));