From an open code I have this line
var average = parseFloat($(this).attr('id').split('_')[0]),
It gets the first part of a div id with '_' as delimiter. The problem is that an id cannot start with a number (naming violation convention). So I am going to add a letter before the id value in my php script. How do I insert substr(1) to this var to remove this letter and get 'average' as expected?
Assuming you're talking about this format for an id:
<div id="A1000_bc"></div>
You can insert the substr(1) like this:
var average = parseFloat(this.id.split('_')[0].substr(1));
I might prefer to do it like this so it's a little less presumptious about the exact format and just grabs the first floating point numeric sequence:
var average = parseFloat(this.id.match(/[\d\.\+\-]+/)[0]);
Also, notice how I removed the jQuery. $(this).attr("id") performs a lot worse than this.id and offers no advantages here. jQuery should be used only when it's actually better than plain JS.
Both of these methods assume you are only going to present the code with properly formatted ids. If you want to handle a default condition when the id is not in the right format, then you will need multiple lines of code with some if conditions to check for validity and offer a default result when not valid.
Both options work here: http://jsfiddle.net/jfriend00/B4Rga/
Incidentally, if you control the HTML here, then there are better places to put data like this than in an id. I'd suggest a custom data attribute (HTML5 standard, but works everywhere).
<div id="whatever" data-avg="3.5"></div>
Then, you can get the data like this without having to parse it:
var average = parseFloat(this.getAttribute("data-avg"));
var average = parseFloat(
$(this) // you've got a jQuery object here - bad place
.attr('id') // you've got a string here - why not
.split('_') // you've got an array here - bad idea
[0] // you've got a string here - why not
// you need to have a number string here
);
Remeber: substr(1) can only be called on Strings.
Related
I have the following html Input element:
<input size=6 type="text" id="prd_price" title="prd_price" name="prd_price" >
I want Currency Symbol ман for "Azerbaijani manat
" to be saved in the database. I would like to populate this as the symbol inside HTML Input element and perhaps concatenate with the price of a product. But when I populate the Input Element dynamically with the UTF-8 Code, it remains in the code form and does not become the Currency Symbol it is suppose to become.
Anyone knows what am I missing here...
The UTF-8 encoding can represent the complete Unicode catalogue (in fact, the letter U in the acronym comes from Unicode) so you don't need HTML entities in the first place. Such entities are only necessary if have characters that your current encoding cannot handle, which isn't the case here.
If you absolutely need to use those HTML entities (e.g., you consume a third-party data feed you cannot tweak) you need to realise that they only make sense in HTML context. A fairly common error in jQuery is to use .text() where you should really be using .html().
In this precise situation you have an <input> element so you cannot use either. Your only choice is .val(). However, since an <input> cannot contain HTML at all everything you feed .val() with will be eventually handled as plain text.
A little trick you can use is to create a detached node so you can use .html() to populate it with HTML and .text() to extract the plain text representation:
var $input = $("#prd_price");
// Original string "м ;а ;н ;" fixed:
var symbols = "ман"
var plainText = $("<span></span>").html(symbols).text()
$input.val(plainText);
... will render as:
ман
Demo
First of all I got the UTF-8 Code for Azerbaijani manat ман which is able to be run in javascript from "https://r12a.github.io/apps/conversion/". In this case it came up to be \u043C\u0430\u043D. Then I ran it up with the following code to get it display inside the input element using javascript:
var x = "\u043C\u0430\u043D";
var r = /\\u([\d\w]{4})/gi;
x = x.replace(r, function (match, grp) {
return String.fromCharCode(parseInt(grp, 16)); } );
x = unescape(x);
console.log(x);
I have the following string :-
http://myapp.local/myapp/shop/products/admin/ShopProducts%5Bproduct_name%5D//ShopProducts%5BemailNotification%5D//ShopProducts%5Bemail_user%5D//ShopProducts%5Bactive%5D//ShopProducts%5Binstant_win%5D//ShopProducts%5Bmulti_buy%5D//ShopProducts%5Bprice%5D//ShopProducts%5Bquantity%5D//ShopProducts_page/2/ajax/shopproducts-grid
I only want to grab the last section as so on.. not this is a part of pager (needs some weird custom hack) and the page number in this case is 2 but could 2,3,4, 500...
ShopProducts_page/2/ajax/shopproducts-grid
What is the easiest way to do this using vanilla js or jquery or a structured way to grab the parts into some of an array that I'll be able to manipulate?
If there will always be double forward-slashes // in the path, you can simply do this:
//Where string is already defined to be the path
var sections = string.split('//');
var lastSection = sections[sections.length-1];
I have a element like this
<div class="th-class2 th-hhjjsd th-context-78474378437834873"></div>
(Note: I know class names should not be pure numbers)
I want to get the numerical number from this div.
id = 78474378437834873
Is there a way I can use regular expressions to do it. I am nearly there but it only returns the first 4 numbers.
I use a clickevent to target the div and try and get the class like this
var classString = $(this).prop("class").match(/([0-9]+)/)[1];;
console.log(classString)
result is 7847
I am just not understanding how to get the rest of the number.
Thanks
You shouldn't use integers for class names because using a class typically means you are going to use the element more the once and adding a dynamic number defeats the purpose of classes, also working with someone else code and they use integers it's very hard to understand their code. As far as your questions goes, you shouldn't really use regular expressions to get a value of a class you should either store the value as an id so your element would look like this,
HTML
<div id="78474378437834873" class="th-class2 th-hhjjsd"></div>
or you could use a data object which is how I would do it like so,
HTML
<div class="th-class2 th-hhjjsd" data-object='{"value":78474378437834873}'></div>
and then when you select your element with your click event to get the value of the element you clicked console log the elements data object like so
jQuery
$('.th-class2').click(function() {
console.log($(this).data('object').value);
});
You should not use number only class names, they must start with an Alpha character [a-Z]
You can find what are the allowed characters in this discussion: Which characters are valid in CSS class names/selectors?
(Please make sure to read also the comments).
As per a solution for you,
The easy solution would be to use data attributes as so:
<div data-id="1000"></div>
and then you could get your id as simple as:
$(this).on('click', function() { console.log($(this).data('id')); } );
Happy Coding.
Very quick and hopefully simple question.
I am trying to select a hidden input by value with some predefined variable.
var id = $("#puid").val();
$('input[value=id]').closest('tr').css({'background-color':'red'});
I thought the above code would have worked, however its not processing id as a variable. What is the right notation to do this? (I have tested the code by replacing id with the actual number and the rest of the code works fine).
remove it from the quotes, so the variable is concatenated into the string. They way you have it, it's looking for the literal value "id", and has no way of knowing that you're talking about a variable.
$('input[value='+id+']')
edit: more info - you could put double quotes around the id part, inside the strings, as in Nick's answer, which would make it safe to use with non-numeric ids. I omitted them since your example doesn't need them, as you said your ids are numeric.
Concatenate the string selector with the variable, like this:
var id = $("#puid").val();
$('input[value="' + id + '"]').closest('tr').css({'background-color':'red'});
Currently, it's looking exactly for this: value="id", but you want your variable there.
I have a javascript function that changes a user preference, if they want weights to be metric or in imperial.
On my page I print out the weight, IE:
This is some description:
This product weights <b>200 KG</b>
Blah blah
I need to make it so that Javascript changes the weight measurement for all weights on the page, and am not sure the best way to tackle this. Can you create your own tags, or tag properties?
Thanks for any suggestions, JQuery is fine.
I'd recommend using strong rather than b, but the below will work for either of them.
Edit: Better solution than using a class, with working example, below.
Tag the weights with a class, e.g.:
This product weighs <strong class='weight'>200 KG</strong>
Then in your JavaScript, you can switch like so:
$('.weight').each(function() {
var $this = $(this);
var original = $this.text();
var converted = /* ...convert the weight here... */;
$this.text(converted);
});
Obviously you can condense that a bit, kept it verbose for clarity.
Better solution:
Tag the elements with the original weight (the one you store in your database) as a data-weight attribute, e.g.:
This product weighs <strong data-weight='200'>200 KG</strong>
Then convert from that value:
$('[data-weight]').each(function() {
var $this = $(this);
var value = $this.attr("data-weight");
if (usingMetric) {
$this.text(value + " KG");
}
else {
value = parseFloat(value) * 2.20462262; // Convert to imperial
$this.text(value.toFixed(2) + " lbs");
}
});
Working example: http://jsbin.com/icure3
Attributes in the form data-xyz will pass validation as of HTML5; prior to HTML5 they are technically invalid, but harmless. But if you prefer a version that doesn't use data-weight, you can do it with classes instead: http://jsbin.com/icure3/2 (inspired by Reigel's answer to Tom's other question).
If you see a delay when switching between metric and imperial on slower browsers (I'm looking at you, Microsoft), you can help jQuery's selector engine optimize by giving it more context than just "[data-weight]". jQuery's engine supports nearly all of CSS3. For instance, if you always use the data-weight attribute only one one kind of tag (say, strong tags), change the selector to "strong[data-weight]" so the selector engine knows it can optimize for just one specific tag name. Similarly, if all of these are inside some container (e.g., a div with the ID "productList" for instance), you can help the engine out even more ("#productList strong[data-weight]") so it can ignore anything outside that div. I've kept it completely general above. But probably only bother if the page is big and complex enough that you see a performance issue.
Final thought: To throw a bone to browsers with JavaScript disabled, you might include both values in a title attribute as well, e.g.:
This product weighs <strong title='200 KG / 441 lbs' data-weight='200'>200 KG</strong>
...so it shows up as a tooltip on browsers that do that. I included that in the example above.
I would add a class .weight and use this to target all the weights..
$('.weight').each(function(){...})
If you want to change the innerHTML you can use the html() method directly
$('.weight').html(function(idx, oldhtml){
// you can use the oldhtml to extract info and create the new text here..
$(this).html( ../*you new html here*/.. ); // replace existing with new html ..
})
HTML:
<b class="weight">200 KG</b>
Javascript:
$("#UnitChangeButton").click(function() {
$('.weight').each(function(){
txt = $(this).text();
newTxt = convert(txt);
$(this).text(newTxt);
});
});
You need to implement the convert function. You can store the state (metric or imperial) in a javascript variable.