jQuery not selecting id containing "<" angular bracket? - javascript

I am not able to select checkbox which has id="check stage<lead>" in jQuery Selector.
HTML:
<input id="check stage<lead>" type="checkbox" title="Select/Unselect Column" name="chk-stage-column-select" value="" onchange="">
Javascript:
// escape jquery selectors
function jQueryEscape(str) {
if (str)
return str.replace(/([ #;?%&,.+*<>~\':"!^$[\]()=>|\/#])/g, '\\$1');
return str;
}
var StageName = "<lead>";
$("[id='check stage" + jQueryEscape(StageName) + "']").prop("checked", true);
Equivalent JsFiddle : https://jsfiddle.net/vuw43uav/5/
Note: I'm using jQuery 1.7 and we can select id with spaces in jQuery. refer this jsFiddle: https://jsfiddle.net/vuw43uav/7/

I know you asked to make it work using jQuery Selector, but you can do it using javascript.
Just select the element using javascript and make it checked.
document.getElementById("check stage"+StageName).checked = true;
Here is the working fiddle for your 1.7 jquery version.
Fiddle
In case you want jquery selector, just select the element using javascript and then convert it to jquery selector, I know this is lame but should work fine for you.
var y = $(document.getElementById("check stage"+StageName));
y.prop("checked",true);

Id attribute must not have any space characters, check this spec
The value must be unique amongst all the IDs in the element's home
subtree and must contain at least one character. The value must not
contain any space characters.
There are no other restrictions on what form an ID can take; in
particular, IDs can consist of just digits, start with a digit, start
with an underscore, consist of just punctuation, etc.
use data-id instead
<input data-id="check stage<lead>" type="checkbox" title="Select/Unselect Column" name="chk-stage-column-select" value="" onchange="">
$("[data-id='check stage" + StageName + "']").prop("checked", true);
Demo

Related

Selecting value based on string in attribute

I'm working with the following bit of html and am trying to select it's value in either plain javascript or jquery. The name attribute can vary so I can't use it as my selector, although it will always represent the same data (grade_level). I think my best way of selecting it is via the string 'students.grade_level, but I'm not sure how to access it.
<input type="hidden" name="UF-001008-1$formatnumeric=#########.#####" value="1" data-validation="{"maxlength":"10","isinteger":"true","type":"number","key":"students.grade_level"}">
I have so far not been able to select element's value. I have tried:
var myvar = $( "input[data-validation~='students.grade_level']" ).val();
var myvar = $( "input:contains('students.grade_level')" ).val();
How else can I go about this?
TYIA
The way that you have given your attribute is wrong,
<input type="hidden" name="UF-001008-1$formatnumeric=#########.#####" value="1" data-validation="{'maxlength':'10','isinteger':'true','type':'number','key':'students.grade_level'}">
Use quotes properly to cover your attributes, either escape the double quote or use single quotes instead.
And after correcting that you could use the *= attibute value contains selector to achieve what you want,
var myvar = $( "input[data-validation*='students.grade_level']" ).val();
:contains() selector will not work out since it would search for matching text content. Also ~= attribute contains word selector wont work out as we do not have any word in our data-validation attribute. Word in the sense, group of texts separated by a space.
DEMO

Jquery [attribute] Selectors

So I've seen several posts explaining how to use a variable in a value for attribute selection. i.e. (where the JS event refers to the div (making it $(this):
HTML
<div id="item1"></div>
<div id="item1" style="display: none;"></div>
JS
var find = $(this).attr("id")
$('div[id="'+find+'"]').show();
But I would like to know how to use a variable in a jquery selector to find something with a similar string to the value of the variable. i.e. finding an element from the example above but looking for "#item1div", where the event target is still "#item1"
HTML
<div id="item1"></div>
<div id="item1div" style="display: none;"></div>
JS
var find = $(this).attr("id")
$('div[id="'+find+"div"'"]').show(); // incorrect syntax
So my question is: How do I correct the above syntax to include an additional string in the attribute check?
I can't find any reference to the correct syntax for how to add compile a string of the value of a variable and an explicit string then check that as the value for x attribute.
I know I can use [id*="'+find+'"] here because the alternate id contains the same characters as the basic one, but I want to know how to target a specific other id based on the first one. For example if I had #item1, #item1div, and #item1img, how can I use an event on "#item1" to find attribute values equal to "item1div" and/or "item1img"
EDIT: I also just realized I can just use [id|="'+find+'"] if I name the divs accordingly with hyphens, but again doesn't solve ids with different endings (or different strings that come after the hyphen)
$('div[id="'+find+"div"'"]') isn't valid Javascript syntax:
$( // jQuery function
'div[id="' // String
+ find // Add variable
+ "div" // Add String
'"]' // Unexpected string! - Error
One example of valid syntax would be:
$('div[id="'+find+'div"]')
However, since it's an id, you can use the id selector instead:
$('div#'+find+'div')
the question is very unclear, but I assume your question boils down to :
Q:how do you search all the elements where it starts with string x ?
A:To get all the elements starting with "item1" you should use:
$("[id^=item1]")
You should use ID selector like below to find an element by ID,
$('#' + find).show();
To find item1div or the dynamic first part - $('#' + find + 'div')
Note: the incorrect syntax you had mentioned is because of a missing + - It should be
// V-- you missed this
$('div[id="'+find+"div"+'"]').show();
To add the explicit string to the attr value you can write as follows
$('[attr="'+attrVal+'extraString"]')
For evample in case of id of div itemdiv
var item1ID = $('#item1').attr('id'); // item1
$('[id="'+item1ID+'div"]') // valid selector to select #item1div

How to match id in javascript for dynamically added field on html?

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.

Leading Zeros Getting Dropped Using jQuery

Using jQuery, I am copying a select into a ul for use in a mobile app. Some of the values in the select options have leading 0s. I'm using a custom attribute in the li elements to mimick the values in the select's options.
When I copy the value into the li:value, it loses the leading 0. I've even tried creating the whole li as a liter string that I append to the outer ul.
html:
<select id="seltest">
<option value="011111">good bye</option>
</select>
<div id="container"></div>
javascript:
$("#container").append("<ul id='thefilter'></ul>");
$("#seltest option").each(function () {
var optval = $(this).val();
var strvar = '<li value=\"' + String(optval) + '\">' + $(this).text() + '</li>';
alert(strvar);
$("#thefilter").append(strvar);
var lastli = $("#thefilter li:last");
alert(lastli[0].outerHTML); // now the value has lost the leading 0
});
Here's a fiddle to show an example: http://jsfiddle.net/richbuff/4RbH9/7/
Does anyone have an idea how to preserve the leading 0? It seems like jQuery is modifying my text.
TIA!
The browser is actually enforcing the spec. From the Mozilla Developer Network:
The only allowed value for this attribute is a number, even if the list is displayed with Roman numerals or letters.
In my handful of years of web development I've never used the value attribute on a list item. So, some of you might find this additional note of interest:
This attribute was deprecated in HTML4, but reintroduced in HTML5.
I'm using a custom attribute in the li elements
No, you aren't. There is a standard value attribute for LI elements.
I don't think this has anything to do with jQuery (other than it creates confusion between DOM properties and HTML attributes). In the following:
<ol>
<li value="06" onclick="alert(this.value)">Show value property
<li value="06" onclick="alert(this.getAttribute('value'))">Show value attribute
</ol>
both IE and Firefox return 6 for both alerts. The only difference is that in the first case, the value is type number and in the second type string (since getAttribute returns a string).
If you want to preserve the literal value, use a data- attribute on the LI.

jQuery Select # id with word as prefix and counter as suffix

Is there a way to select all id's with jQuery with a prefix "my" and a suffix "0-9".
Something like these $("#my$1-4") or is it just possible with a loop ?
<div id="my1"/>
<div id="my2"/>
<div id="my3"/>
<div id="my4"/>
<div id="my5"/>
First thoughts, which seems to work well:
$('div[id^="my"]').filter(
function(){
return this.id.match(/\d+$/);
});
JS Fiddle demo.
The above selects all div elements whose id starts with the value my, and then filters the returned elements to those whose id also ends with numeric characters.
References:
attribute-starts-with selector.
filter().
Regular Expressions, at Mozilla Developer Network.
The prefix part is easily achievable with an attribute starts-with selector:
$("div[id^=my]");
But there is no selector that will allow you to specify a range of characters, so a loop will have to be involved. I would suggest filter:
$("div").filter(function () {
return /^my\d$/.test(this.id);
});
Assuming you don't have millions of elements that start with "my", you could do:
$('[id^=my]').filter(function() { return this.id.matches(/\d/) && this.id.length == 3 })
This grabs all elements that have an id starting with "my", contain a number, and are only 3 characters long (so "my54" will not match but "my6" will)

Categories

Resources