I have problem in add new input:checkbox, when i adding new input and checked on it next setup clicked on button i not have value for input:checkbox that was checked. how is fix it?
DEMO: http://jsfiddle.net/G4QRp/
$(function () {
$('a.add_input').live('click', function (event) {
event.preventDefault();
var $class = '.' + $(this).closest('div.find_input').find('div').attr('class').split(" ")[0];
var size_un = $($class).length;
var $this = $(this),
$div = $this.closest($class),
$clone = $div.clone().hide().insertAfter($div).fadeIn('slow');
$clone.find('.adda').not(':has(.remove_input)').append('<div class="mediumCell"></div>');
$clone.find('input').val('').prop('checked', false);
$this.remove();
var size_un = $($class).length---1;
$($class + ':last input:checkbox').prop('name', 'checkbox_units[' + size_un + '][]');
console.log($($class + ':last input:checkbox').prop('name'));
});
});
Your code always clears the value of all the checkboxes it adds:
$clone.find('input').val('').prop('checked', false);
It's working fine, though it's quite confusing. The alert correctly shows the checkboxes that are checked, but since your code has set the value to '' for each of them, well, it's empty. If you change it like this:
$clone.find('input').prop('checked', false);
it shows the values to be the same as the original checkboxes.
You might want to think about using "data-" attributes instead of the "class" string for storing things like that "add_units" class name.
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 );
}
);
I have this code right here for getting the id of a clicked input element:
jQuery(event.target.id).change(function(){
if(event.target.id===null)
{
}
else
{
alert(event.target.id);
}
});
for example: i have a dynamically generated textbox. Upon clicking it using the code above, it returns the id.
However when I click a dropdown list input, it returns null, but when inspecting the element, the id is there. It still goes to the else block.
I am using this event for fields that were dynamically generated.
What might be wrong?
Sorry if it seems noobish I am new on jQuery.
On select elements you need to listen to the change event, not the click event:
$('select').change(function() {
var selectId = $(this).attr('id');
var optionId = $(this).find(":selected").attr('id');
alert('select id:' + selectId);
alert('option id: ' + optionId);
});
UPDATE
Usually in a select element you would be looking for the option value. This is how you would do that:
$('#selectId').change(function() {
var optionValue = $(this).find(":selected").val()
alert(optionValue);
});
Try access original target
var originalElement = event.srcElement || event.originalTarget;
console.log(originalElement.id)
I have selects with some values, and i want to remember value by clicking one of them and after change do something with this.
$("select[id^='zmieniaj']").click(function() {
var poprz=$(this).val();
$("select[id^='zmieniaj']").change(function(){
...
});
});
So im remembering clicked value in variable and i refer to it in change function. It works good when i click only once on select and made change in the same step. If i click few times it does not trigger change function imimmediately, but it remembers how many times i clicked and when i made change it acts crazy by making up for previous clicks.
How to do that, if CONDITION A-click and CONDITION B-change is made only then, and only once do what is in change function ??
Try something like
$("select[id^='zmieniaj']").focus(function () {
var $this = $(this);
$this.data('fvalue', $this.val());
}).change(function () {
var $this = $(this),
cval = $this.val(),
pval = $this.data('fvalue');
});
I have a small script of javascript which iterates over a set of checkboxes which grabs the name attribute and value and then convert it to json. Then I use that value to set the href of an element and then try to trigger a click.
For some reason everything seems to function properly except for the click. I successfully change the href, I console.log() a value before the .click() and after. Everything hits except for the click. The url in the href is value as I clicked it manually.
I have my script included just before the closing body tag and have it wrapped in $(document).ready(). and I do not have duplicate ID's (I viewed the rendered source to check)
Can anyone offer some insight on this?
Here is the javascript
$(document).ready(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var i = 0;
var list = new Array();
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var id = $(this).val();
list[i] = new Array(name, id);
i++;
});
var serList = JSON.stringify(list);
console.log(serList);
var webRoot = $("#webRoot").text();
$("#exportLink").attr('href', webRoot+"/admin/admin_export_multiExport.php?emailList="+serList); //hits
console.log('1'); //hits
$("#exportLink").click(); //this line never executes
console.log('2'); //hits
});
});
$(selector).click() won't actually follow the link the way clicking on it with your mouse will. If that's what you want, you should unwrap the jquery object from the element.
$(selector)[0].click();
Otherwise, all you're doing is triggering event handlers that may or may not exist.
I may guess you need
$(document).on('click', '#multiExport', function(e){
(you can replace document by a nearest element, if you got one).
if you need dynamic click event binding.
EDIT
I would try something like that :
$(document).ready(function() {
$("#exportLink").click(function() {
window.location = $(this).attr('href');
});
$("#multiExport" ).on('click', function(e){
//whatever you want
$('#exportLink').attr('href', 'something').trigger('click');
});
});
$("#exportLink").click(); // this would launch the event.
I must admit I am very surprised that the .click() does not work.
If the idea is to load the page, then the alternative is
$(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var list = [];
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var val = $(this).val();
list.push([name, val]);
});
var serList = JSON.stringify(list);
var webRoot = $("#webRoot").text();
location=webRoot+"/admin/admin_export_multiExport.php?emailList="+serList;
});
});
I have a hidden select which should be automatically selected via a visible select, my jquery is:
$(document).ready(function() {
var selected_val = $('#id_foo option:selected').val();
$('#id_bar').val(selected_val);
$("#id_foo").change(function() {
selected_val = $(this).attr('value');
$('#id_bar').val(selected_val);
});
});
This works fine, but the page I am working on has the option to add a value to the (visible) select on the fly. How do I bind to this event and add this to the hidden list before updating the selected value?
The best way to tackle this is to update the hidden select with the new values when you update the visible one.
Or, as per my comment, you could populate the hidden select when the visible one is changed:
$("#id_foo").change(function() {
selected_val = $(this).attr('value');
//clear and re-populate all of hidden select here
$('#id_bar').val(selected_val);
});
This should do the trick:
$(function () {
var $bar = $('#id_bar');
var $foo = $('#id_foo');
$bar.val($foo.val());
$foo.change(function () {
var newValue = $(this).val();
if ($bar.find('[value="' + newValue + '"]').length === 0) {
$bar.append($('<option/>').val(newValue));
}
$bar.val(newValue);
});
});
Before setting the new value, checks if the value is an option. If it's not, add as an option.
This snippet correctly identifies the event and succesfully copies the select options from foo to bar. However it does not seem to set :selected correctly on either id_foo or id_bar and using DOMSubtreeModified feels hackish
$('#id_foo').bind("DOMSubtreeModified", function(){
var high = 0;
$('#id_foo').children().each(
function(){
if ($(this).val() > high) {
high = $(this).val();
}
}
);
$('#id_foo').val(high);
var new_options = $('#id_foo').clone();
$('#id_bar').html('');
$('#id_bar').append(new_options.children());
});
So, for now the best I could come up with:
$('#id_foo').bind("DOMSubtreeModified", function(){
location.reload();
});