Can't change span content - javascript

I've got this span:
<span id="inicial"></span>
and this javascript inside a button click:
var pat = /\/\S+\//i;
context = '';
context = $('#cmd').attr('value');
context= context.match(pat);
alert(context); //this gives correctly the string i need
if (context.length){
$('#inicial').text(context); //but it fails to change the text inside the span
}
What could be the problem?
Also i noticed that it affects the whole click function, it just stops working. What could possibly be the cause?

The problem is that .match() returns an array, not a string. But .text(parm) requires parm to be a string.
So after the .match(), you should do something like:
context = context[0];
or use some other methodology to convert at least the first element in the array to a string, if not the full array.
Here's the reference for .match(): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match
And the ref for .text(parm): http://api.jquery.com/text/

try -- edited as per #Jonathan M
answer
$('#inicial').html(context[0]);

Related

How to change split sign from html element with jQuery

I have some h3 element:
<h3>Data Performance</h3>
I need to change it to class name: data_performance.
So i do this but something is wrong, can anybody tell me what?
var $product_name = $('.subpage_promo.top').find('h3').text().toLowerCase(),
$product_name_mod = $product_name.split(' ').replace('_');
Thx for help.
You can do this using below code.
var $product_name = $('h3').html().toLowerCase(),
$product_name_mod = $product_name.replace(' ','_');
Demo
You're not implementing replace correctly. Its syntax is:
str.replace(regexp|substr, newSubStr|function)
It should be executed on a string (you're passing an array of strings), and it should specify both what to search for and what to replace it with (you're currently passing only what should be the second argument):
$product_name_mod = $product_name.replace(/ /g,'_');
The code above uses a regex, only to be able to specify the global flag, which is required in order to replace every space with an underscore. If you know you'll always have just one, .replace(' ','_') should do.
$('h3').addClass(product_name.replace(/ /g,'_'));
DEMO

Add special character at end of input fields string, jquery automatically adding comma

I am adding % symbol at the end of the string on keyup event, first I get the current value of input field and then split('%') and then I use following code
$('.percent input[type=text]').val(str+'%');
But this also adding comma after newly added character.
jsfiddle
Also Would love to do it by using css but the condition is only that there should not be any image used for it neither positioning used.(Can I use :after or :befor)
IMO the problem was the split function.
Try this:
$('.percent input[type=text]').on('keyup',function(){
var oldstr=$('.percent input[type=text]').val();
var str=oldstr.replace('%','');
$('.percent input[type=text]').val(str+'%');
});
Javascript .split() method returns comma seperated data, that is why your data is comma seperated.
If all you wish to do is remove the first symbol you could use .substr() - read about it here.
$('.percent input[type=text]').on('keyup',function(e){
var oldstr=$('.percent input[type=text]').val();
var tokens = oldstr.split('%');
var suffix = tokens.pop() + '%';
var prefix = tokens.join("");
$('.percent input[type=text]').val(prefix+suffix);
});
JS Fiddle: http://jsfiddle.net/uU8Lf/4/
A little late now, however I couldn't help but notice the constant reuse of the element's class/type throughout both answers. Is it not beneficial/best practice to use 'this' keyword within the '.on' callback function like so:
$('.percent input[type=text]').on('keyup',function(){
var oldstr=$(this).val();
var str=oldstr.replace('%','');
$(this).val(str+'%');
});
Please correct me if I'm wrong, and yes, I'm being picky here :)

Extracting values from Array with Javascript

