Get text when copying from input - javascript

<input type="text"> event: <span id="result"></span>
<script>
var input = document.body.children[0];
input.oncopy = function(e) {
debugger
e = e || event;
// document.getElementById('result').innerHTML = e.type +' '+input.value;
// return false;
}
I want get text when copying .It is possible?

Just try with:
input.oncopy = function(e) {
var value = this.value.substring(this.selectionStart, this.selectionEnd);
}
demo

Related

disable button if the input field is empty and enable if there is text

I am a new learner and I am facing a problem. I want to create a simple messaging app and I want that if there is no text inside the input field then the button should be disabled. Help me out.
Here is the code:
let sendMessage = document.getElementById("sendMessage");
sendMessage.addEventListener("click", () => {
let val = document.getElementById("val");
let p = document.createElement("p");
let pTxt = document.createTextNode(val.value);
p.appendChild(pTxt);
val.value = "";
let messages = document.getElementById("messages");
messages.appendChild(p);
if (val.value === "") {
sendMessage.disabled = true;
} else {
sendMessage.disabled = false;
}
});
<div id="messages"></div>
<input type="text" id="val" />
<button id="sendMessage">Send</button>
You should use input event to set disabled to false or true. Set disabled to true by default and after button was clicked.
let sendMessage = document.getElementById("sendMessage");
let input = document.getElementById("val");
sendMessage.addEventListener("click", () => {
let val = document.getElementById("val");
let p = document.createElement("p");
let pTxt = document.createTextNode(val.value);
p.appendChild(pTxt);
val.value = "";
let messages = document.getElementById("messages");
messages.appendChild(p);
sendMessage.disabled = true;
});
input.addEventListener("input", () => {
if(input.value.length > 0){
sendMessage.disabled = false;
} else {
sendMessage.disabled = true;
}
});
<body>
<div id="messages"></div>
<input type="text" id="val"/>
<button id="sendMessage" disabled>Send</button>
<script src="app.js" type="text/javascript"></script>
</body>
Simply create a disabled class for the button if you use custom button.
Then listen to the input change and toggle the class on button if the input have value.
With your code :
const button = document.getElementById('sendMessage');
const input = document.getElementById('message-input');
const messagesBox = document.getElementById('messages');
input.addEventListener('input', () => sendMessage.disabled = input.value === '');
button.addEventListener('click', () => {
let p = document.createElement('p');
let pTxt = document.createTextNode(input.value);
p.appendChild(pTxt);
messagesBox.appendChild(p);
});
<body>
<div id="messages"></div>
<input type="text" id="message-input" />
<button id="sendMessage" disabled >Send</button>
<script src="app.js" type="text/javascript"></script>
</body>
Set a keyup input handler for the input field and a click handler for the button. In the snippet event delegation is used.
document.addEventListener(`input`, handle);
document.addEventListener(`click`, handle);
function handle(evt) {
const isInput = evt.target.closest(`#val`);
const isBttn = evt.target.closest(`#sendMessage`);
if (isInput) {
document.querySelector(`#sendMessage`).disabled = !isInput.value.trim();
}
if (isBttn) {
isBttn.disabled = isBttn;
const inputField = document.querySelector(`#val`);
document.querySelector(`#messages`).insertAdjacentHTML(`beforeend`,
`<li>${inputField.value.trim()}</li>`);
inputField.value = ``;
inputField.focus();
}
}
<ul id="messages"></ul>
<input type="text" id="val" />
<button id="sendMessage" disabled>Send</button>

Issue with textarea

