jQuery each to find label for attr not working - javascript

I am getting an error and think i know why but not sure how to resolve it.... for example my for label / id is:
shipping_address[country] << i think because of the brackets []
and my JS is
$(document).ready(function() {
$("form :input").each(function(index, elem) {
var eId = $(elem).attr("id");
var label = null;
if (eId && (label = $(elem).parents("form").find("label[for="+eId+"]")).length == 1) {
$(elem).attr("placeholder", $(label).html());
$(label).remove();
}
});
});
Error:
js__jquery.js?1419646…:1468 Uncaught Error: Syntax error, unrecognized
expression: label[for=billing_address[first_name]]
Example HTML:
<div class="col-sm-6">
<div class="form-group">
<label for="card[first_name]">First Name<span> * </span></label>
<input id="card[first_name]" name="card[first_name]" type="text" class="form-control" value="" validate="true">
</div>
</div>

Wrap the attribute value within quotes or escape metacharacter since the id value contains some metacharacter which has special meaning in jQuery.
.find("label[for='" + eId + "']")
// -^-----------^-
From jQuery docs :
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?#[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \. For example, an element with id="foo.bar", can use the selector $("#foo\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.
FYI : Use text() method instead of html() method to get text content.
$(elem).attr("placeholder", $(label).text());
// ------^^^^^^---

Square brackets inside attribute selectors need to be escaped.
var eId = elem.id.replace(/[\[\]]/g, '\\$&');

Related

jQuery css selector match form array names