I am having issues with getting exactly values with Javascript.
Following is working version of when we have class on single item.
http://jsfiddle.net/rtnNd/
Actually when code block has more items with same class (see this: http://jsfiddle.net/rtnNd/3), it picks up only the first item which use the class name.
My issue is that I would like to pick up only the last item which use the class name. So I used following code:
var item = $('.itemAnchor')[6];
var href = $($('.hidden_elem')[1].innerHTML.replace('<!--', '').replace('-->', '')).find(item).attr('href');
But it doesn't work though. I don't really know why.
The code that may contains items are using same class, class may be use in 2 items, 3 items, or 6th times. That's why, I want to pick up only the last item to extract.
Can you explain, thank you all for reading my question.
"My issue is that I would like to pick up only the last item which use the class name."
OK, so in a general sense you would use the .last() method:
var lastItem = $('.itemAnchor').last();
Except that there are no elements in the DOM with that class because (in your fiddles) they're all commented out. This is also the reason why the code you showed in your question didn't work. The first line:
var item = $('.itemAnchor')[6];
...sets the item variable to undefined. The selector '.itemAnchor' returns no elements, so $('.itemAnchor') is an empty jQuery object and it has no element at index 6.
You need to use the '.itemAnchor' selector on the html that you get after removing the opening and closing comments with your .replace() statements, so:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor').last().attr('href');
Demo: http://jsfiddle.net/rtnNd/4/
EDIT in response to comment:
"How can we pick up the itemElement before that last one."
If you know you always want the second-last item use .slice(-2,-1) instead of .last(), as shown here: http://jsfiddle.net/rtnNd/5/
Or if you know you want whichever one has an href that contains a parameter h= then you can use a selector like '.itemAnchor[href*="h="]' with .find(), in which case you don't need .last() or .slice():
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor[href*="h="]').attr('href');
Demo: http://jsfiddle.net/rtnNd/6/
Note though that this last method using the attribute-contains selector is picking up elements where the href has the text "h=" anywhere, so it works for your case but would also pick up hh=something or math=easy or whatever. You could avoid this and test for just h= as follows:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor')
.filter(function() {
return /(\?|&)h=/.test(this.href);
}).attr('href');
Demo: http://jsfiddle.net/rtnNd/7/

Trying to reduce repetition of javascript using a variable

I am trying to reduce the repetition in my code but not having any luck. I reduced the code down to its simplest functionality to try and get it to work.
The idea is to take the last two letters of an id name, as those letters are the same as a previously declared variable and use it to refer to the old variable.
I used the alert to test whether I was getting the right output and the alert window pops up saying "E1". So I am not really sure why it wont work when I try and use it.
E1 = new Audio('audio/E1.ogg');
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
fileName.play();
$('#note' + fileName).addClass('active');
});
The code block works when I use the original variable E1 instead of fileName. I want to use fileName because I am hoping to have this function work for multiple elements on click, instead of having it repeated for each element.
How can I make this work? What am I missing?
Thanks.
fileName is still a string. JavaScript does not know that you want to use the variable with the same name. You are calling the play() method on a string, which of course does not exist (hence you get an error).
Suggestion:
Store your objects in a table:
var files = {
E1: new Audio('audio/E1.ogg')
};
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
files[fileName].play();
$('#note' + fileName).addClass('active');
});
Another suggestion:
Instead of using the ID to hold information about the file, consider using HTML5 data attributes:
<div id="#note" data-filename="E1">Something</div>
Then you can get the name with:
var filename = $('#note').data('filename');
This makes your code more flexible. You are not dependent on giving the elements an ID in a specific format.

Why is my .data() function returning [ instead of the first value of my array?

I want to pass an array into a jQuery data attribute on the server side and then retrieve it like so:
var stuff = $('div').data('stuff');
alert(stuff[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<div data-stuff="['a','b','c']"></div>
Why does this appear to alert '[' and not 'a' (see JSFiddle link)
JSFiddle Link: http://jsfiddle.net/ktw4v/3/
It's treating your variable as a string, the zeroth element of which is [.
This is happening because your string is not valid JSON, which should use double-quotes as a string delimiter instead of single quotes. You'll then have to use single-quotes to delimit the entire attribute value.
If you fix your quotation marks your original code works (see http://jsfiddle.net/ktw4v/12/)
<div data-stuff='["a","b","c"]'> </div>
var stuff = $('div').data('stuff');
When jQuery sees valid JSON in a data attribute it will automatically unpack it for you.
Declaring it as an attribute means that it is a string.
So stuff[0] would be equivalent to: var myString = "['a','b','c']"; alert(myString[0]);
You need to make it look like this:
<div data-stuff="a,b,c"></div>
var stuff = $('div').data('stuff').split(',');
alert(stuff[0]);
Retraction: jQuery's parsing fails because it didn't meet the rules of parseJSON.
However, I will stand behind my solution. There are aspects of the others that are less than ideal, just as this solution is less than ideal in some ways. All depends on what your paradigms are.
As others have identified the value is treated as string so it is returning "[". Please try this (aaa is the name of the div and I took out the data-stuff):
$(function(){
$.data($("#aaa")[0],"stuff",{"aa":['a','b','c']});
var stuff = $.data($("#aaa")[0],"stuff").aa;
alert(stuff[0]); //returns "a"
});
A different approach is posted at jsfiddle; var stuff = $('div').data('stuff'); stuff is a string with 0th character as '['
Well, var stuff = eval($('div').data('stuff')); should get you an array

Categories