jquery dynamic id - javascript

i use such code to access item
function f(id){
$("#"+id).val(); // with analogy $("#id item")
}
is it correct? is any other methods?

If you want to return the value of an element with specified id, then yes as that is what seems to be logical purpose of your function:
function f(id){
return $("#" + id).val();
}
The functions should assume that an element with specified id exists and then it returns you the value of that element. This should work for input fields as well as textarea. If however, it is any other element, you might want to use html() or text() instead of val() eg:
function f(id){
return $("#" + id).html();
// return $("#" + id).text();
}

You could use PureDom
function f(id){
return document.getElementById(id).value;
}
Take that, jQuery!

Yes this is perfectly valid way to access the element having its id.

From the jQuery API website:
.val() Returns: String, Array
Description: Get the current value of
the first element in the set of
matched elements.
What It's not clear to me when you say
// with analogy $("#id item")
is if you want to have ONLY one child item of the one that is identifiedby #id or if you need the item that is identified by item#id.
Your code is perfect if you are passing a string like "hello" inside your code and you want to get the DOM element with ID of #hello.

Related

Append array value to ID attribute of selected elements

Simply, i'm trying to use jQuery to append a numeric value (currently stored in an array) to the end of the "id" attribute of a number of specified elements.
$('#headerAfirstLink, #headerAsecondLink, #headerAthirdLink, #headerAfourthLink').attr("id", // Append modCount[0].toString() to each existing ID);
The struggle I am having is in working out how to append the numeric value as opposed to simply set the ID equal to the numeric value. I don't want to lose the existing ID.
In the example, the preferred resulting ID's should be:
#headerAfirstLink1, #headerAsecondLink1, #headerAthirdLink1, #headerAfourthLink1
(If modCount[0] == 1).
I'm sure it is crucifyingly simple but would appreciate some guidance.
Thanks
You can use .attr(attributeName, function) syntax to update the attribute value for each of the respective element.
$('#headerAfirstLink, #headerAsecondLink, #headerAthirdLink, #headerAfourthLink')
.attr("id", function(index, oldId) {
// oldId is the attribute value
return oldId + modCount[0];
});
Just in case, to update the attribute of all the elements whose ID starts with header, you can use attribute starts with selector.
$('[id^="header"]').attr('id', function(index, oldId) {
return oldId + modCount[0];
});
Try to use .attr("attrName" , callBack) signature to achieve what you want.
$('#headerAfirstLink, #headerAsecondLink, #headerAthirdLink, #headerAfourthLink')
.attr("id", function(_,id){
return id + modCount[0];
});
Don't confuse the first parameter passed with callBack. It is index. I just used an underscore there as it is not required in our case. Simply to hide its visual.
Or the best/maintainable approach would be setting a common class (ex: test) to those four elements and use a class selector there instead of multiple selector.
$('.test').attr('id', function(_, id) {
return id + modCount[0];
});

get checkbox name from javascript

I am trying to get a checkbox name when a checkbox is clicked...i am using a javascript function but it returns undefined.
Here is the code:
notType= document.getElementById($('[type="checkbox"]').attr('id')).value;
alert(notType);
In your code example, you are retrieving the value of the field, rather than the name. Instead, you should use:
var notType = document.getElementById(id).name;
you can do it like this:
$('input[type="checkbox"]').on('click', function(event){
alert(event.target.id);
});
This should work. $("#" + id) finds the element with the specified id. After that, you get the attribute called "name".
var notType = $("#" + id).attr("name");

same classes multiple times how to get object using index

I want to get an element's value based on the class and the index that it was created.
Fiddle here:
Code (not working)
alert($('.demo-default').length); //works
//alert ( $('.demo-default').get(2).val());
x = $('.demo-default').get(2);
alert(x).val();
//alert ( $('.demo-default').index(2 ).val()); //NW
WORKING :
http://jsfiddle.net/A324T/7/
You need to use eq() instead of x to invoke val() on it, or use .value
With
x = $('.demo-default').get(2); //x is DOM element.
Use
x.value; //Prop on DOM element
With
x = $('.demo-default').eq(2); //x is Jq object.
Use
x.val(); //method on jq object
get() returns the DOM element.
You want to use eq()
First, you use alert function wrong.
Also, jQuery.get() method will return a DOM element. val() method works only with jQuery objects. To fetch the value, simply use value property.
alert(x.value);

How to select empty inputs (value="") using jQuery

How can I check for empty values of (required) input fields within a section, and then add a class to them on an event, using jQuery? So far, I have tried:
jQuery("#sender_container input.required").val("").addClass("error");
But that seems to SET the value, rather than checking it. Any ideas?
jQuery("#sender_container input.required").filter(function() {
return !this.value;
}).addClass("error");​
Why you have to use filter and not [value=""] you can see in this DEMO
The reason is: attribute selectors check the initial state of the element, not the current state. (note that you can change the "initial" state with the attr function, but it's bad practice, you should always use prop)
So if you change the input value, the current value won't effect the attribute selector. not wise... :)
Notes:
.val() returns the value of the form element, and breaks the jQuery chain,
$('selector').val().addClass('foo') Error, the return value is a string\ number
.val(valueToSet) sets the value of the form element and doesn't break the jQuery chain.
$('selector').val("some value").addClass('foo') - Valid, the returned value is a jQuery
$('input:text[value=]','#sender_container').addClass('error');
DEMO
$('#sender_container input.required[value=""]').addClass('error')
jQuery('#sender_container input.required[value=""]').addClass("error");
You can try this:
$('input:not([value!=""])').addClass('error');
DEMO
Note: This answer should not be used, and the only reason it wasn't deleted is so it can be learned from.
$field = $("#sender_container input.required");
if( ! $field.val())
{
$field.addClass("error");
}
this simple way may work.
If you only need to select based on the initial attribute value of the input then the following will do:
var elements = $('#sender_container input.required[value=""]')
But be aware that this won't work if the value attribute isn't present. It also won't work for the current input value if it has been changed by user or script.
If you'd like to get the current input value you can use jquery's filter function:
var elements = $('#sender_container input.required').filter(function() {
return this.value === '';
// alternatively for "no value":
// return !this.value;
})
After you've selected the jquery elements you can add your class:
elements.addClass('error');
to get all fields inspected this might help.
$('#sender_container [required]').each(function(index)
{
if (!($(this).val())) $(this).addClass('error');
}
});

Selecting from a list of previously selected elements via jQuery

I'm having a bit of a brain fart here, and hoping someone can help me find a 1-line solution to this problem, without having to call .each().
So I get a list of all checkboxes within a container like this:
var checkboxes = $(':checkbox', '#surveyModal');
At some point later, I need to find out if any (or none) of the checkboxes are checked within that list.
I expected something like these to work:
$(':checked', checkboxes)
// or
checkboxes.attr(':checked')
// or
$(checkboxes).attr(':checked')
But it doesn't. The only thing I've had success with is calling each() and then checking each individually. But that means I'll have to keep a separate variable (.e.g. someAreChecked at a higher-level scope, which I don't feel is optimal.
checkboxes.each(function () {
if ($(this).attr('checked')) {
someAreChecked = true;
}
});
I was hoping that I can easily in a single line do such a check:
if (checkboxes.('get checked count') == 0)
{
}
Thanks in advance.
The filter function is what you're looking for :)
checkboxes.filter(':checked').length;
.attr returns the value of an attribute, and you have to pass the attribute's name to it, not a selector.
Just use .is instead.
Description: Check the current matched set of elements against a
selector, element, or jQuery object and return true if at least one of
these elements matches the given arguments.
$(checkboxes).is(':checked')
This should do it:
$("input[type=checkbox][checked]").length

Categories

Resources