i'm new to js
so i have a simple html element that has contenteditable="true" which i'm using as an input box.
i want the innerhtml to change to "CAN'T BE EMPTY" when the user has typed nothing in the input box ( " " )
and apparently it doesn't work, any tips on how i can do it?
this is my code (which is not working):
HTML:
<p contenteditable="true" id="myparagraph">Input</p>
JS:
if(document.getElementById("myparagraph").innerHTML == ""){
document.getElementById("myparagraph").innerHTML = "CAN'T BE EMPTY";}
i've also tried using the LENGTH property, but didn't work either:
var plength = document.getElementById("myparagraph").innerHTML;
var plength2 = plength.length;
if(plength2 == 0){
document.getElementById("myparagraph").innerHTML = "CAN'T BE EMPTY";}
It's not empty. It's got a value of Input according to your HTML.
If you want to change the value when the user edits, you need to attach an event listener:
document.getElementById('myparagraph').addEventListener('input', (e) => {
if (e.target.textContent.trim() === '') {
e.target.textContent = 'Cannot be empty';
}
})
<p contenteditable="true" id="myparagraph">Input</p>
Note that I changed the logic from using innerHTML to using textContent because otherwise remaining empty HTML tags can prevent the warning from triggering. (Firefox, for example inserts a <br> when there is no content.)
It would be better to display the warning anywhere than the content of the element you're trying to check. Add an event listener to the paragraph element. In the handler get the textContent from the element, and then show/hide the warning depending on whether that text is empty.
const para = document.querySelector('#para');
const warning = document.querySelector('#warning');
para.addEventListener('input', handleInput, false);
function handleInput() {
const text = this.textContent;
warning.textContent = text ? '' : 'Cannot be empty';
}
#para { border: 1px solid #565656; padding: 0.5em; }
#warning { color: red; }
<p contenteditable="true" id="para">Input</p>
<p id="warning"></p>
Related
I got a filed in a form for text area and all other are input elements.
I am not able to use the same for text area as its not supported for the above method that is being used.
I want to get a function , if the input is invalid then return false which adds the class invalid and show the errror message.
Can anyone guide , what the alternative method I can use here instead of checkValidity to perform the validation on text area?
I tried using the below function but the event is not getting picked up
function validateTxt(textArea) {
const reg = new RegExp("^[a-zA-Z0-9]+$")
if (!reg.test(textArea.value)) {
return false
}
return true
}
The pattern attribute is not supported on the textarea element. You need to implement it yourself. This can be done by setting its value in a data attribute, which you use to create a RegExp in the input event handler to validate the value against. You can then toggle the class on the element as required.
Try this:
$('textarea').on('input', e => {
const $textarea = $(e.target);
const valid = new RegExp($textarea.data('pattern')).test($textarea.val());
$textarea.toggleClass('invalid', !valid);
});
.invalid {
border: 2px solid #C00;
color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<textarea type="text" class="form txt" id="message" data-pattern="^[a-zA-Z0-9]+$"></textarea>
I'm a HTML JS beginner.
Right now I'm doing a Meme generator project and I encounter a problem
this is my HTML code
//this is input tag
<div>
<input type="text" placeholder = 'text' class="mtext">
<input type="text" placeholder = 'text' class="mtext">
</div>
//this is my div block.
<div id = "meme">
<div class="mtext1" style = 'left: 5px; top: 5px; width: 400px; height: 25px'></div>
<div class="mtext1" style = 'left: 5px; top: 5px; width: 400px; height: 25px'></div>
</div>
and my thought is wanting to use "addEventListener" to solve this problem.
const inputText = document.querySelectorAll('.mtext')
const showTextBox = document.querySelectorAll('.mtext1')
inputText.addEventListener('????' , function(){
showtextbox.textContent +=
})
the first problem is what addEventListener parameter is proper to meet my expectation? That I can type into the text box and shows the result on div box at the same time.
the second problem is my inputText and showTextBox are array-like value, how can I extract the value for each of inputText and represent to the right showTextBox?
Thank you
First of all, you are looking for the change event. Check this website
// this code is wrong, read below.
inputText.addEventListener('change' , function(){
// code
});
second, inputText and showTextBox are not what you think they are.
document.querySelectorAll gives you a NodeList which is just a list of html elements (for example - [elem1, elem2...] ). See this website. So inputText and showTextBox are lists.
You need to put an eventListener to every one of those elements in the list:
inputText.forEach(element => {
// add eventListener to every element in the list:
element.addEventListener('change', function () {
// element.value gives the value inside your input elements.
// your code
})
});
The code above puts change eventListener to every mtext class.
Here is how you do it:
const inputText = document.querySelectorAll('.mtext');
const showTextBox = document.querySelectorAll('.mtext1');
//element is current element, index is the current element's index
inputText.forEach((element, index) => {
// add eventListener to every element in the list:
element.addEventListener('change', function (e) {
// element.value gives the value inside your input elements.
showTextBox[index].innerText = element.value
})
});
Here is the demo
you can also use keyup, but as this post discusses:
The reason you should not use keyup() is because if a user inputs a value using autofill, it will not fire the keyup() event. However, autofill does fire the change() event, and your verification script will run, and the input will be verified.
Hello I have try a lot but can't solve . can any one explain me how I'll drive a JavaScript event after write" in " . I mean i wanted to make a div display:none to display:block after write " in ". that's a auto suggestion issue i've attaching a image the pattern is like that [word] [in] [word].
That's will do onkeyup event.
JS version...
var myInput = document.getElementById('myInput');
var messageBox = document.getElementById('messageBox')
myInput.addEventListener("keyup", checkString);
function checkString() {
var str = myInput.value;
// notice whitespace either side of "in" to prevent false positives
if (str.indexOf(' in ') > -1) {
messageBox.style.display = "block";
} else {
messageBox.style.display = "none";
}
}
#messageBox {
display: none;
padding: 15px;
background: #f2f2f2;
border: 1px solid #e6e6e6;
margin-top: 15px;
}
<input id="myInput" placeholder="Type here">
<div id="messageBox">In was typed</div>
Use input event in jQuery
$('#some_text_box').on('input', function() {
var value = $(this).val();
// do your stuff
// split the value by space and check if it contains 'in'
});
Using jQuery keyup event you can get value which user type in text box while user typing. Then with the use of indexOf javascript method you can compare string with in word. if match found you can display div otherwise hide that div.
Make sure to use toLowerCase() to convert string enter by user in lower case to get perfect match with in word. if user enter in in uppercase it function works fine.
DEMO
What is indexOf() method ?
The indexOf() method returns the position of the first occurrence of a
specified value in a string.
This method returns -1 if the value to search for never occurs.
Note: The indexOf() method is case sensitive.
$('#text').on('keyup', function() {
var value = $(this).val();
if(value.toLowerCase().indexOf(' in ') >= 0){
$('yourdiveselector').show()
}else{
$('yourdiveselector').hide()
}
});
I'm working on a Chrome extension that deals with text selection. I want to detect whether the selected text is editable. Given a Selection object returned by getSelection(), is it possible to check whether the selected text is editable? How?
A selection can contain text from multiple elements. Some elements may be editable and some may not.
However, if you are only interested in the element where the selection starts, you can use
Selection.prototype.anchorNode, which returns the Node in which the selection begins.
Node.prototype.parentNode, which should be the Element in which the selection begins. Latest browsers also support Node.prototype.parentElement.
HTMLElement.prototype.isContentEditable, a read-only property returns a Boolean that is true if the contents of the element are editable; otherwise it returns false.
That is:
getSelection().anchorNode.parentNode.isContentEditable
However, that won't work for input and textarea elements because:
getSelection() won't return selections in them, because their value doesn't exist as a text node. You can use document.activeElement instead.
isContentEditable won't apply because you edit their value instead of their content. Instead, you should check if they are disabled or readOnly (disabled ones doesn't seem to be selectable, but you can check just in case).
function isEditable() {
var el = document.activeElement; // focused element
if(el && ~['input','textarea'].indexOf(el.tagName.toLowerCase())
return !el.readOnly && !el.disabled;
el = getSelection().anchorNode; // selected node
if(!el) return undefined; // no selected node
el = el.parentNode; // selected element
return el.isContentEditable;
}
var el;
function isEditable() {
if(el) el.className = '';
el = document.activeElement; // focused element
if(el && ~['input','textarea'].indexOf(el.tagName.toLowerCase())) {
el.className = 'selected';
return !el.readOnly && !el.disabled;
}
el = getSelection().anchorNode; // selected node
if(!el) return undefined; // no selected node
el = el.parentNode; // selected element
el.className = 'selected';
return el.isContentEditable;
}
var res = document.getElementById('result');
setInterval(function() {
res.textContent = isEditable();
}, 200);
#result {
font-size: 200%;
font-weight: bold;
}
.selected {
outline: 3px solid red;
}
<div>Non-editable div</div>
<div contentEditable="true">Editable div</div>
<input value="Editable input" />
<input value="Read-only input" readonly />
<input value="Disabled input" disabled />
<textarea>Editable textarea</textarea>
<textarea readonly>Read-only textarea</textarea>
<textarea disabled>Disabled textarea</textarea>
<hr />
<p>Is editable: <span id="result"></span></p>
Input tags have the attribute readonly to tell if the input can be edited.
You can try:
if(yourInput.readonly == true) { // where yourInput is the input tag
// can not be edited
} else {
// can be edited
}
You can tinker with this to fit what you are using.
I have 5 input box in my page. I want to check if any field is blank, i will show the error message using a span tag appending to that input field.
Here is my code:
function validateForm() {
// Declare all the local variable
var inputElements, inputId, inputType, i, inputLength, inputNode;
// Get all the input tags
inputElements = document.getElementsByTagName("input");
for(i = 0, inputLength = inputElements.length; i < inputLength; i++) {
inputId = inputElements[i].id; // Get the input field ID
inputType = inputElements[i].type; // Get the input field type
// We will ONLY look for input[type=text]
if(inputType === "text") {
inputNode = document.getElementById(inputId);
if(inputNode.value === "") {
var spanTag = document.createElement("span");
spanTag.innerHTML = inputFieldBlankErrorMessage;
console.log(inputNode.appendChild(spanTag));
}
}
}
return false; // Do Nothing
}
This is what i am getting
It should append after the input tag. I am getting a weird tag which i don't need. Please help!!!
You can't .appendChild() anything to an input node, since an input can have no descendants.
Instead, you should insert the new node after it, or something similar.
inputNode.parentNode.insertBefore(spanTag, inputNode.nextSibling);
DEMO: http://jsfiddle.net/hMBHT/
Simply put you are not supposed to append any elements to input elements.
What you probably want is something like this:
<div class="field">
<input type="text" name="bla"/>
<span class="error">This field can't be blank!</span>
</div>
So you need to insert the span before or after the input element.
Here is an answer that shows you how.
I believe that your issue is that you are trying to append the span as a child of the input, not a sibling (which, I believe, is what you really want).
I can't to be sure without seeing your actual HTML, because I don't know how your inputs are situated in the DOM, but if they have separate parent elements, then you would replace:
inputNode.appendChild(spanTag);
. . . with
inputNode.parentNode.appendChild(spanTag);
Edit: FYI, the code that squint gave below (inputNode.parentNode.insertBefore(spanTag, inputNode.nextSibling);) would be how you could do it if all of the inputs are under the same parent element. It all depends on how the DOM structure is set up.