I'm trying to wrap up my script placeholderRX. All I need to do is get the 'px' off the end of the string returned from this call.
$(form).children('.inputSpan').each(function() {
var $input = $(this)
var $padding = $input.children('.input').css('padding-left');
});
This returns "6px". I want to trim the 6 px off and make sure it's an integer so I can then add 2 pixels to it and feed it to the css rule. I'm new to string manipulations in javascript. Help me out!
You can use a basic javascript replace(), parseInt(), or parseFloat() function to remove "px" from your result. Which method you use, depends on what exactly you need.
The following is a shortened version of your code using parse replace() to remove "px".
$(form).children('.inputSpan').each(function() {
var padding = $(this).children('.input').css('padding-left').replace("px", "");
});
In the above code, "16px" will return "16". "16.7px" will return "16.7px". "16em" will return "16em".
The following is a shortened version of your code using parse parseInt() to remove "px" and more.
$(form).children('.inputSpan').each(function() {
var padding = parseInt($(this).children('.input').css('padding-left'));
});
In the above code, "16px" will return "16". "16.7px" will return "16". "16em" will return "16". As opposed to the first replace() example, this will remove any text, not just "px".
The following is a shortened version of your code using parse parseDouble() to remove "px" and more.
$(form).children('.inputSpan').each(function() {
var padding = parseDouble($(this).children('.input').css('padding-left'));
});
In the above code, "16px" will return "16". "16.7px" will return "16.7". "16em" will return "16". As opposed to parseInt(), this keeps decimals, if you have them for some reason.
Of course, you can keep the code lengthy if there is a reason to see the broken up steps taken for future reference, or if the other variables are used for other reasons. This is the long version using parseInt().
$(form).children('.inputSpan').each(function() {
var $input = $(this)
var padding = $input.children('.input').css('padding-left');
var paddingInt = parseInt(padding);
});
Also, to explain the change in the variable name from $padding to padding. A $ symbol in front of a javascript variable is common usage to distinguish regular javascript variables from jQuery variables, as they have different properties. There is no reason to use $padding because .css() does not return a jQuery object, but rather just a simple string.
In addition, for more complicated searches, you can research regular expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With