Changing a Value on Key Up - javascript

This may be a simple JavaScript problem, but I really don't know what's wrong with my code.
What I would want to do is very simple, there is an input element in my template, and I would like to change the value of it whenever there is a key up.
The following is the relevant part of my code.
var track = document.getElementById("id_tracking");
track.value = "a";
function track_record() {
track.value = "b";
}
$(document).ready(function() {
$("#id_urnA_red").keyup(function() {
c_urn();
react();
track_record();
});
$("#id_urnA_blue").keyup(function() {
c_urn();
react();
track_record();
});
});
function c_urn() {}
function react() {}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="id_urnA_red" />
<input id="id_urnA_blue" />
<br><br>
<input type="text" name="tracking" id="id_tracking" />
Here, id_urnA_red is an input element. When its value changes, I would like the value of id_tracking to change.
Other functions c_urn and react are implemented normally on key up. I am confused why track_record is not implemented.
Thank you

Related

How to make data input readonly, but showing calendar?

I can't find any solution for this anywhere. I would like to allow user to see calendar when clicking on my input, but when user will try to change the value, it shouldn't change (or immediately change back for value, what was at the beggining).
Readonly attribute removes calendar, so I was trying to do it different ways like use onchange/onclick functions to restore my value after event, but the value was changing anyway.
So for now my input looks like this:
<input class='test' type='date' value='2020-06-04' onkeydown='return false' >
So at least user can't change value of my input using keyboard. Could you help me?
You might try to set a time limit
<html>
<body>
<input type="date" value="2020-06-04">
<input type="date" value="2020-06-04" min="2020-06-04" max="2020-06-04">
</body>
</html>
If I understood correctly, this is what you want.
HTML
<input class='test' type='date' value='2020-06-04' />
JavaScript
const date = "2020-06-04";
const input = document.querySelector('.test');
input.onkeydown = function(e) {
return false;
}
input.onchange = function(e) {
this.value = date;
}
Check out this JSFiddle
EDIT
function preventInputChange(input, staticValue) {
input.onchange = function(e) {
this.value = staticValue;
}
}

Passing execution context in JavaScript from html elements

