clearing input fields upon pressing enter - javascript

After an a user presses enter inside an input field, I clear the value by document.getElementById('text').value = "";
As Im using a spacebars to iterate over an array, this displays multiple input fields with the same id of course id='text'
After typing in the first input field and pressing return key, the input field clear.
However, this is not the case for the proceeding inout fields. I understand document.getElementById only finds the first id.
How can I make this the input value is cleared for all input fields.
'keydown #text': function(event, template) {
if ((27 === event.which) || (13 === event.which)) {
event.preventDefault();
document.getElementById('text').value = "";
}
},

Never ever use ID for multiple elements. ID is unique and it can only be present once in the HTML document. Use class instead or regular HTML element selector:
'keydown input[type="text"]': function(event, template) {
if ((27 === event.which) || (13 === event.which)) {
event.preventDefault();
//this should delete value from the input
event.currentTarget.value = "";
}
}
And in HTML:
<input type="text" />
<input type="text" />

Solution:
You can iterate over all the matches and clear their value.
$("[id='text']").each(function(){
$(this).val("");
});
working example on jsfiddle, initially commented by #abdullah
Recommendations:
It is not good idea to use same id for multiple elements, id must be unique.
Use Jquery libary if you are including it $("#id") much simpler and neat than document.getElementById("id")

I would place the event listener on the parent (the form for example). And instead of
document.getElementById('text').value = "";
by
var inputs = event.currentTarget.querySelector('input');
Array.prototype.forEach.call(inputs , function(el, i){
el.value = '';
});

Related

Check if textbox goes empty after having a value without submitting form or pressing outside of the textbox

I have a currency exchange in my backend, I post data from my textbox to the currency exchange using ajax and view the exchanged value in a label, which is otherwise hidden.
The problem is, if I enter a value in the textbox, and then erase the value from the textbox, the latest value is still there ( I want to hide the label again when the textbox is empty )
This is the code I've tried so far:
$('#transferAmount').on('change',function () {
var amount = $('#transferAmount').val();
if (amount.length < 1 || amount === ""){
$('#amountExchangedHidden').hide();
}
});
I've tried with "on-input" aswell, but it didn't work. Does anyone have a good solution to this?
Use input event instead of change event as change event handler will only be invoked once focus in the input field is lost.
The DOM input event is fired synchronously when the value of an <input> or <textarea> element is changed.
$('#transferAmount').on('input', function() {
var amount = $(this).val();
$('#amountExchangedHidden').toggle(!!amount.length);
}).trigger('input'); //`.trigger` to invoke the handler initially
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" id='transferAmount'>
<input type="text" id='amountExchangedHidden'>
Use blur Event instead of Change
$(function) {
$('#transferAmount').on('blur',function () {
var amount = $('#transferAmount').val();
if (amount.length < 1 || amount === ""){
$('#amountExchangedHidden').hide();}
});
});

Check if input value is not the same onBlur

