Making a variable I can manipulate further - javascript

I'm relatively new to jQuery and need to perform some transformations on the following working code:
jQuery('#vari_1').click(function() {
var selected = [];
jQuery('#cartsnitch')
.addClass('new')
.html(jQuery('#vari_1')
.find('input[type="radio"]:checked')
.val())
.fadeIn('5000');
})
The code returns the value of a radio button clicked in a tab id of #vari_1.
The problem is I then need to replace hyphens of the radio button value with spaces (duck-egg-blue to duck egg blue) and prepend an h2 heading. Chaining these appears to break my code.
I instead tried the below to make it into a variable so I can work with that on a new line, but couldn't get it to work. Can someone point me in the right direction please?
jQuery('#vari_1').click(function() {
var selected = [];
var cart1 = jQuery('#cartsnitch')
.addClass('new')
.html(jQuery('#vari_1')
.find('input[type="radio"]:checked')
.val())
.fadeIn('5000');
var cart2 = ('<h2>My heading</h2>') + cart1;
return cart2;
})
It's driving me nuts! Thanks in advance.

It sure can seem daunting Utkanos, I'm yet to get a straight answer to a question after being a member for a good few years. All I seem to attract is ambiguity and politician style question dodging!
Anyway due to lack of a hint other than Ashkay's syntax error spot (not in my code sorry), I fixed it as such:
jQuery('#vari_1').click(function() {
var selected = [];
jQuery('#cartsnitch').addClass('new')
.html(jQuery('#vari_1')
.find('input[type="radio"]:checked')
.val().replace("-"," "))
.prepend('<div class="mystyle"><small>My Label:</small><br />')
.append('</div>')
.fadeIn('5000');
})
val().replace() prepend() and append() were all I was after.
Thanks for the reassurance anyway!

Related

JavaScript delete-function does not work (absolute Newbie)

First off: sorry for that awful Code. I am an absolute beginner and this is my very first JS code ever and I had to code it under time-pressure (not good).
The task was to code a guest book. I have a function that creates a new div per entry and appends it to the last one (this part works well).
var lastid = 2;
function eintragen() {
...
var divC = document.createElement('div');
var ident='item'+lastid;
divC.innerHTML = '<table id="'+ident+'" class="eintrag center">
<tr><td>Name:</td><td>'+name2+'</td></tr><tr>
<td>Email:</td><td>'+email2+'</td></tr>
<tr><td>Eintrag</td><td>'+nachricht2+'</td></tr>
<tr><td></td><td><button class="buttonklein"value="loeschen"
***onclick="loeschen('+ident+')"***
>Eintrag löschen</button></td></t></table><hr>';
**divC.setAttribute('id',ident);**
var add = document.getElementById('item1');
add.appendChild(divC);
lastid+=1;
...
}
I tried do highlight the relevant part. As you can see, I gave the id to the divC twice, because after testing, I figured out, that it did not work in the "divC.innerHTML"-segment.
Every entry has an own delete-button, which should - you guess it - delete that associated entry.After clicking the button, the function starts, but then nothing happens.
function loeschen(itemid) {
var sitem = document.getElementById(itemid);
sitem.parentNode.removeChild(sitem);
}
I guess, since assigning the ID to the divC did not work in the "divC.innerHTML" part, it also does not work to assign it as a parameter to the "onclick" -attribute.
If I replace itemid with something concrete like 'item4' in the loeschen-function, it does delete entry number 4, so I guess the mistake is in the divc.innerHTML-part.
Question: Where did I go wrong? Any wrong '' oder ""? How can i give every button the current itemid? everything worked fine for the other variables like name oder email, so I have absolutely no clue.
Thanks so much in advance and sorry for my bad style. I will work on this in the future.
User Teemu found the answer super fast and was a great help.
It was indeed bad syntax in the divC.innerHTML-segment.
This does the job:
divC.innerHTML = `<table id="${ident}" class="eintrag center">
<tr><td>Name:</td><td>${name2}</td></tr><tr>
<td>Email:</td><td>'+email2+'</td></tr>
<tr><td>Eintrag</td><td>${nachricht2}</td></tr>
<tr><td></td><td><button class="buttonklein" value="loeschen"
onclick="loeschen('${ident}')">Eintrag löschen</button>
</td></t></table><hr>`;

How to select something from a textarea. Creating my editor

I've been searching for a few hours, trying with so many different solutions but anything works for me.
I'm building my own text editor in jQuery, but now I'm facing a problem:
I have this code right now:
function bbcode() {
var div = document.querySelector('textarea');
var start = div.selectionStart;
var finish = div.selectionEnd;
var text = div.value.substring(start, finish);
div.value('[b]' + text + '[/b]');
}
And this too:
$('#bold').click(function(evt) { bbcode(); });
#bold is a button and I want that when I click, it adds me the first part of the bbcode ([b]), the text I've already selected and the last part of the bbcode.
But it doesn't work for me. Where's the problem?
Thanks for reading and helping.
PD: I hope I have explained well.
Cheers.
You are assigning it wrongly. value is not a function which accepts parameter. It is instead a property which can be assigned to.
div.value = '[b]' + text + '[/b]'; // setter
DEMO