I have a simple textarea. I want to check this area for text, when you push button and if your textarea is empty it fills it with default email.
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.textContent != null) {
x.textContent = 'defaultmail#gmail.com';
}
}
btn.addEventListener('click', function(e) {
e.preventDefault();
putDefaultMail();
});
<form>
<textarea id="smth"></textarea>
<button id="btn">Sumbit</button>
</form>
But something went wrong. It just calls once.
textContent is not the proper way of getting values from textarea. And also, a blank textarea's value is "", not null.
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.textContent != null) {
x.textContent = 'defaultmail#gmail.com';
}
}
btn.addEventListener('click', function (e) {
e.preventDefault();
putDefaultMail();
});
<form>
<textarea id="smth"></textarea>
<button id="btn">Sumbit</button>
</form>
Instead, try .value:
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.value == '') {
x.value = 'defaultmail#gmail.com';
}
}
btn.addEventListener('click', function (e) {
e.preventDefault();
putDefaultMail();
});
<form>
<label>Text: <textarea id="smth"></textarea></label>
<button id="btn">Sumbit</button>
</form>
By the way, you should add labels to the controls like above.
However, if the user enters spaces, then it passes. Like #MuhammadAliMalekzadeh said below, trim() should remove the spaces around for you.
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.value
.trim() // <-- here
== '') {
x.value = 'defaultmail#gmail.com';
}
}
btn.addEventListener('click', function (e) {
e.preventDefault();
putDefaultMail();
});
<form>
<label>Write here: <textarea id="smth"></textarea></label>
<button id="btn">Sumbit</button>
</form>
Textarea has a value. You should check if value empty or not.
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.value == "") { // if empty
x.value = 'defaultmail#gmail.com';
}
}
btn.addEventListener('click', function (e) {
e.preventDefault();
putDefaultMail();
});

How to hide error message when click on other input with javascript?

Hello I have code that shows msg when we write 20 in text input :
link of code for test : https://jsfiddle.net/wdqvkjnu/
$(function() {
var money = 20;
$("#nominal").on("change keyup", function() {
var input = $(this);
// remove possible existing message
if( input.next().is("h5") )
input.next().remove();
// show message
if( input.val() === money.toString() )
input.after("<h5>Thank You</h5>");
});
});
what I want to add:
1> red color for the error
2>when I click on other input the message disapear
AnyOne can help ??
Here is one way to do so:-
$(function() {
const message = document.getElementById("message");
var money = 20;
$("#nominal").on("change keyup", function() {
var input = $(this);
// remove possible existing message
document.querySelectorAll('input').forEach(e => e.addEventListener("click", function() {
message.textContent = "";
}));
// show message
if (input.val() === money.toString()) {
message.style.color = "green";
message.textContent = "Thank You 😁";
}
if (input.val() !== money.toString()) {
message.style.color = "red";
message.textContent = "Error: Enter a valid number 😓";
}
});
});
Input 1: <input id="nominal" type="text" />
Input 2: <input id="nom" type="text" />
<h5 id="message"></h5>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Here is a pratical solution:
$(function() {
var money = 20;
$("#nom").on("click", function() {
$("#nominal").val('');
$(".error").remove();
});
$("#nominal").on("change keyup", function() {
var input = $(this);
// remove possible existing message
if( input.next().is("h5") )
input.next().remove();
// show message
if( input.val() === money.toString() )
input.after("<h5>Thank You</h5>");
if( input.val() !== money.toString() )
input.after("<h5 class='error' style='color:red;''>Error!</h5>");
});
});
Happy coding!
You can try something like this
<div>
<input id="nominal" type="text" />
<input id="nom" type="text" />
</div>
$(function() {
var money = 20;
$("#nominal").on("change keyup", function() {
var input = $(this);
/*
for red color you can add style attribute or add css class
*/
if (input.val() === money.toString())
input.after("<h5 style='color:#f00'>Thank You</h5>");
});
/*
for remove error massage if exist use another listner
*/
$("#nominal,#nom").on("change keyup", function() {
if ($(this).val() != money.toString())
$(this).parent().find('h5').remove();
})
});

Log datalist value when pressing with mouse