I am very new to JavaScript programming, and i am trying to do form validation using JavaScript.
While learning form validation i was reading about how to disable submit button until all input fields are validated, i saw many techniques to do this, but, i am confused regarding the following code:
<body>
<h3>Enter some values in the text to enable the button!</h3>
<input type="text" id="txt" onkeyup="manage(this)" /> //focus here on "this" parameter
<input type="submit" id="btSubmit" disabled />
</body>
<script>
function manage(txt) {
var bt = document.getElementById('btSubmit');
if (txt.value != '') {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
</script>
Here this is passed as an argument from an input element event listener in html. I tried passing something other than this from there, it didn't work only passing this works,
As far as i know this in JavaScript signifies current-execution-context, but since this is JavaScript keyword then how it is interpreted inside html?
JS FIDDLE LINK while passing 'this': https://jsfiddle.net/s0vnjpqb/
JS FIDDLE LINK while passing 'some': https://jsfiddle.net/s0vnjpqb/
PS: I am new to JavaScript, hence the question is easy, this might not match the standards of stack-overflow, but i tried researching in stack-overflow as well as on other platform i couldn't understand it.
As you mentioned correctly in the description that this in Javascript signifies the current execution context.
Similarly in html
this also represent the value of the ThisBinding of the current execution context and this.value indicates the value of the current execution context
e.g txt.value in your case.
Alternately what you can do is,
<body>
<h3>Enter some values in the text to enable the button!</h3>
<input type="text" id="txt" onkeyup="manage()" /> //focus here on "this" parameter
<input type="submit" id="btSubmit" disabled />
</body>
<script>
function manage(txt) {
var value = document.getElementById("txt").value;
var bt = document.getElementById('btSubmit');
if (value != '') {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
</script>

alerting the value of an input type number

Here is the code that I am having problems with. Below it I'll add an explanation:
$(function() {
var $input = $("#input");
var input = $input.val();
var $go = $("#go");
$go.click(function() {
alert(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>
The code above is a dummie example to represent my actual question, no more background is needed.
So I have one input type="number" id="input" in which you input a number, and a button type="button" id="go".
In my jQuery, I first declare $input which holds the element #input, then input which holds the value of the element #input, and finally $go which holds the element #go.
Below that I have a function, that says that when I click on #go, I should be able to alert(input).
Now, this code does not do that. In my head this makes perfect sense, but apparently it doesn't work.
That is because you are declaring input outside the click function, which means the value (simply an empty string) is set at runtime and will not be updated. You should define input within your click event handler:
$(function() {
var $input = $("#input");
var $go = $("#go");
$go.click(function() {
var input = $input.val();
alert(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>
First of all, StackOverflow seems to block alerts origination from the code snippet, it will be much easier to output them to the console instead so you can keep track of things.
Your code can be simplified way down without the need for many variables.
But your main problem was the fact that the input value was not getting reset when the click event happened but was getting picked up on page load, meaning it would be stuck at ''.
$(function() {
$("#go").click(function() {
var input = $("#input").val();
console.log(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>

How to check if a field has been populated with data using a javascript function?

Please note that i am a beginner in javascript. I've googled all the possible terms for my question but no luck. I wanted to know if there exists a javascript function that can be used to check if a field has been populated with data using another javascript function. No libraries please since i want to know the basics of javascript programming.
Edit:
I just wanted to clarify that scenario that i am into.
I have 3 input fields. These fields have their value assigned automatically by another javascript function. What i wanted to do is when this fields have their respected values i wanted to create a new input field that will calculate the sum of the value of the 3 fields.
As You are new Please try this whole code of HTML with Javascript code too.
<!DOCTYPE html>
<html>
<head>
<script>
function copyText()
{
var TextValue = document.getElementById("field1").value
if(TextValue !=''){
alert(TextValue);
}
alert();
}
</script>
</head>
<body>
<input type="text" id="field1" value="Hello World!"><br>
<button onclick="copyText()">Copy Text</button>
</body>
</html>
Hope this works.
Hope this helps you
//Html Code
<input type="text" value="sdsd" onChange="checkValue(this.value)">
//Java Script Code
function checkValue(value){
if((value).trim()!==""){
alert('return true');
}
else{
alert('return false');
}
}
//HTML line:
<input type="text" id="txtAddress" />
//JS code:
function setValue() {
//first we set value in text field:
document.getElementById('txtAddress').value = 'new value';
TestFunction();
}
function TestFunction() {
//second we will get value from this filed and check wether it contains data or not:
var address = document.getElementById('txtAddress').value;
if (address != "") {
alert("Yes, field contains address");
}
else {
alert("Empty field, there is no address");
}
}
I'm not sure what are you trying to achieve.
If you want to check if the input to the field was made with Javascript : there's no way to make that UNLESS your Javascript input function stores such information in some place (for example, add specific class to the modified object). Then you can proceed with following:
If you want to check if there's any value in the field then you can use onchange (triggers on change, you can pass the object to the function and get every property attached to it - value, class etc.).
example:
function changeValue( object )
{
object.value = "new value";
object.classList.add("modified");
}
function isChanged( object )
{
if( object.classList.contains("modified") )
alert("I'm modified by JS!");
}
<input type="text" id="first" onchange="isChanged(this)">
It has been some time since I was writing JS, but this should work.
Edit: now I remember onchange triggers only, if element is edited by user, thus rendering onchange detection worthless. Well, you could use set interval with the following function:
function getModified() {
// somehow process with
// document.getElementsByClassName("modified");
}
setInterval( getModified(), 3000 ); // get JS modified elements every 3s
lets say this is your html field (text input for instance):
<input type="text" id="txtName" />
in order to get it's value with javascript, use document.getElementById('txtName').value - for example:
function alert_value() {
var value = document.getElementById('txtName').value;
alert(value);
}
hope that helps.
EDIT:
if this text field is added dynamically, i'd suggest including jQuery and set the following script:
$(function(){
$(document).on('keyup', '#txtName', function(){ alert($(this).val()) });
});

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

Categories

Resources