Find any form element

I am trying to find if a class exists and if not just find the first form element. How do I write :input? This does not seem to work.
$('.focus:not(:hidden):first, :input:not(:hidden):first').focus();
Comma-separated selectors are not hierarchical in the manner you seem to indicate. Your selector will yield the first visible .focus and the first visible input element. You'll need to break this up in two selectors:
var focusElement = $('.focus:visible:first');
if(focusElement.length == 0)
focusElement = $(':input:visible:first');
focusElement.focus();
Or I suppose you could write
$('.focus:visible:first, body:not(:has(.focus:visible)) :input:visible:first').focus();
Your code actually worked for me. Take a look at this jsfiddle. Try removing my class='focus' and it then falls back to selecting the first input field.
I would go for the easy to understand model:
var finder = $('.focus:not(:hidden):first');
finder = finder.length ? finder: $(':input:not(:hidden):first');
finder.focus();
Same result, but likely better given the right to left sizzle re: performance
var finder = $('.focus').not(':hidden').eq(0);
finder = finder.length ? finder: $(':input').not(':hidden').eq(0);
finder.focus();

Select label from document without knowing id

I've been working on the modification of an iframe using javascript. The iframe contains this form
What I want to be able to do is retrieve information from the label; however it doesn't have an ID. is there any way I could get javascript to get the input button by ID, and have it analyze the label assigned to it?
You could go through all label elements and find the one whose for attribute matches your button ID:
var labels = document.getElementsByTagName('label');
var label = null;
var buttonID = '...';
for (var i = 0; i < labels.length; i++)
if (labels[i].htmlFor == buttonID) {
label = labels[i];
break;
}
// "label" now refers to the label you're looking for
casablanca's way is the best way if you only know the button ID.
Depending on what else you might know, other things might be quicker. If, for instance, you know that it is inside a DIV that you know the ID of, and you know that it is the only label inside that DIV, then you could do something like
var label = document.getElementById('myDiv').getElementsByTagName('label')[0];
If you know that it'll always be the only label with the same parent as your button, you could write
var label = document.getElementById('button').parentNode.getelementsByTagName('label')[0];
Basically, a broad set of solutions might be optimal depending on what assumptions you can afford to make. If you only know what you've told us in the question, then casablanca's iteration is the way to go.
I highly recommend investigating jQuery for this sort of manipulation. I'm sure that you probably don't want to introduce a whole Javascript framework to solve this one little issue, but if you learn it you will find that Javascript programming becomes much easier.
Assuming that #casablanca's answer is correct, you could accomplish the same thing in jQuery with the following code:
var label = $('label[for="..."]').get(0);
(Or something like that. My syntax may be off. :-)

how to capture the mouseover element?

i am developing an autocomplete feature.but i am facing one problem there...
when i click on the suggestion box one of the results will not enter into the suggest html box...
function handleOnMouseOver(oTr)
{
deselectAll();
oTr.className ="highlightrow";
position = oTr.id.substring(2, oTr.id.length);
updateKeywordValue(position);
}
can you plz tell the solution
thanks
function updateKeywordValue(oTr)
{
var oKeyword = document.getElementById("keyword");
var strKeyword="";
var crtLink = document.getElementById("a" +oTr.id.substring(2,oTr.id.length)).toString();
crtLink = crtLink.replace("-", "_");
crtLink = crtLink.substring(0, crtLink.length);
oKeyword.value=unescape(crtLink.substring(googleurl.length, crtLink.length));
strKeyword=oKeyword.value.toString();
if (oTr.id.substring(2,oTr.id.length)==0)
{
oKeyword.value=strKeyword.substring(3,strKeyword.length);
}
selectedKeyword=oKeyword.value;
}
you should get rid of the second parameter in the substring() method. Since you just want the remainder of the string, I'm guessing, that is the default if you don't set a second value.
position = oTr.id.substring(2);
My guess is that you are getting the value of the keyword from the id, and pushing that into the input box, right? If that's the case, we'll need to see more of your code. Specifically, I'd like to see the updateKeywordValue function and I'd also like to know if the text that they are hovering over is the text you are trying to send the input box. If so, you could probably simplify the whole thing and go with something like:
function handleOnMouseOver(oTr)
{
deselectAll();
oTr.className ="highlightrow";
keywordbox.value = oTr.innerHTML;
}
But this is based on the assumption that the only data inside the hovered row is the text, and no other html. And I had to make up a name for your input box.
But if this way off, this is because we need more information to see the real problem.

Categories