here the snippet of code
var input_form =["first_text","middle_text","last_text","suffix_text","title_text","url_text","day_pnum","mon_pselect","year_pnum","day_anum","mon_aselect","year_anum"];
where "first_text","middle_text",... refers to the different ids in my html
i can access it via document.getElementById(input_form[i]), (within for loop)
but i have to use jquery, so whats wrong when i write the above code in jquery as $(input_form[i]) to get the same result
Since jQuery are query selectors (or CSS selectors), for id you need to prefix with #. So use this way:
$("#" + input_form[i])
You missed the # selector, try with this:
$("#" + input_form[i])
Hope it helps!
for (var i = 0; i < input_form.length; i++) {
var $el = $('#' + input_form[i]);
}
$el would give u the element's jquery reference
For id selectors, jQuery uses the JavaScript function document.getElementById(), which is extremely efficient. When another selector is attached to the id selector as #.you can use like below:
$("#" + input_form[i])
or
$('[id=input_form[i]]')
For more information check here
Depends on your needs, you can also select all of your input's as one jQuery object, is such case you can for e.g. call .val('') to clean all of them.
Example:
var input_form =["first_text","middle_text","last_text","suffix_text","title_text","url_text","day_pnum","mon_pselect","year_pnum","day_anum","mon_aselect","year_anum"];
var inputs_selector = input_form.map(s => "#" + s).join(",");
// reset all values
$(inputs_selector).val('');
Related
There are several functions to get DOM document elements e.g. .getElementById(), .getElementByName() etc. but I do not see any function which would allow to get element by type.
Is there some mechanism to do it?
You can use the getElementsByTagName() function to get all elements by their tag name.
I.e. getElementsByTagName("div") will return all <div>'s.
CSS selectors via .querySelectorAll are most powerful.
let p = document.querySelectorAll("p");
console.log(p[0].innerHTML + " and " + p[1].innerHTML);
<p>asdf</p>
<span>fdafsdf</span>
<p>kjkjkj</p>
You can get all elements by the type with 'document.querySelectorAll()' method.
As an example, you can get all the 'input' elements with type 'text' as follows.
document.querySelectorAll('input[type="text"]')
I have a variable that finds the data attribute of an element that is clicked on in a callback function:
var dropdown = document.getElementsByClassName('js-dropdown');
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", callBack (dropdown[i]));
}
function callBack (i) {
return function () {
var thisDropdown = i.getAttribute('data-dropdown');
//rest of the code here
}
}
I am basically trying to do this
$('#' + thisDropdown ).toggleClass('is-active');
...but in vanilla JS.
This works fine using jQuery however I would like a vanilla version.
So when a user clicks on an element that activates a drop down, I want it to dynamically find its relevant ID matching value within the document so it can toggle a show/hide class.
I've searched through a lot of SO questions and everyone replies with a jQuery answer which is not what I am looking for.
I've been trying to do something along the lines of
var idValue = document.getElementById(thisDropdown);
Then
var findId= idValue + thisDropdown;
findId.toggleClass('is-active');
Obviously that does not work the same way the jQuery statement works... any ideas?
Ignore the toggleClass method! Some of you may find this contradictory as I want vanilla JS.
To replace $('#' + thisDropdown ).toggleClass('is-active'); with plain js, use Element.classList. Like this:
const someElement = document.querySelector('#' + thisDropdown);
someElement.classList.toggle("is-active");
I like #kamyl's answer, but you might need backward compatibility. For that, see if you can find a polyfill.
If you have to write it yourself, use string.split(" ") to get your list of active attributes and iterate to find if it exists; add if not, remove if so...then array.join(" ") and replace the class attribute with it.
Given a select tag with options:
<div id='mydiv'>0</div>
<select id="mysel">
<option id="opt1">a</option>
<option id="opt2">b</option>
</select>...
How do I retrieve the actual string selection? Ie. How do I retrieve the actual "select#mysel" from the var mysel?
example of how this might be used?
var mysel = $("select#mysel");
var myopt = $(mysel.actualstringselection + " option");
var myoptcount = myopt.length;
alert("my option count:" + myoptcount );
$("#mydiv").html(myoptcount);
Answer for updated question:
How do I retrieve the actual "select#mysel" from the var mysel?
example of how this might be used?
var mysel = $("select#mysel");
var myopt = $(mysel.actualstringselection + " option");
So basically, you want the original selector string that you passed into $() in order to get mysel.
You can't get that. jQuery never offered an official way to do it. For a long time, there was an undocumented property on jQuery instances that contained it (mostly, most of the time), but it was always undocumented because it wasn't entirely reliable, and it doesn't even exist in current versions.
So instead, you can do it yourself:
var selector = "select#mysel";
var mysel = $(selector).data("selector", selector);
// Presumably somewhere else where you no longer have the `selector` variable:
var myopt = $(mysel.data("selector") + " option");
But, you wouldn't want to use that for the above. (You'd use find, as described originally [below]). The only reason I can think of for such a thing is if you've changed the DOM and want to repeat the original query. E.g.:
mysel = $(mysel.data("selector")); // Goes looking for the elements again
Original answer:
If after this line:
var mysel = $("select#mysel");
...you're trying to use mysel to find something within the descendant elements of any DOM elements in that jQuery object, you use find:
var optionElements = mysel.find("option");
What is the correct jquery syntax for a getElementsByName call?
Here is my javascript code:
var test = document.getElementsByName(tableName)[0];
using this is returning a different value:
var test = $("[name=tableName]");
Thanks in advance
Use quotes around the attribute selector:
$('[name="somenamehere"]');
If you need to use a variable within a selector, you need to use string concatenation to get the value of the variable:
$('[name="' + tableName + '"]');
Typically one should avoid using the [name] attribute in favor of the [id] attribute, because selection would be simpler as:
$('#someidhere');
-or-
$('#' + tableID);
Remove the index from the first statement
These are equal.
var test = document.getElementsByName(tableName);
var test = $("[name=tableName]");
"[name=tableName]" is bad syntax in 2 ways. First, you should put your name in quotes, so it should be "[name='tableName']" and second, in the first case, you're using a variable and in the second, a string, so in reality it shoudl be "[name='" + tableName + "']"
good call also on the fact that you have an index on your getelementsbyname() call, if you select item [0] then it will only return one item.
Interesting to know that jquery is a LOT slower than the native method here.
See the jsPrefs test : http://jsperf.com/getelementsbyname-vs-jquery-selektor/4
if you want to get a element value use this code:
var test1 = $("[name='tableName']").val();
alert(test1);
These are equal to get value of specific index[]:
For same index [0]
var test2 = $("[name='arryname[]']")[0];
alert(test2.value);
var test3 = $("[name='arryname[]']").get([0]);
alert(test3.value);
I have a function
function toggleSelectCancels(e) {
var checkBox = e.target;
var cancelThis = checkBox.checked;
var tableRow = checkBox.parentNode.parentNode;
}
how can I get a jQuery object that contains tableRow
Normally I would go $("#" + tableRow.id), the problem here is the id for tableRow is something like this "x:1280880471.17:adr:2:key:[95]:tag:". It is autogenerated by an infragistics control. jQuery doesn't seem to getElementById when the id is like this. the standard dom document.getElementById("x:1280880471.17:adr:2:key:[95]:tag:") does however return the correct row element.
Anyways, is there a way to get a jQuery object from a dom element?
Thanks,
~ck in San Diego
Absolutely,
$(tableRow)
http://docs.jquery.com/Core/jQuery#elements
jQuery can take the DOM elements, try with:
$(tableRow)
or
$(checkBox.parentNode.parentNode)
You should be able to pass the element straight in, like this:
$(tableRow)...
I have tested this by creating a reference to a div, then passing it straight into jQuery and it creates the jQuery object for you.
You can call the jQuery function on DOM elements: $(tableRow)
You can also use the closest method of jQuery in this case:
var tableRowJquery = $(checkBox).closest('tr');
If you want to keep using your ID, kgiannakakis (below), provided an excellent link on how to escape characters with special meaning in a jQuery selector.
See this for how you should escape the id.
try:
var r = $(document.getElementById("XXXX----ID Of Your Row----XXXX"));
now, if document.getElementById doesn't return undefined you can use r as any regular jquery object.