<input name="Indian_Karnataka_Bangalore" value="Bangalore" />
<input name="Indian_Andhra_Hyderabad" value="Hyderabad" />
<input name="Indian_Kerala_Trivandrum" value="Trivandrum" />
<input name="Indian_Maharashtra_Mumbai" value="Mumbai" />
At a given time, only one input element will be present in the DOM. How will I know the name of the specific input element name? I don't want to depend on values as it might change.
Using jQuery.
The INDIAN term will be static in every input element.
Actually i am trying to validate the input elements. DOM will have all the elements but at a given time only one element will be active and that element should have some value in it.
var $inputs = $('input[name*="Indian"]'),
inputsName = $inputs.attr('name');
You can use the same selectors as you would CSS.
Chris Coyier wrote a piece on attribute selectors here
var indianInputs = $("input[name^='Indian']");
//Matches all input elements whose name attrributes 'begin' with 'Indian'
This differs than the one posted by #ahren in that his selector will match all input elements whose name attribute contain the string 'Indian'.
indianInputs.attr("name");
Would return the first matched element's name attribute's value, which, for your markup will be Indian_Karnataka_Bangalore
To find the names of all indianInputs, you must iterate over all matched elements
var indianInputNames = [];
indianInputs.each(function() {
indianInputNames.push($(this).attr("name"));
});
$('input[name="element_name"]')
You have a lot of ways to select by the name of the attribute check http://api.jquery.com/category/selectors/attribute-selectors/
Try
var name = $('input[name^="Indian_"]').attr('name')
Have you tried the filter function? Something like this:
$('input:visible')
.filter(function() {
return $(this).attr("name").match(/^Indian/);
});
This will return an array of input elements whose name starts with "Indian".
There is a good example here: https://stackoverflow.com/a/193787/1237117.
Related
I recently saw a code voucher that surprised me a bit and I would really like to understand. Can the document.querySelector() take a parameter, an attribute to make selections :
const tabs = document.querySelectorAll('[data-tab-value]')
<span data-tab-value="#tab_1">Tab-1</span>
I would also like to know why the attribute name is enclosed in brackets.
document.querySelector is just like CSS selectors
It can even select elements with attributes like:
document.querySelector("input[name]") // <input name>; input which has attribute name
document.querySelector("input[type=number]") // <input type='number'>; input whose attribute type's value is number
I want to use JavaScript to find a specific HTML element by the number of characters in its id attribute.
For example if the element I want to find looks like this:
<element id="12345678"></element>
And has 8 characters in its id attribute, how would I find this element.
Some basic pseudo code I imagine would look like this:
[e] = document.GetElementById where id.charLength == 8
And this would return an array with all elements on the page whose id attribute is 8 characters long.
In case anyone asks, I cannot just use the id to get the element because the id changes with every page refresh. Xpath will not work either as the element changes its position in the DOM with every refresh. There are no constant identifying attributes of the element's parents either.
The only constant is the length of the id attribute of this specific element, and so I have concluded that this is the only way to grab the element.
You could use Document.querySelectorAll() with an attribute selector to find all elements on the page that have an id attribute (with any value) and then use Array.prototype.filter() (and Array.from()) to filter them according to their id's length:
console.log(Array.from(document.querySelectorAll('[id]'))
.filter(element => element.id.length === 3));
console.log(Array.from(document.querySelectorAll('[id]'))
.filter(element => element.id.length === 6));
<div></div>
<div id="123"></div>
<div id="456"></div>
<div id="123456"></div>
<div id="987654"></div>
Here is the solution in pure xpath.
//element[string-length(#id)=8]
Try Javascript: How to loop through ALL DOM elements on a page? to loop through all elements and then set your own criteria (for the id length) during that loop
You can do first get all the dom elements by using document.getElementsByTagName("*") and then use find to get the required dom element
const domElements = document.getElementsByTagName("*");
const required = [...domElements].find(element => element.id.length === 8);
In our rails app, dynamic fields can be added to the form. Here is a html source code for the dynamically added field order_order_items_attributes_1413563163040_unit_price:
<div class="input decimal required order_order_items_unit_price">
<label class="decimal required control-label" for="order_order_items_attributes_1413563163040_unit_price">
<abbr title="required">*</abbr>
Unit Price($)
</label>
<input id="order_order_items_attributes_1413563163040_unit_price" class="numeric decimal required span5 span5" type="number" step="any" name="order[order_items_attributes][1413563163040][unit_price]">
</div>
As you can see, there is 13 digits string in field's id and it is randomly generated when the field is added. How we can match (locate) this type of random id in javascript? rails app uses jquery (ex, $('#order_order_items_attributes_xxxxxxxxxxxxx_unit_price').change(function (){})).
We are new to this css type of id match. More detail would be appreciated.
You have to first decide what algorithm you're using for matching the id values. Based on your comments (it is not specified precistly in your question), it appears you want to find all ids that start with "order_order_items_attributes_" and end with "_unit_price" and have a sequence of digits between them.
You can do that like this by find all the ids that start with the thing you want and then filtering them to things that only match all three criteria:
// find ids that match this pattern: order_order_items_attributes_xxxxxxxxxxxxx_unit_price
var orderItemRegex = /^order_supplier_id_\d+_unit_price$/;
$("[id^='order_supplier_id_']").filter(function(index) {
return orderItemRegex.test(this.id);
}).change(function() {
// this will be only the ids that match
});
This uses jQuery to make a list of all objects that have an id that starts with "order_supplier_id_". It then filters through that list eliminating any objects who don't match the full regex /^order_supplier_id_\d+_unit_price$/ that defines your pattern and then hooks up the .change() event handler to only the objects that pass the regex test.
Have you tried
$("input").prop("id");
That'll search for your input field and find the id property.
Use the for attribute of your <label>:
var selector = $('.decimal.required.control-label').eq(0).attr('for'),
element = $('#'+selector);
console.log(element);
// [<input id="order_order_items_attributes_1413563163040_unit_price" ... >]
You can use an attribute selector to match an id that "contains" the specified value, using [attr*=value]. Like:
$("[id*='order_supplier_id']").change(function() {
});
MDN's docs on attribute selectors specifies the kinds of selectors you can use to match the attribute, among them:
[attr*=value]
Represents an element with an attribute name of attr and whose value contains at least one occurrence of string "value" as substring.
You could maintain an array of element IDs that gets updated each time the form element is added. Then call your change method on the elements in your array. But that isn't necessary if the change event callback is identical for all the new elements. Just call it on the class.
I am cloning some form elements and want to generate for them dynamic ids so I can acces their content later on, but I don't really know how to do that, I'm a noob with Jquery/Javascript, by the way.
My html:
<tr>
<td>
<label for="ability">Ability</label><br>
<div id="rank_ability" name="rank_ability">
<select name="ability" id="ability">
<option value=""></option>
<option value="hexa">Test</option>
</select><br>
<label for="range_ability_min">Range:</label>
<input type="textbox" name="range_ability_min" id="range_ability_min" class="small_text" value="0" /> -
<input type="textbox" mame="range_ability_max" id="range_ability_max" class="small_text" value="0" /><br>
</div>
Add Ability<br><br>
</td>
</tr>
My JS:
$(document).ready(function () {
var element, ele_nr, new_id;
$('.rank_clone').click( function() {
element = $(this).prev();
ele_nr = $('div[name="'+element.attr('name')+'"]').length;
new_id = element.attr('name') + ele_nr;
element.clone().attr('id', new_id).attr('name', new_id).insertAfter(element);
});
});
I setup a jsfiddle with what I got here: http://jsfiddle.net/xjoo4q96/
Now, I am using .prev() to select the element to clone which leads to those repeated 1 in the id/name attributes, how could I select it in another way (to mention: I really need to use 'this' because I need this little script in like 3 places, so I don't want to write it for an element with a specific id/class).
Also, I am counting only the element with the base name attribute so .lenght yelds 1 all the time, how would I go around counting all of them ? I guess I have to place them in another div or something but I don't know how would I go around couting them even then.
And, at last, how would I go around changing all the name/id attributes of the elements I have in the div ?
I'd appreciate any help. Thanks.
you can put the template in a hidden div like #tmpl, then clone and set the id attr, e.g.
$('#tmpl').children().first().clone().appendTo('#target').attr('id', 'the_generated_id');
Update
Demo of the template way: http://jsfiddle.net/xjoo4q96/1/, though it would be quite easy to adjust the code to clone the first component that already existed.
BTW, principally, id should be unique, thus the sub-element in the cloned component should use other attribute, like class or certain data- attribute, like those used in the updated fiddle.
Also you might want to call event.preventDefault() as you're clicking an <a>
You are searching already with the wrong name, since it still has the number attached. So delete it first, search for element which have a name attribute starting with this name and then use this base name to create a new one.
$(document).ready(function () {
var element, ele_nr, new_id, base_name;
$('.rank_clone').click( function() {
element = $(this).prev();
base_name = element.attr('name').replace(/[0-9]/g, '');
ele_nr = $('div[name^="'+base_name+'"]').length;
new_id = base_name + ele_nr;
element.clone().attr('id', new_id).attr('name', new_id).insertAfter(element);
});
});
And to answer your last question: you can not go around changing all ids of inner elements, it would be invalid HTML. In principal you can do the same with every id, like adding a number. If you have to do the same with all the name attributes depends on what you want to do exactly. If you have to distinguish between the first and second input, which I suggest, you have to change them too.
try to use cloneJs, it's clone ids, names input, and parametre inside functions ids of input must be like id_foo_1, id_foo_2 ,,,, and name be like inputName[0][foo], inputName[1][foo] https://github.com/yagami271/clonejs
I want to search through my document, and find all inputs with title attribute, but at the same the title attribute can not be empty. So it should look for every input with title attribute that has at least one character in length.
Then I would like to make some event on those inputs (like add them some CSS class).
Is that even possible with jQuery or other javascript library?
I believe this would give you what you want:
$('input[title][title!=""]')
To apply css
$('input[title][title!=""]').addClass('class1 class2 class3');
http://jsfiddle.net/5hkAG/
$("input[title]").not('[title=""]')
var myInputs = [];
$("input").each(function() {
if($(this).attr("title").length > 0) {
myInputs.push(this);
// do other events as usual, using $(this) as selector for current input
}
});
// do something with myInputs, which is an array of all inputs with a title attribute