How to get element where class name is not equal to value? - javascript

I would simply like to find out how to get an element where the class name is not equal to the value passed in. E.g:
$(document).ready(function () {
$(document).on('change', '#allRolesDD', function () {
var toShow = document.getElementsByClassName($(this).val());
//Below line is the one where I want to get the value where the class name is not equal to the value
var toHide = document.getElementsByClassName(!$(this).val());
alert($(toHide).html());
toHide.attr('hidden', true);
toShow.show();
});
});

Use :not selector
$('selector:not(.hateThisClass)')
You can also use .not() to "Remove elements from the set of matched elements."
$('selector').not('.hateThisClass')
Complete Code:
$(document).on('change', '#allRolesDD', function () {
var toShow = '.' + $(this).val();
$(toShow).show();
$(':not(' + toShow + ')').hide(); // Assumed the elements need to hide, not just adding an attribute
});

You have to use the :not selector.
Here is the full documentation for that.
Usage example
XX:not(<class>)

Don't mix up pure JavaScript and jQuery, use :not selector to filter out like this:
$(document).ready(function () {
$(document).on('change', '#allRolesDD', function () {
var toShow = $("." + $(this).val());
//Below line is the one where I want to get the value where the class name is not equal to the value
// make sure you define your parent here.
var toHide = $(parent).find(":not(." + $(this).val() + ")");
alert($(toHide).html());
toHide.prop('hidden', true);
toShow.show();
});
});

Related

Use jQuery variable within selector name

I'm grabbing the value of an input and setting this as a variable. How can I then use this as part of the selector name. Here's a demo of where I've got too and what I'm trying to achieve
// grab the id
var rowId = $('input[name="row-id"]').val();
// Use the variable as part of selector
$('body').on("click", ".upload-form-'rowId'", function(event) {
// do stuff here
})
The output of the selector would be like .upload-form-99 for example
Why not just do this:
// grab the id
var rowId = $('input[name="row-id"]').val();
rowId = '.upload-form-' + rowId;
// Use the variable as part of selector
$('body').on("click", rowId, function(event) {
// do stuff here
})
Any particular reason that this wouldn't work?
$('body').on("click", ".upload-form-" + rowId, function...
Here's a more elegant solution if you happen to be using ES6:
// grab the id
let rowId = $('input[name="row-id"]').val();
// Use the variable as part of selector
$('body').on("click", `.upload-form-${rowId}`, (event) => {
// do stuff here
})

Input jQuery get old value before onchange and get value after on change

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 );
}
);

How can I take contents of one element and add to another when they both have an id ending in the same two or three digit number?

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 );
});​

Jquery: trying to hide and show on hover on multiple divs with same id plus number

Trying to get a div that looks like <a id="thumblink-10"> to show and hide another div on hover, but no luck.
jQuery(document).ready(function() {
jQuery(document).find("a[id^='thumblink-']").live('hover', function(){
var num = this.id.split('-')[1];
jQuery('#thumb-hover-' + num).show();
}, function(){
//var num = this.id.split('-')[1];
jQuery('#thumb-hover-' + this.num).hide();
});
});
Thanks
This should work for you:
jQuery("a[id^='thumblink-']").live('hover', function(){
var num = this.id.split('-')[1];
jQuery('#thumb-hover-' + num).toggle();
});
Fixed the initial selector to not use find, only need to supply and single function for the hover and use the toggle function to show/hide the content.
http://jsfiddle.net/Zy2Ny/
But the way I would actually do it is to add data attributes to your links (can then change the selector to a class one instead) and use those to find the correct div to toggle like this:
JS
jQuery("a.thumblink").live('hover', function(){
var num = $(this).data('contentid');
jQuery('#thumb-hover-' + num).toggle();
});
HTML
<a class="thumblink" data-contentid="10">Hover</a>
<div id="thumb-hover-10" style="display: none;">Content</div>
http://jsfiddle.net/Zy2Ny/1/
You can't really do traversal methods like find and then use live. You should just use a standard selection. Also, you can't use live with hover and give two functions.
$("a[id^='thumblink-']").live('hover', function(){ // simple selector
Better still would be to use delegate and a map of events and handlers:
$(document).delegate('a[id^="thumblink-"]', {
mouseenter: function() {
},
mouseleave: function() {
}
});
I haven't been able to test it unfortunately, but I believe the following should work:
var id = 10;
$('#thumblink-' + id).hover(function(id) {
return function () {
$('#thumb-hover-' + id).show();
};
}(id),
function(id) {
return function () {
$('#thumb-hover-' + id).hide();
};
}(id)
);

Adding new input:checkbox and not has value

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.

Categories