I'm running into a problem. How can I console.log the selected option/value from the datalist when selecting/clicking with my mouse?
var input = document.querySelector("input");
var options = Array.from(document.querySelector("datalist").options).map(function(el){
return el.innerHTML;
}); //Optional if you have data
input.addEventListener('keypress', function(e){
if(e.keyCode == 13){
var relevantOptions = options.filter(function(option){
return option.toLowerCase().includes(input.value.toLowerCase());
}); // filtering the data list based on input query
if(relevantOptions.length > 0){
input.value = relevantOptions.shift(); //Taking the first
console.log(input.value)
}
}
});
<input list='typesOfFruit' placeholder="Enter a fruit...">
<datalist id='typesOfFruit'>
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</datalist>
If I understand correctly, select your element and add an eventListener to it that listens to 'change'
const input = document.querySelector('input');
input.addEventListener('change', (e) => { console.log(e.target.value) })
In your example just do this
var input = document.querySelector("input");
// above mentioned eventListener
input.addEventListener('change', function(event){
console.log(`selected value: ${event.target.value}`)
})
var options = Array.from(document.querySelector("datalist").options).map(function (el) {
return el.innerHTML;
}); //Optional if you have data
input.addEventListener('keypress', function (e) {
if (e.keyCode == 13) {
var relevantOptions = options.filter(function (option) {
return option.toLowerCase().includes(input.value.toLowerCase());
}); // filtering the data list based on input query
if (relevantOptions.length > 0) {
input.value = relevantOptions.shift(); //Taking the first
console.log(input.value)
}
}
});

javascript get and use an input value

hello i was just wondering if there is anyway to get an input value to change / use it for the healLevel = 70% i give it a try but i'm new to this and fail.
(function() {
var checkbox1 = document.getElementById("cb1");
var checkbox2 = document.getElementById("cb2");
heal = document.getElementsByClassName('hud-shop-item')[10];
petHeal = document.getElementsByClassName('hud-shop-item')[11];
useHeal = document.getElementsByClassName('hud-toolbar-item')[4];
usePetHeal = document.getElementsByClassName('hud-toolbar-item')[5];
healthBar = document.getElementsByClassName('hud-health-bar-inner')[0];
up = new Event('mouseup');
healLevel = 70;
HEAL1 = function() {
if (checkbox1.checked) {
heal.attributes.class.value = 'hud-shop-item';
useHeal.dispatchEvent(up);
heal.click();
}
};
HEAL2 = function() {
if (checkbox2.checked) {
petHeal.attributes.class.value = 'hud-shop-item';
usePetHeal.dispatchEvent(up);
petHeal.click();
}
};
script = function(e) {
if (e.keyCode == 82) {
HEAL1();
HEAL2();
}
};
document.addEventListener('keydown', function(e) {
script(e);
});
observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutationRecord) {
if (parseInt(mutations[0].target.style.width) < healLevel) {
HEAL1();
HEAL2();
}
});
});
observer.observe(healthBar, {
attributes: true,
attributeFilter: ['style']
});
})();
<input type="number" min="1" max="100" value="70">
this is what i have tried this but didn't seen to work any ideas why i failed ?
i tried using document.querySelector what am i doing wrong?
(function() {
var checkbox1 = document.getElementById("cb1");
var checkbox2 = document.getElementById("cb2");
var elem = document.querySelector('input[type="number"]');
heal = document.getElementsByClassName('hud-shop-item')[10];
petHeal = document.getElementsByClassName('hud-shop-item')[11];
useHeal = document.getElementsByClassName('hud-toolbar-item')[4];
usePetHeal = document.getElementsByClassName('hud-toolbar-item')[5];
healthBar = document.getElementsByClassName('hud-health-bar-inner')[0];
up = new Event('mouseup');
healLevel = elem.value;
<input type="number" min="1" max="100" value="70">
HTML
<input type="number" min="1" max="100" value="70" id="healRate" onchange="updateHealLevel()">
JS
var healLevel = document.getElementById("healRate").value;
function updateHealLevel(){
healLevel = document.getElementById("healRate").value;
}
EDIT
Updated so that a change to the input value will update the healLevel.
To have the value change with the input, you must simply add an onchange event on the HTML component so that when the user changes this input, it will run the code which will update the healLevel.

Categories