Use jQuery variable within selector name - javascript

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

Related

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

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

How to assign value to a #html.validationfor id?

#Html.ValidationMessageFor(m => m.name, "", new { id = "valName" })
I need to assign value for "valName" using JavaScript or jQuery.
Is there any way to assign value to the id?
It is not clear exactly what you want to do?
If you want to change the id of the validation message DOM element:
document.getElementById('valName').id = 'newId';
// or via jQuery
$('#valName').attr('id', 'newId');
If you want to change the text of the validation message DOM element:
document.getElementById('valName').innerHTML = 'new content';
// or via jQuery
$('#valName').html('new content');
This should work:
$(document).ready(function () {
$('[class^=field-validation]').each(function () {
var id = "val" + $(this).attr("data-valmsg-for");
$(this).attr("id", id);
});
});
It will set the id to the same as the form field but prefixed with "val".

Get element by ID using class name

I want get the id of the element that is clicked and within a specified class, and want to print the ID.
Here is my JS , I am really new JS , Please help
$('.wrapinner').click(function(e) {
$('.wrapinner').css("margin-top","0");
$('.wrapinner').css("opacity","0.4");
$(this).css("margin-top","25px");
$(this).css("opacity","1");
var r= document.getElementById(this).attributes.toString();
document.write(r);
});
There are two ways to do this:
1) Done without jQuery object (it is faster)
$(".wrapinner").click(function(){
//Your Code
var id = this.id;
document.write(id);
});
OR
2) Done with jQuery object:
$(".wrapinner").click(function(){
//Your Code
var id = $(this).attr('id');
document.write(id);
});
NOTE after jfriend00's comment.
Use document.write() if really needed and is not harmful to your page OR use console.log(). Read Why is document.write considered a "bad practice"?
You can call the native javascript object directly; this.id.
$('.wrapinner').click(function(e) {
$('.wrapinner').css("margin-top","0").css("opacity","0.4"); // chained these two
$(this).css("margin-top","25px").css("opacity","1"); // chained these two
var r = this.id; // this should already reference the correct element.
document.write(r);
});
Try this way :
$('.wrapinner').click(function(e) {
console.log(this.id);
});
You are not passing id to getElementById, rather you are passing the object it self. You can get id of source object of event using this.id not by this.
Change
var r= document.getElementById(this).attributes.toString();
To
var r= document.getElementById(this.id).attributes.toString();
Just write
document.write(this.id)
$(".wrapinner").click(function(){
var id = this.id
});
Try this example:
<table>
<tbody>
<tr id="CustomerScreen" class="rows"></tr>
<tr id="TraderScreen" class="rows"></tr>
<tr id="DistributorScreen" class="rows"></tr>
</tbody>
</table>
<script>
$('.rows').each(function () {
var ar = this.id;
console.log(ar);
});
</script>
You can check this code..
$('.wrapinner').click(function(e) {
var getID = $(this).attr('id');
alert(getID);
});
Try this:
$('.wrapinner').click(function(e) {
$('.wrapinner').css("margin-top","0");
$('.wrapinner').css("opacity","0.4");
$(this).css("margin-top","25px");
$(this).css("opacity","1");
var id = $(this).attr('id');
});
I am capturing click event on class and then finding its id and class name using parent().
demodemo
$(document).ready(function(){
$('.class-first ul li, .class-second ul li, .class-third ul li').on('click',function(){
console.log("child :"+$(this).attr('id') + " Parent:"+$(this).parents().eq(1).attr('class'));
});
})

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.

jquery capturing text of selected id

If I have id's of the form: t_* where * could be any text, how do I capture the click event of these id's and be able to store the value of * into a variable for my use?
Use the starts with selector ^= like this:
$('element[id^="t_"]').click(function(){
alert($(this).attr('id'));
});
Where element could be any element eg a div, input or whatever you specify or you may even leave that out:
$('[id^="t_"]').click(function(){
alert($(this).attr('id'));
});
Update:
$('[id^="t_"]').click(function(){
var arr = $(this).attr('id').split('_');
alert(arr[1]);
});
More Info:
http://api.jquery.com/attribute-starts-with-selector/
var CurrentID = $(this).attr('id');
var CurrentName = CurrentID.replace("t_", "");
That should help with the repalce.
Try this:
// handle the click event of all elements whose id attribute begins with "t_"
$("[id^='t_']").click(function()
{
var id = $(this).attr("id");
// handle the click event here
});
$("[id^='t_']").click(function()
{
var idEnding = $(this).attr("id");
idEnding.replace(/\t_/,'');
});
Using the click event capture the ID that begins with t_, then replace that with nothing giving a capture the end of the ID value.

Categories