html
<input name="single">
<input name="multi[]">
<input name="multi[]">
<input name="multi_keys[my]">
<input name="multi_keys[key]">
jQuery
var match_single = $('[name="single"]');
var match_multi = $('[name="multi"]'); // No match
var match_multi_keys = $('[name="multi_keys"]'); // No match
console.log(match_single.length);
console.log(match_multi.length);
console.log(match_multi_keys.length);
It will only match match_single because the other selectors are not correct.
How can I make them match the form field arrays as well?
I could do this:
var match_multi = $('[name="multi[]"]');
but how can I match when there are keys inside and they are unknown? I would like to write it like this:
$('[name="multi_keys*');
You can use ^= which matches what an attribute starts with:
$('[name^="multi"]')
Note that this will match both name="multi[]" and name="multi_keys[]". If you wish to select multi[] and multi_keys[] separately, you can simply add the opening square bracket to that selector:
$('[name^="multi["]')
...and:
$('[name^="multi_keys["]')
[att^=val]
Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.
– W3C's Selectors specification
use the * before the = like this $('[name*="multi"]');
var match_single = $('[name="single"]');
var match_multi = $('[name*="multi"]'); // No match
var match_multi_keys = $('[name*="multi_keys"]'); // No match
console.log(match_single.length);
console.log(match_multi.length);
console.log(match_multi_keys.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="single">
<input name="multi[]">
<input name="multi[]">
<input name="multi_keys[my]">
<input name="multi_keys[key]">
You can query these inputs by matching the prefix of the input names, like $('[name^=multi_keys]') so it will pick up elements which' name starts with multi_keys . But it is quite hacky.

Migration from jquery1 to jquery 2 : selectors

I'm having troubles with selectors and brackets :
var myInputId = $(input).attr("id")
"value-5379-32433[]"
This is an input id for a checkbox list. I want to select now all the elements having this ID :
$("#" + myInputId);
Uncaught Error: Syntax error, unrecognized expression: #value-5379-32433[]
It works if I escape the brackets but I find this solution quite ugly as I have to use it in many places :
$("#" + inputId.replace("[", "\\[").replace("]", "\\]"))
Do you have a nicer solution to this problem ?
EDIT Note : This has to returns many elements as there is many checkboxes with this ID.
EDIT 2 : The html 3 elements I want to select :
<div class="type_mlist_check ">
<input type="checkbox" id="value-5379-32433[]" value="1" >
<input type="checkbox" id="value-5379-32433[]" value="2" >
<input type="hidden" id="value-5379-32433[]" value="-1">
</div>
Since selector contains meta character use attribute equals selector instead.
$('[id="' + myInputId + '"]');
Or use a single String#replace method with character class regex and global modifier.
$('# ' + myInputId.replace(/[#;?%&,.+*~\':"!^$[\]()=>|\/#]/g,'\\$&'))

ID with special characters with Jquery

I have a ID with special characters. I need to get the value of this input with JQUERY.
<input style="text-align:center; width:50px;" type="text" onKeyPress="jq(this.id);" value="5" id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG">
<script>
function jq(str) {
var id = str.replace(/[%#;&,\.\+\#*~':"!\^\$\[\]\(\)=>|\/\\]/g, '\\\\$&');
var value = $("#"+id).val();
alert(value);
}
</script>
I try with this, but i dont have response in the alert.
Help! please!
Normally you can use jQuery's escape sequence in a selector, \\, to escape special characters. However that won't work in this case as the id you have specified in the element is invalid as it contains spaces.
Due to that you will have to use the attribute selector in jQuery to retrieve it:
var $el = $('[id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG"]');
console.log($el.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="text-align: center; width: 50px;" type="text" onKeyPress="jq(this.id);" value="5" id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG">
A much better solution would be to fix the id of your elements before they are output in to the page to remove the spaces and special characters.
Get the answer from fiddle here
I have written in both javascript & jquery. There is an option fot trying // before every special character in ID, but that doesn't worked for me. So on the other way you can get the answer. Check & let me know.
$("#clickID").on('click', function(){
getVal = $(document.getElementById('adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG')).val();
console.log(getVal);
alert(getVal);
});
function jq(str) {
var element = document.getElementById("adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG");
var value = $(element).val();
alert(value);
}

How can I get input tags with title attributes that contain " "?

I have the following input tag in my dom and unable to add classes and/or ids:
<input type="radio" title=" ">
When I try
$('input[title=" "]')
or
$('input[title=" "]')
it does not return anything. Can I pull this based on that title?
Your selectors didn't work because you didn't use the proper symbol. The title attribute gets any html entities decoded, so is going to get decoded to the actual symbol   (ascii code 160). So that means the text isn't going to match it, neither will a regular space (ascii code 32).
On a Windows OS you can type ALT+0160 to get the symbol. On other OS you will need to find the equivalent key combo, or copy paste from a character map.
console.log( "Number of inputs with regular space: ", $('input[title=" "]').length );
console.log( "Number of inputs with text: ", $('input[title=" "]').length );
console.log( "Number of inputs with symbol: ", $('input[title=" "]').length );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Regular space in title -->
<input type="checkbox" title=" ">
<!-- non-break space html entity -->
<input type="checkbox" title=" ">
<!-- encoded html entity which will match -->
<input type="checkbox" title="&nbsp;">
Would it suffice to select all non-blank title attributes?
$('input:not([title=""])').click(function(){
alert('non-blank title');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" title=" " />
This should work:
var isFound = $('[title=" "]').length === 1;
if (isFound) console.log('Element is found.');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div title=" "></div>
This subtle difference is to put an actual not a space character into selector.
It's a bit unwieldy can try a function to return the value of the title attribute and use that. If you are using this in a normal page, you can swap getTitle parameter below for a more specific selector like ID.
function getTitle(selector) {
return $(selector).attr('title');
}
$('input[title=' + getTitle('input[type="radio"]') + ']');
Use the following trick with JQuery's filter() function and RegExp.test function to get input tags with title attributes that contain :
var inputs = $("input[title]").filter(function(i){
return /\u00A0/.test($(this).attr('title'));
});
$("input[title*=' ']");
To get input elements with title attributes that contains a "regular" space use the following:
The [attribute*=value] selector matches every element whose attribute
value containing a specified value.

Check pattern in javascript

I Have next pattern:
[a-z[A-Z]а-я[А-Я][0-9]їЇіІєЄ[-][,]_"/\ ]{0,483}
<input
id="<?= $field['id'];?>"
name="input"
<?php if (isset($field['regex'])) echo "pattern=".$field['regex'];?>
>
By this pattern I check data in field by javascript:
var decode_pattern = $(this).attr('pattern');
var reg = RegExp("^" + decode_pattern + "$");
But when i try to input (sdfzsdf) in field, regexp tell me - wrong.
Why?
I Have this pattern: [a-z[A-Z]а-я[А-Я][0-9]їЇіІєЄ[-][,]_"/\ ]{0,483}
JavaScript Regex syntax does't allow character classes in character classes. Maybe you meant
[a-zA-Zа-яА-Я0-9їЇіІєЄ,_"/\\ -]{0,483}
Your current regex is equivalent to /[a-z\[A-Z]а-я[А-Я]\dїЇіІєЄ-,_"\/ \]{0,483}/.
Also, since it contains a quote you will need to html-escape your attribute value:
echo 'pattern="'.htmlspecialchars($field['regex']).'"';

Categories