I have an input type="tel" with id="#enter" and I want to add append values from button clicks. I have done this:
$("#one").click(function () {
$("#myInput").val("1");
});
$("#two").click(function () {
$("#myInput").val("2");
});
So every time a button is pressed from #id 1-9 it enters the corresponding numeric value.
However this doesn't append the value in the input field type just replaces the existing value with the value of the button clicked. How can it append the values?
This is the JSFiddle
You can use something like this to append values:
$("#myInput").val(function() {
return this.value + '1';
});
You can also improve your approach by giving each number button a class and register the same event listener for all buttons. For example:
$(".dial").click(function () {
var number = $(this).data('number');
$("#myInput").val(function() {
return this.value + number;
});
});
Where the button would be defined as
<button type="button" class="btn btn-primary btn-xs1 dial" data-number="4"> <b>GHI<br>4
as so on.
Demo: http://jsfiddle.net/8R9xL/2/
Try this
$("#one").click(function(){
$("#myInput").val($("#myInput").val()+"1");
});
Of course it doesn't append the value, you've done nothing to make it append the value.
To append the value you have to...append the value. Get the current value, add (append) something to it, and then set that.
$("#one").click(function(){
var input = $("#myInput");
input.val(input.val() + "1");
});
$("#two").click(function(){
var input = $("#myInput")
input.val(input.val() + "2");
});
$("#one").click(function(){
var input = $("#myInput");
input.val(parseInt(input.val() + 1));
});
$("#two").click(function(){
var input = $("#myInput")
input.val(parseInt(input.val() + 2));
});
I have done something like this.
$('.pin-number').on('click', (e) => {
$('#pin').val($('#pin').val() + e.target.innerText)
})
Where .pin-number is a set of divs containing a number from 0 to 9 (this is the reason that I use e.target.innerText instead of e.target.value), and #pin is the input where the values are inserted.
Hope this helps!
Related
I have an input text in jQuery I want to know if it possible to get the value of that input text(type=number and type=text) before the onchange happens and also get the value of the same input input text after the onchange happens. This is using jQuery.
What I tried:
I tried saving the value on variable then call that value inside onchange but I am getting a blank value.
The simplest way is to save the original value using data() when the element gets focus. Here is a really basic example:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/
$('input').on('focusin', function(){
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
});
$('input').on('change', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value " + prev);
console.log("New value " + current);
});
Better to use Delegated Event Handlers
Note: it is generally more efficient to use a delegated event handler when there can be multiple matching elements. This way only a single handler is added (smaller overhead and faster initialisation) and any speed difference at event time is negligible.
Here is the same example using delegated events connected to document:
$(document).on('focusin', 'input', function(){
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
}).on('change','input', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value " + prev);
console.log("New value " + current);
});
JsFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/65/
Delegated events work by listening for an event (focusin, change etc) on an ancestor element (document* in this case), then applying the jQuery filter (input) to only the elements in the bubble chain then applying the function to only those matching elements that caused the event.
*Note: A a general rule, use document as the default for delegated events and not body. body has a bug, to do with styling, that can cause it to not get bubbled mouse events. Also document always exists so you can attach to it outside of a DOM ready handler :)
Definitely you will need to store old value manually, depending on what moment you are interested (before focusing, from last change).
Initial value can be taken from defaultValue property:
function onChange() {
var oldValue = this.defaultValue;
var newValue = this.value;
}
Value before focusing can be taken as shown in Gone Coding's answer. But you have to keep in mind that value can be changed without focusing.
Just put the initial value into a data attribute when you create the textbox, eg
HTML
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
JQuery
$("#my-textbox").change(function () {
var oldValue = $(this).attr("data-initial-value");
var newValue = $(this).val();
});
I have found a solution that works even with "Select2" plugin:
function functionName() {
$('html').on('change', 'select.some-class', function() {
var newValue = $(this).val();
var oldValue = $(this).attr('data-val');
if ( $.isNumeric(oldValue) ) { // or another condition
// do something
}
$(this).attr('data-val', newValue);
});
$('select.some-class').trigger('change');
}
I found this question today, but I'm not sure why was this made so complicated rather than implementing it simply like:
var input = $('#target');
var inputVal = input.val();
input.on('change', function() {
console.log('Current Value: ', $(this).val());
console.log('Old Value: ', inputVal);
inputVal = $(this).val();
});
If you want to target multiple inputs then, use each function:
$('input').each(function() {
var inputVal = $(this).val();
$(this).on('change', function() {
console.log('Current Value: ',$(this).val());
console.log('Old Value: ', inputVal);
inputVal = $(this).val();
});
my solution is here
function getVal() {
var $numInput = $('input');
var $inputArr = [];
for(let i=0; i < $numInput.length ; i++ )
$inputArr[$numInput[i].name] = $numInput[i].value;
return $inputArr;
}
var $inNum = getVal();
$('input').on('change', function() {
// inNum is last Val
$inNum = getVal();
// in here we update value of input
let $val = this.value;
});
The upvoted solution works for some situations but is not the ideal solution. The solution Bhojendra Rauniyar provided will only work in certain scenarios. The var inputVal will always remain the same, so changing the input multiple times would break the function.
The function may also break when using focus, because of the ▲▼ (up/down) spinner on html number input. That is why J.T. Taylor has the best solution. By adding a data attribute you can avoid these problems:
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
If you only need a current value and above options don't work, you can use it this way.
$('#input').on('change', () => {
const current = document.getElementById('input').value;
}
My business aim was removing classes form previous input and add it to a new one.
In this case there was simple solution: remove classes from all inputs before add
<div>
<input type="radio" checked><b class="darkred">Value1</b>
<input type="radio"><b>Value2</b>
<input type="radio"><b>Value3</b>
</div>
and
$('input[type="radio"]').on('change', function () {
var current = $(this);
current.closest('div').find('input').each(function () {
(this).next().removeClass('darkred')
});
current.next().addClass('darkred');
});
JsFiddle: http://jsfiddle.net/gkislin13/tybp8skL
if you are looking for select droplist, and jquery code would like this:
var preValue ="";
//get value when click select list
$("#selectList").click(
function(){
preValue =$("#selectList").val();
}
);
$("#selectList").change(
function(){
var curentValue = $("#selectList").val();
var preValue = preValue;
console.log("current:"+curentValue );
console.log("old:"+preValue );
}
);
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/
I facing problem with my jquery, on showing input text based on input value.
Here is the JS fiddle demo :
http://jsfiddle.net/Ltapp/364/
When I try to input #hotmail, the input box will show. But when I want to type some text in the #hotm input box, it will hide again.
JS code :
$(window).load(function(){
var myString = '#hotmail';
$('#hotm').hide();
$("input").keyup(function () {
var value = $(this).val();
if($(this).val().match(myString)) {
$('#hotm').show();
} else {
$('#hotm').hide();
}
});
});
It's because your selector $("input") affects both input elements. I have updated it to the $("input:first") selector instead. JsFiddle here
$("input:first").keyup(function () {
var value = $(this).val();
if(value.match(myString)) {
$('#hotm').show();
} else {
$('#hotm').hide();
}
});
As many has said, you are binding the event on all the inputs I did a little change:
$(function(){
var myString = /#hotmail/ig;
$("#check").bind('keyup checkvalue', function() {
$('#hotm')[myString.test(this.value) ? 'show' : 'hide']();
}).trigger('checkvalue');
});
using regex if you are using #HoTmAil it will also hit on that, and also added a custom event checkvalue to see if #hotm should be visible on for example a postback on the form you might be using.
demo: http://jsfiddle.net/voigtan/xjwvT/1/
You're affecting all inputs. Either give each one a unique ID / Class or use the jQuery $(this) method.
See JSFiddle Here:
http://jsfiddle.net/Ltapp/366/
<input type="text" id="firstinput"/>
<p id="secondinput"><input type="text"/></p>
var myString = '#hotmail';
$('#secondinput').hide();
$("#firstinput").keyup(function () {
var value = $(this).val();
if($(this).val().match(myString)) {
$('#secondinput').show();
} else {
$('#secondinput').hide();
}
});
use this for your if part :
if($(this).val().match($(this).val().substr(0,strlen($(this).val())))
it's because the new box also = "input"; if you give the hotmail textbox it's own id, it won't hide
<input id="hotmail" type="text"/>
and then
$("#hotmail").keyup(function () {...});
I have this code:
$('.update-title')
.change(function () {
$(this).prop('title', $('option:selected', this).prop('title'));
});
and this HTML:
<select id="modal_TempRowKey_14" class="update-grid update-title">
...
...
</select>
<input id="modal_Title_14" class="update-grid" type="text" value="xx">
Is it possible for me to make it so that when the .update-title changes
then the value of the title is put into the input id with the matching number.
So in this case the #modal_TempRowKey_14 title would go into #modal_Title_14 value
Important
I want this to happen only if the element being changed starts with modal_TempRowKey. Is this possible to put into the change block?
Try
$('.update-title').on("change", function() {
var id = this.id.replace('modal_TempRowKey_', '');
$("#modal_Title_" + id).val( $(this).val() );
});
My suggestion, rather than trying to parse id attributes, is to make use of jQuery's data function.
Edit your HTML so that the select menu has a data-target attribute:
<select id="modal_TempRowKey_14" data-target="#modal_Title_14" class="update-grid update-title">
...
...
</select>
Then, create your event handler like so:
$('.update-title').on('change',function() {
var $this = $(this);
$($this.data('target')).val($this.val());
})
You use the data-target attribute to find the element to which you want to apply the select menu's value.
Here's a demo:
--- jsFiddle DEMO ---
$('.update-title').change(function () {
var m = this.id.match(/^modal_TempRowKey_(\d+)$/);
if (m) {
$("#modal_Title_" + m[1]).val(this.id);
}
});
DEMO.
Others have a more elegant approach, here is my attempt:
http://jsfiddle.net/8sLCL/1/
$('.update-title')
.change(function () {
var my_text = $(this).find(":selected").text();
var my_id = $(this).attr("id");
var my_num_pos = my_id.lastIndexOf("_");
var my_num = my_id.substr(my_num_pos + 1 ,my_id.length - my_num_pos );
$( "#modal_Title_" + my_num ).val(my_text );
});
can someone show me how to take an input value and append it to a div once the user clicks on an Add link?
This is the best I could do.
HTML:
<div id="customUtility-container"></div>
Add
jQuery:
$(function() {
var addDiv = $('#customUtility-container');
var i = $('#customUtility-container').size() + 1;
$('#addUtility').live('click', function() {
$('#customUtility').val().appendTo(addDiv);
$('<p><label for="customUtility-container"><input type="text" id="customUtility" size="20" name="customUtility_' + i +'" value="" placeholder="" /></label> Remove</p>').appendTo(addDiv);
i++;
return false;
});
$('#removeUtility').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
This creates another input field however; I just want to have one input box, have the user click Add, then it takes that value, puts it into the list, and clears the input box so the user can add something else again.
Use jQuery's append() function
addDiv.append($('#customUtility').val());
Here's a working fiddle.
Warning: opinion below
When creating a variable to store a jQuery object, I think it's helpful to prefix the variable with $. This way, you know that you're working with a jQuery object. It also makes it easier for those coming behind you to recognize what you're doing:
var $addDiv = $('#customUtility-container');
$addDiv.append($('#customUtility').val());
Something like:
addDiv.html(addDiv.html() + whateveryouwanttoadd)
addDiv.append($('#customUtility').val());
Change
$('#customUtility').val().appendTo(addDiv);
To
addDiv.append($('#customUtility').val());
val() method gives the value of the input element and you cannot call a jQuery method on a string which will throw an error.
Working demo - http://jsfiddle.net/t9D8R/
I ended up scrapping everything and redoing it:
$(function() {
var i = $('#customUtility-container').size() + 1;
$("#addUtility").on("click", function() {
$("#customUtility-container").append('<div id ="customUtility_' + i +' " name="customUtility_' + i +' ">'+ $("#customUtility").val() + 'Remove</div>');
});
$('#removeUtility').live('click', function() { $(this).closest('div').remove();
i--;
});
});