How to call javascript function when value in textarea was change ?
When fill data into textarea id="yyyy", textarea id="xxxx" will change value too. This function are work good.
When textarea id="xxxx" change value, i want to call function check2 , how can i do ?
please do not change code in function check and id="yyyy"
https://jsfiddle.net/9b6h897d/3/
<textarea id="yyyy" onkeyup="check(this.value)"></textarea>
<textarea id="xxxx" onchange="check2(this.value)" ></textarea>
<script>
function check(value){
document.getElementById("xxxx").value = value;
}
function check2(value){
alert(value);
}
</script>
The standard events for <textarea> are keypress, keydown, or keyup. To do what you want you'll have to trigger the onchange in one of the functions. This makes most sense inside the first function called check.
document.getElementById("textarea2").addEventListener("change", function(event) {
console.log("Textarea two was changed.");
});
function check(element) {
var textarea2 = document.getElementById("textarea2"),
event = new Event('change');
textarea2.value = element.value;
textarea2.dispatchEvent(event);
};
<textarea id="textarea1" onkeyup="check(this);"></textarea>
<textarea id="textarea2" onkeyup="check(this);"></textarea>
Updated fiddle : https://jsfiddle.net/9b6h897d/6/
When you change the value in check call the check2 method like :
function check(value){
document.getElementById("xxxx").value = value;
check2(value).
}
i think it's better to use oninput if you want to track the user changes.
if you don't want to change the content of check() you have to call the both function in the oninput :
<textarea id="yyyy" oninput="check(this.value);check2(this.value)"></textarea>
New fiddle : https://jsfiddle.net/9b6h897d/9/
Hope this will help you.
Create just one function that both use, within the function check to see what textarea called the function and then write your separate code for each.
This is just sudo code that I'm writing off my phone, so it may have minor errors you need to fix.
var userEdit = true;
function(ta) {
if (ta.Id == 'xxx')
{
// Do code for xxx text area
userEdit = false;
// update yyy via code
userEdit = true;
} else if (ta.Id == 'yyy' && userEdit) {
// Do code for yyy text area change only when a user edits it
} else if (ta.Id == 'yyy' && !userEdit) {
// Do code for yyy text area change only when your code edits it
}
}
You could also use onblur instead of onchange, onblur gets called when a user changes the focus out of a object. Like after they type in a input and then tab or click into another input or button it will get fired.
Related
I have an input field in my code: <input type=text name=code id=code>.
What I want to do is to convert a specific text to another one as the user types in the field.
Let me explain more. When the user enters 31546 in the input, I want that text to directly convert to HELLO.
I know this can be done using JavaScript/jQuery, but I can't have any ideas on how to achieve this. How can I?
P.S. If it's easier to work with a textarea, I'm ready to change my input to a textarea.
EDIT: I got a code from this StackOverflow post which detects any changes to an element,
$('.myElements').each(function() {
var elem = $(this);
// Save current value of element
elem.data('oldVal', elem.val());
// Look for changes in the value
elem.bind("propertychange change click keyup input paste", function(event){
// If value has changed...
if (elem.data('oldVal') != elem.val()) {
// Updated stored value
elem.data('oldVal', elem.val());
// Do action
....
}
});
});
but I am not sure how to utilise this for what I want.
Please bear with me as I am yet a fledgling in this domain.
Thank you.
One option is to set up a keyup event for your input and then replace the value as the user types. For example:
$('input').keyup(function () {
var val = $(this).val();
var newVal = val.split('31546').join('HELLO');
if (newVal !== val) {
$(this).val(newVal);
}
});
You can use keyup event as,
$(document).on('keyup', '#code', function() {
$('#code').val(convertedValue($('#takeInput').val()));
})
function convertedValue(val) {
return 'hello';
}
This may help you :--
<input type="text" id="code">
$('#code').bind('change click keyup onpaste', function(ele){
var origVal = ele.target.value;
if(origVal.indexOf("123") !== -1){
ele.target.value = origVal.replace("123","Hello");
}
});
I'm using this method http://www.w3schools.com/jsref/event_onsearch.asp
What I want is the text that I searched with to stay in the textarea or at least get back to the textarea, not disappear because I click the enter button.
I understand that it clears the text because in the link they describe the function like this: "The onsearch event occurs when a user presses the "ENTER" key or clicks the "x" button in an element with type="search".
So it acts as if I click the x button, although, there must be a way to get the text back there after?
This is my current code html code
<form> <input type="search" name="search" id="searchid" onsearch="OnSearch(this)"/> </form>
This is my javasript/jquery
function OnSearch(input) {
alert("The current value of the search field is " + input.value);
$("#searchid").val(input.value);
}
What happens now is that it correctly alerts the value the textarea is holding, although it wont add back the textarea value.
EDIT: It seems like the page reloads, how can i insert code that runs after page reload?
Well I have an alternative. Since you cannot avoid the clear functionality you can store the text each time keypressed in a global variable and if x is pressed retain the value in textbox. Below is the code:
DEMO HERE
var text="";
function OnSearch(input) {
if(input.value == "") {
$("#searchid").val(text);
}
else {
alert("You searched for " + input.value);
}
}
$(document).on('keyup','#searchid', function (e) {
text=$(this).val();
console.log(text);
});
UPDATE
if your html is inside the form you can do as below:
Check in document.ready if it already had a text and if yes set it!!
$(document).ready(function()
{
if(localStorage.getItem("text")!="")
{
$("#searchid").val(localStorage.getItem("text"));
}
});
function OnSearch(input) {
if(input.value == "") {
$("#searchid").val(localStorage.getItem("text"));
}
else {
alert("You searched for " + input.value);
}
}
$(document).on('keyup','#searchid', function (e) {
localStorage.setItem("text",$(this).val());
});
I think this will help you to display the alert dialog symbol as that:
HTML:
<input type="search" name="search" id="searchid"/>
Javascript:
document.getElementById("searchid").onsearch = function() {yourfunctionname()};
/* Put this before the below function or in the top of the document */
function yourfunctionname(){
var x = document.getElementById("searchid").value;
alert("The current value of the search field is "+x);
/* Or do what ever you wish */
}
/*Remember to replace the yourfunctionname with your function's name */
OR If it is in a form try this:
Your form should look like this:
<form method="/* method */" action="/* action */" onSubmit="yourfunctionname()">
<input type="search" name="search" id="searchid"/>
/* Rest of your form*/
</form>
Javascript:
document.getElementById("searchid").value = localStorage.getItem("saved");
document.getElementById("searchid").onsearch = function() {yourfunctionname()};
/* Put this before the below function or in the top of the document */
function yourfunctionname(){
var x = document.getElementById("searchid").value;
alert("The current value of the search field is "+x);
/* Or do what ever you wish */
/* The below code does the trick*/
localStorage.setItem("saved", x);
location.reload();
return false;
}
/* Remember to replace the yourfunctionname with your function's name */
If you are having a different function to submit the form then replace your form's onsubmit attribute with that function's name and a word "return" before it's name and add the below javascript inside that function.
var x = document.getElementById("searchid").value
localStorage.setItem("saved", x);
location.reload();
return false;
If you wanted something else then please comment.
Please accept as if it solves your problem.
And thanks...
Lastly for more just comment
It is possible to check if a input was not changed using change() event?
I'm working with <input type='file' /> and i want to warning the user that no changes was made on his own action.
Right now, i just made a normal change() event:
// fire the thumbnail (img preview)
$("#file-input").on("change", function () {
readURL(this); // create the thumbnail
});
what i'm missing ?
Prev Solutuib:
well, i found a workaround for this, the real problem is that i give a option to the user to hide the thumbnail, and if he wants, open again...
but the thumbnail will only open when the user select a image, that's the problem, because the change event fire this option to open, so, if no change, no thumbnail open.
so, when i hide the thumbnail, i change the input file for a new one, making the change event always fire.
Use a variable to store the last value of the input, and compare to the current value on change event, if they are the same, no change was made :
var last_value = $("#file-input").val();
$("#file-input").on("change", function () {
if (this.value === last_value) alert('no change');
last_value=this.value;
});
EDIT: Or you can always just replace the input tag with another, like this SO answer suggest :
var $c = $("#container");
var $f1 = $("#container .f1");
function FChange() {
alert("f1 changed");
$(this).remove();
$("<input type='file' class='f1' />").change(FChange).appendTo($c);
}
$f1.change(FChange);
<input type="file" id="file-input" data-url="intial-value" />
$("#file-input").on("change", function () {
if($(this).val() != $(this).data('url'){
//value has changed
$(this).data('url', $(this).val())
}
else{
return false;
}
});
$("#file-input").on("change", function () {
if($(this).data('last-val')){
// do something
} else {
$(this).data('last-val',$(this).val());
//do something else
}
});
I have a button:
<button id="a" onclick="Foo()">Button A</button>
When I click this button the first time, I want it to execute Foo (which it does correctly):
function Foo() {
document.getElementById("a").onclick = Bar();
}
What I want to happen when I click the button the first time is to change the onclick function from Foo() to Bar(). Thus far, I've only been able to achieve an infinite loop or no change at all. Bar() would look something like this:
function Bar() {
document.getElementById("a").onclick = Foo();
}
Thus, clicking this button is just alternating which function gets called. How can I get this to work? Alternatively, what's a better way to show/hide the full text of a post? It originally starts shorted, and I provide a button to "see the full text." But when I click that button I want users to be able to click the button again to have the long version of the text go away.
Here's the full code, if it helps:
function ShowError(id) {
document.getElementById(id).className = document.getElementById(id).className.replace(/\bheight_limited\b/, '');
document.getElementById(id+"Text").className = document.getElementById(id+"Text").className.replace(/\bheight_limited\b/, '');
document.getElementById(id+"Button").innerHTML = "HIDE FULL ERROR";
document.getElementById(id+"Button").onclick = HideError(id);
}
function HideError(id) {
document.getElementById(id).className += " height_limited";
document.getElementById(id+"Text").className += " height_limited";
document.getElementById(id+"Button").innerHTML = "SHOW FULL ERROR";
document.getElementById(id+"Button").onclick = "ShowError(id)";
}
Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.
document.getElementById("a").onclick = Bar;
Looking at your other code you probably want to do something like this:
document.getElementById(id+"Button").onclick = function() { HideError(id); }
var Foo = function(){
document.getElementById( "a" ).setAttribute( "onClick", "javascript: Boo();" );
}
var Boo = function(){
alert("test");
}
Do not invoke the method when assigning the new onclick handler.
Simply remove the parenthesis:
document.getElementById("a").onclick = Foo;
UPDATE (due to new information):
document.getElementById("a").onclick = function () { Foo(param); };
Thanks to João Paulo Oliveira, this was my solution which includes a variable (which was my goal).
document.getElementById( "myID" ).setAttribute( "onClick", "myFunction("+VALUE+");" );
I recommend this approach:
Instead of having two click handlers, have only one function with a if-else statement. Let the state of the BUTTON element determine which branch of the if-else statement gets executed:
HTML:
<button id="a" onclick="toggleError(this)">Button A</button>
JavaScript:
function toggleError(button) {
if ( button.className === 'visible' ) {
// HIDE ERROR
button.className = '';
} else {
// SHOW ERROR
button.className = 'visible';
}
}
Live demo: http://jsfiddle.net/simevidas/hPQP9/
You could try changing the button attribute like this:
element.setAttribute( "onClick", "javascript: Boo();" );
What might be easier, is to have two buttons and show/hide them in your functions. (ie. display:none|block;) Each button could then have it's own onclick with whatever code you need.
So, at first button1 would be display:block and button2 would be display:none. Then when you click button1 it would switch button2 to be display:block and button1 to be display:none.
For anyone, like me, trying to set a query string on the action and wondering why it's not working-
You cannot set a query string for a GET form submission, but I have found you can for a POST.
For a GET submission you must set the values in hidden inputs e.g.
an action of: "/handleformsubmission?foo=bar"
would have be added as the hidden field like: <input type="hidden" name="foo" value="bar" />
This can be done add dynamically in JavaScript as (where clickedButton is the submitted button that was clicked:
var form = clickedButton.form;
var hidden = document.createElement("input");
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "foo");
hidden.setAttribute("value", "bar");
form.appendChild(hidden);
See this question for more info
submitting a GET form with query string params and hidden params disappear
I have a form that has default values describing what should go into the field (replacing a label). When the user focuses a field this function is called:
function clear_input(element)
{
element.value = "";
element.onfocus = null;
}
The onfocus is set to null so that if the user puts something in the field and decides to change it, their input is not erased (so it is only erased once). Now, if the user moves on to the next field without entering any data, then the default value is restored with this function (called onblur):
function restore_default(element)
{
if(element.value == '')
{
element.value = element.name.substring(0, 1).toUpperCase()
+ element.name.substring(1, element.name.length);
}
}
It just so happened that the default values were the names of the elements so instead of adding an ID, I just manipulated the name property. The problem is that if they do skip over the element then the onfocus event is nullified with clear_input but then never restored.
I added
element.onfocus = "javascript:clear_input(this);";
In restore_default function but that doesn't work. How do I do this?
Use
element.onfocus = clear_input;
or (with parameters)
element.onfocus = function () {
clear_input( param, param2 );
};
with
function clear_input () {
this.value = "";
this.onfocus = null;
}
The "javascript:" bit is unnecessary.
It looks like you don't allow the fields to be empty, but what if the user puts a single or more spaces in the field? If you want to prevent this, you need to trim it. (See Steven Levithans blog for different ways to trim).
function trim(str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
If you really want to capitalize the strings you could use:
function capitalize(str) {
return str.substr(0, 1).toUpperCase() + str.substr(1).toLowerCase();
}
By clearing the onfocus event you have created a problem that should not have been there. An easier solution is to just add an if-statement to the onfocus event, so it only clears if it is your default value (but I prefer to select it like tvanfosson suggested).
I assume that you on your input-elements have set the value-property so that a value is shown in the input-elements when the page is displayed even if javascript is disabled. That value is available as element.defaultValue. Bonuses by using this approach:
You only define the default value in one place.
You no longer need to capitalize any value in your handlers.
The default value can have any case (like "John Y McMain")
The default value no longer needs to be the same as the name of the element.
.
function clear_default(element) {
if (trim(element.value) == element.defaultValue ) { element.value = ""; }
}
function restore_default(element) {
if (!trim(element.value).length) { element.value = element.defaultValue;}
}
I would suggest that you handle it a little differently. Instead of clearing the value, why not just highlight it all so that the user can just start typing to overwrite it. Then you don't need to restore the default value (although you could still do so and in the same way if the value is empty). You also can leave the handler in place since the text is not cleared, just highlighted. Use validation to make sure the value is not the original value of the input.
function hightlight_input(element) {
element.select();
}
function restore_default(element) // optional, do we restore if the user deletes?
{
if(element.value == '')
{
element.value = element.name.substring(0, 1).toUpperCase()
+ element.name.substring(1, element.name.length);
}
}
<!-- JavaScript
function checkClear(A,B){if(arguments[2]){A=arguments[1];B=arguments[2]} if(A.value==B){A.value=""} else if(A.value==""){A.value="Search"}}
//-->
<form method="post" action="search.php">
<input type="submit" name="1">
<input type="text" name="srh" Value="Search" onfocus="checkClear(this,'Search')" onblur="checkClear(this,' ')">
</form>