How can I check if the value of an input box is not the same after blur?
$("#username").on('blur', function() {
$("#usertext").append("new input<br>");
})
Check this jsFiddle: https://jsfiddle.net/xztptsdg/
Let's think that I enter "Josh" in input and after blur, will append new input box. But, user can "re-blur" the username input, and will append other input.
I want to check if the value is the same, not append new input.
You may use change instead of blur, for example:
$("#username").on('change', function() {
$("#usertext").append("new input<br>");
});
So, there is no need to check if the value changed or not because the change event is sent to an element when its value changes.
See this fiddle
You can keep a global variable to store the current value of the textbox and then check whether the entered value is the same as the previous one. If not, then append the new input text and also set the global variable with the new one. Below is the Javascript that does this.
JS
var txt = "";
$("#username").on('blur', function() {
if (txt != this.value) {
$("#usertext").append("new input<br>");
txt = this.value;
}
})
I would suggest you to use change(). According to the docs
The change event is sent to an element when its value changes.
See the fiddle and below is the JS code with change().
$("#username").change(function() {
$("#usertext").append("new input<br>");
});
You can do it like following snippet.
var text = '';
$("#username").on('blur', function() {
if(this.value != text){
text = this.value;
$("#usertext").append('new input<br>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="username" id="username">
<br>
<span id="usertext"></span>

How can I add to the end of the string that already exists in input field?

Now, If I hit the button, it clears all in the input field, and it automatically inputs "#marry" to it.
But, I don't want it to be cleared:(
What if I want to add "#marry" to the end of the strings that already exists in the input field?
How can I customize my javascript part?
Input field
<textarea class="box text_area" cols="10" id="input" name="comment[body]"></textarea>
button
<a href="#topic" id="username" value="#marryā€¯><span class='btn'>reply</span></a>
javascript
$(document).on('click', 'a#username', function() {
$(".box#input").val($(this).attr('value'));
}
val() has a callback with the arguments index and value, you can use that to easily add something to the value.
$(".box#input").val(function(_, val) {
return this.value + 'some extra string';
});
$(document).on('click', 'a#username', function() {
var self = this;
$(".box#input").val(function(_, val) {
return val + self.value;
});
});
First of all adeneo's answer is good and you should read it. Here is an alternative solution that does not use jQuery:
I assume that both these elements are a part of a form. Let's say for instance the form has an ID of "post". We can access it using document.forms and then its fields as such:
var input = document.forms.post["comment[body]"];
Now, we can add to its value whenever the button is clicked. First select username with getElementById or querySelector and then add the event:
username.addEventListener("click", function(ev){
input.value += ev.target.value;
});
Or with jQuery (this also delegates if the element is not in the DOM yet):
$(document).on('click', 'a#username', function() {
input.value += this.value;
});
It might be desirable to append an extra space between the current text and the username.
append #marry at the end of text area. you can use bellow code its working fine.
$(document).on('click', 'a#username', function () {
var txtvalue = $(".box#input").val();
$(".box#input").val(txtvalue + $(this).attr('value'));
});
see jsfiddle link http://jsfiddle.net/F6mkh/1/

How to get reference to current textbox in a table which contains 50 textboxes?

Basically i have table with 50 rows and each row has 2 td. One for input and next one has label and everything is dynamic.
Refer this image
Dilemma
The user enters a number in the textbox(how do i know which one if i dont want to loop through all of them?) and on enter key event i call a javascript function which checks if its valid and adds corresponding message to the next tds label.
How to know the reference of input without looping through all the textboxes as i call the function on each textbox input's enter function?
The following works, based upon the (limited available information), though requires you to handle validation yourself, obviously:
function yourDefinedFunction(){
// you need to handle the validating yourself, somehow.
return false;
}
/* binds the 'keypress' to the 'tr' elements, which 'listens' to see
if they take place on/in a 'td' element */
$('tbody tr').on('keypress', 'td', function(e){
/* 'this' is the 'td' element,
'e.target' is the element within the 'td' that received the event
var cell = this,
target = e.target;
// if the key pressed is the enter key, *and* the target was the input, then:
if (e.which === 13 && target.tagName.toLowerCase() == 'input') {
// you determine whether the entry is valid, however you want:
var validity = yourDefinedFunction() || 'valid';
// and set the text of the next 'td' element to reflect that validity:
$(cell).next('td').text(validity);
}
});
JS Fiddle demo.
References:
next().
on().
text().
use the "change" event for the textbox such as: first add class='myTextboxClass' to your text boxes markup.
$(mytableselector).on('change','.myTextboxClass', function(){
var me = this; // the one that changed
$(this).val();//value of that textbox
});
set the sibling text:
$(mytableselector).on('change','.myTextboxClass', function(){
var me = this; // the one that changed
$(this).val();//value of that textbox
$(me).parent('td').next('td').html('Invalid entry');
});
$("selector for table").on("keyup", "input[type=\"text\"]", function(ev) {
if (ev.which !== 13) {
return;
}
alert($(this).value());
});
Example
It's hard to give a good example without knowing specifically what you're trying to do, but something like this would work:
$('tr > td:first > input').keyup(function(e) {
//jQuery object representing the input box the user typed into
var input_box = $(this);
//get which key was pressed
var key_pressed = e.which;
});
If you use the on... events, this will point to the current input.
Example:
<td>
<textarea onchange="foo(this)">
</td>
<td>
Hello
</td>
...
function (input) {
input.parentNode.nextSibling.innerHTML = input.value;
}
This example would change the value of the td to the right of the textarea to the value of the textarea.
(Not very robust code, but it's just an example.)
$("#tableID :text").keyup(function(e) {
if (e.which !== 13) { //check if the key pressed is Enter
return; // if it is not, stop execution of code
}
var nextTD = $(this).closest('td').next();
//your code goes after this line
});
After the declaration of nextTD you can insert your code to update the td content as you prefer.
P.s.: I'm assuming that your table is in the form of the example linked below
JSFiddle Example

How to update span when text is entered in form text field with jquery

I would like a span to update when a value is entered into a text field using jquery.
My form field has a text box with the name "userinput" and i have a span with the id "inputval".
Any help would be greatly appreciated.
UPDATE:
although you marked this as the correct answer, note that you should use the keyup event rather than the change event or the keydown
$(document).ready(function() {
$('input[name=userinput]').keyup(function() {
$('#inputval').text($(this).val());
});
});
Try the following, you have to call again keyup() to trigger for the last char:
$(".editable_input").keyup(function() {
var value = $(this).val();
var test = $(this).parent().find(".editable_label");
test.text(value);
}).keyup();
Try this. Be sure that you understand what is going on here.
// when the DOM is loaded:
$(document).ready(function() {
// find the input element with name == 'userinput'
// register an 'keydown' event handler
$("input[name='userinput']").keydown(function() {
// find the element with id == 'inputval'
// fill it with text that matches the input elements value
$('#inputval').text(this.value);
}
}
$(function() {
$("input[name=userinput]").keydown(
function() {
$('#inputval').text(this.value);
}
)
})

Categories