I need some clarification, as I have managed to confuse myself. Let's say we have the following code:
var textarea = document.getElementById("myTextarea");
var button = document.getElementById("myButton");
button.addEventListener("click", function() {
var words = textarea.value;
console.log(words);
}
This code runs by first gathering the DOM elements (the button and textarea) into their respective variables. Later in the code, when the button is pressed, textarea.value is placed into the variable words. Fair enough right?
My question is why isn't nothing logged into the console? The textarea variable is created and stored from the DOM after the page loads, which pressumably would be before the user had time to write anything into the textarea. This would mean that textarea.value should equal '' (nothing), as opposed to the string in the textarea at the time that the button was pressed by the user.
If anyone could clear this up for me that would be greatly appreciated.
Thanks :)
This would mean that textarea.value should equal '' (nothing), as opposed to the string in the textarea at the time that the button was pressed by the user.
Nope!
The value property of an input element updates dynamically based on user input or other code that changes it. It matters when you access the value property. Because you access it when the button is clicked, the value set on the element is read when the button is clicked.
If however you did something like this:
var textarea = document.getElementById("myTextarea");
var words = document.getElementById("myButton").value;
button.addEventListener("click", function() {
console.log(words);
}
Then the value would be read earlier (likely being blank, but could be a default value, and auto-save variable, or something else it was set to earlier), and changes by the user would be ignored.
Look at the 2 jsfiddles.
<input id = "myTextarea"/>
<button id= "myButton" type="submit"> test </button>
var textarea = document.getElementById("myTextarea");
var button = document.getElementById("myButton");
button.addEventListener("click", function() {
var words = textarea.value;
console.log(words);
});
In the first one, you are capturing the value of the text area inside the on click event. Thus, you get the value that has already been entered.
<input id = "myTextarea"/>
<button id= "myButton" type="submit"> test </button>
var textarea = document.getElementById("myTextarea");
var button = document.getElementById("myButton");
button.addEventListener("click", function() {
console.log(words);
});
In the second fiddle, you are capturing the value as soon as the DOM is loaded without waiting for the click event to happen. Thus, the value that prints in console is blank.
Thus, whether you will see the value entered or nothing at all depends on when you capture the value, after the event happens or right after the DOM is loaded. Hope this helps.
Related
I have an HTML input box and want to use jQuery to get the value of user input as it is entered, however the DOM seems to be activated upon page load and it never takes the value of the input box as the user types it in. I'm new to this and can't figure out what I'm doing incorrectly, any ideas would be appreciated!
<input id="textFilter" type="text">
function addEventHandlerForSearch() { //Javascript Handler
$('#textFilter').val();
$('#searchText').text($('#textFilter').val());
let searchVal = $('#searchText').text();
$(document).ready(function() { // DOM
$('#textFilter').keypress(addEventHandlerForSearch());
loadSavedRunkeeperTweets().then(parseTweets);
});
Simple vanilla implementation to get the value of the text box as it is typed would be:
const input = document.getElementById('textFilter');
input.onkeyup = () => {
console.log(input.value)
}
Then you could do whatever you need to with that data. If jquery is a requirement, I apologize for not including that in my answer. Not my area of expertise lol.
I'm having some trouble getting my input value to change when I type a value inside it.
var t = document.createElement('div');
t.innerHTML = '<input type="text" id="myText">';
document.getElementById("news").appendChild(t);
var x = document.getElementById("myText").value; //Grabs the value of the input.
t.onchange = function(){myFunction()} //Input. Onchange..
function myFunction() {
console.log(x); //Logs the value of "x"
}
My problem is when I type some string in the input. "Hello world" as a example. It should print "Hello world" to the console. Instead it prints nothing. Just a blank line. How could I make it to print what I type inside the input box?
Using my script.
The 'change' event fires only when you leave the input field. You probably want an 'input' event here which fires immediately and the listener is registered with oninput
x is a variable that's initialized just once and variables are not bound to the current value of whatever you used to initialize them so you need to read the element's value again
bind a function directly to the the event so it can use this to access the element directly
add the event on the input element, not on the div
document.getElementById("myText").oninput = myFunction;
function myFunction() {
console.log(this.value)
}
Since we don't have onchange on div, it's on input element.
Difference between onchange & onkeyup. (MDN)
onkeyup — The keyup event fires when the user releases a key that was previously pressed.
So, whenever you change value it gets triggered.
onchange — change events fire when the user commits a value change to a form control. This may be done, for example, by clicking outside of the control or by using the Tab key to switch to a different control.
So, unless you tab or click outside of input your function won't get called.
You should replace your code with following.
var t = document.createElement('div');
t.innerHTML = '<input type="text" id="myText">'
document.getElementById("news").appendChild(t);
var input = document.getElementById('myText');
input.onkeyup = myFunction
function myFunction() {
var x = document.getElementById("myText").value; //Grabs the value of the input.
console.log(x); //Logs the value of "x"
}
<div id="news"/>
I've built a page where you can filter results by typing into an input box.
Basic mechanics are:
Start typing, input event is fired, elements without matching text begin hiding
If input becomes empty (or if you click a reset button), all elements are shown again
I have noticed a problem, though, when highlighting text. Say I type "apple" into the input. Then I highlight it, and type "orange."
If an element exists on the page containing "orange," but it was already hidden because I filtered for "apple," it does not show up. I have gathered this is because the input never truly empties; rather, I simply replace "apple" with the "o" from orange before continuing with "r-a-n-g-e." This means I get a subset of "apple" results that contain "orange," as if I had typed "apple orange."
What I really want to do is clear my input on the keypress for the "o" in "orange" before hiding nonmatching elements, so I'm effectively searching the whole page for "orange."
What I've tried so far
1: Set input value to '' on select event:
$('.myinput').on('select', function(){
$(this).val('');
});
This doesn't work because it just deletes my highlighted text, which is unexpected. I only want to reset the input on the keypress following the highlight.
2: Include an if statement in my input event that checks if there is a selection within the input:
$('.myinput').on('input', function(){
var highlightedText = window.getSelection();
if($(highlightedText).parent('.myinput')) {
//reset my input
}
});
This doesn't work because it seems to fire on every keypress, regardless of if there is any actual selection. (Are user inputs always treated as selected?)
3: Add a select event listener to the input element, and set a variable to true if there's a selection. Then, in my input event, check if the variable is true on keypress.
$(function(){
var highlightedText = false;
$('.myinput').on('input', function(){
if(highlightedText = true) {
//reset my input
}
//do stuff
highlightedText = false;
});
$('.myinput').on('select', function(){
highlightedText = true;
});
});
I really thought this one would work because a basic console log in the select function only fires when I want it to – when text in the input is highlighted, but not when other text is highlighted and not when text is entered into the input. But alas, when I change that to a variable toggle, it seems to fire on every keypress again.
So the question is: How can I fire a function on input only if text in my input is highlighted?
I have found this question that suggests binding to the mouseup event, but it seems like overkill to check every single click when I'm only worried about a pretty particular situation. Also, that solution relies on window.getSelection(), which so far isn't working for me.
I've also found another question that suggests to use window.selectionEnd instead of window.getSelection() since I'm working with a text input. I tried incorporating that into option 2 above, but it also seems to fire on every keypress, rather than on highlight.
This answer is not about text selection at all.
But still solve your problem to refilter text when highlighted text is being replaced with new input.
var input = document.getElementById('ok');
var character = document.getElementById('char');
var previousCount = 0;
var currentCount = 0;
input.addEventListener('input', function(){
currentCount = this.value.length;
if (currentCount <= previousCount){
/*
This will detect if you replace the highlighted text into new text.
You can redo the filter here.
*/
console.log('Highlighted text replaced with: ' + this.value);
}
previousCount = currentCount;
char.innerHTML = this.value;
});
<input type="text" id="ok">
<div id="char"></div>
I'll agree with others that you will save yourself some trouble if you change your filtering strategy - I'd say you should filter all content from scratch at each keypress, as opposed to filtering successively the content that remains.
Anyway, to solve your immediate problem, I think you can just get the selection and see if it is empty. You can modify your second attempt:
$('.myinput').on('input', function(){
// get the string representation of the selection
var highlightedText = window.getSelection().toString();
if(highlightedText.length) {
//reset my input
}
});
EDIT
As this solution seems to have various problems, I can suggest another, along the lines of the comment from #Bee157. You can save the old search string and check if the new one has the old as a substring (and if not, reset the display).
var oldSearch = '';
$('.myinput').on('input', function(){
var newSearch = $('.myinput').val();
if (newSearch.indexOf(oldSearch) == -1) {
// reset the display
console.log('RESET');
}
oldSearch = newSearch;
// filter the results...
});
This approach has the added benefit that old results will reappear when you backspace. I tried it in your codepen, and I was able to log 'RESET' at all the appropriate moments.
I have a text field that should be filled before custom saving through HTML custom button.
When a user fills this field and tries to save through custom button, the text inside this field is null even if the user fills it.
Any suggestions Please?
Many Thanks for replying to my query. Actually, I am calling the below function from custom HTML button and I saw the result from alert message as NULL value until I leave the text box. Once I click some other Field then I am getting right value and saving the record successfully. I have posted my code below please have a look and suggest me how I can achieve it. So how to get the text value if a user doesn't leave the text box and click on the Save button?
function createRecord() {
var oDescription = Xrm.Page.getAttribute("new_description").getValue();
if (oDescription != null) {
var callentity = {};
var activityId;
var currentUserId = Xrm.Page.context.getUserId();
var oLeadId = Xrm.Page.getAttribute("new_lead").getValue()[0].id;
callentity.Subject = "Call Activity";
callentity.Description = oDescription ;
XrmSvcToolkit.createRecord({....Some more functions here...
})
}
HTML Button code for calling above function
<input id="SaveCall" onclick="parent.createRecord()" type="button" value="Save Phonecall"></p>
Xrm.Page.getAttribute(arg).getValue(val) won't return a value until focus is lost from the arg attribute (as you've found out).
Some options you could try:
document.getElementById('new_description_i')[0].value
Removing focus from "new_description" on click of your button.
I need a javascript variable to be whatever is entered into a textbox when a button is pressed.
Basically, if somebody enters "bubbles" into the textbox and then clicks the button that says submit, I need "var Item" to be bubbles. How to I make that function?
I want an if statement if possible, so something like
var Item = getElementById(whatever the id of the textbox content it)
function Thing() {
if {
getElementById(whatever the id of the textbox content it) = bubbles;
document.open(P2.html);
}
you can get the value like this:
<script>
function getValue(){
var value = document.getElementBydId("textbox").value;
}
</script>
<textarea id="texbox"></textarea>
<button onclick="getValue()">