I have looked everywhere for this, and all I am getting is stuff about dynamically appending more options.
I have a function that calls the following:
$("#" + id_name).val(result).trigger("chosen:updated");
this is called when clicking a suggested button, which then is supposed to add it to the chosen-container-multi container that has all the inputs and so on.
If I call the function again, it erases the previous result and puts the new one in that field. This container is supposed to be able to hold multiple results. How could I go about doing this such that it appends the result to the prior results rather than replace it?
http://jsfiddle.net/16Lj1whL/2/
function addValue(id_name,result)
{
$s=$('#'+id_name);
$s.find('option[value="'+result+'"]').prop('selected',true);
$s.trigger("chosen:updated");
}
Try .prop( propertyName, function )
$("#" + id_name).prop("value", function(_, val) {
return val + result
}).trigger("chosen:updated");
var input = $("input")
, result = 0
, update = function() {
input.prop("value", function (_, val) {
return val + ++result
})
};
$("button").on("click", update)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>click</button>
<input type="text" value="0">
Related
I use the following to get the json for each member and create an element with a click listener.
$.getJSON('/api/members', function (membersJson) {
$(membersJson).each(function (i, item) {
$('#contacts').append('<div class="membercard">' + item.Name + '</div>');
.click(() => show_details(item));
})
});
function show_details(item) {
$('#memberName').val(item.Name);
$('#memberOcc').val(item.Occupation);
}
When a membercard is clicked it is meant to send its info to a more detailed div. However, when clicking on any of the dynamically created divs, only the item data from the last json in the loop is sent to the detailed view. Why is this and how can I fix it?
you are binding and iterating inside a loop, this is to avoid in general, because the scope of the function will in the click, will take only the last element of the loop
Try refactoring like this:
$('#contacts').on('click', '.membercard', function() {
show_details($(this).data('item'));
});
$.getJSON('/api/members', function (membersJson) {
$(membersJson).each(function (i, item) {
var div = $('<div class="membercard">' + item.Name + '</div>');
div.data('item', item);
$('#contacts').append(div)
})
});
function show_details(item) {
$('#memberName').val(item.Name);
$('#memberOcc').val(item.Occupation);
}
This is a common problem with JavaScript. Essentially, because the click event happens after the loop, the “item” variable is equal to the last item. To fix this, simply change:
$(“#contacts”).click(() => show_details(item));
To:
let _item = item;
$(“#contacts”).click(() => show_details(_item));
This creates a copy of the variable that will have the same value even after the loop completes.
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 );
}
);
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!
$(document).ready(function () {
var names = ["nick", "nicky", "nickyy", "nick23", "nickfe09", "nickf9", "jim1", "jimbo2"];
$.each(names, function (index, value) {
$('<span>').html(value + '<br>').appendTo('#div');
});
$('#input').change(function (event) {
$('#div > span:contains("' + $('#input').val() + '")').css('background', 'red');
});
});
<div id="div"></div>
<input type="text" id="input">
Hello again stackoverflow!
I have a string with usernames. I want to display them in a table (or in this example, just a list) and then display only like 10 of them (There are going to be ~200 names in the list eventually). When the user inputs something in the input field, for example nic, I want it to filter the rest and display the 10 best matching usernames.
I've tried the setup above but this didn't work. Could you guys help me?
Greetings
Fiddle: http://jsfiddle.net/4wZ2L/5/
See this working demo.
$(document).ready(function () {
var names = ["nick", "nicky", "nickyy", "nick23", "nickfe09", "nickf9", "jim1", "jimbo2"];
$.each(names, function (index, value) {
$('<span>').html(value + '<br>').appendTo('#div');
});
$('#input').on("change keyup", function (event) {
$('#div > span').css('background','');
$('#div > span:contains("' + $(this).val() + '")').css('background', 'red');
});
});
All I did was the following:
Make it so #input responds to the keyup event in addition to change.
Clear all of the spans of their formatting before determining which ones match.
In the line where you actually change the content, I changed input.val to $(this).val(). The variable input was undefined.
Hope this helps!
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--;
});
});