Text not changing in jQuery - javascript

I seem to be doing something wrong in the following code: http://jsfiddle.net/yunowork/qKj6b/1/
When you click next, the text within the span .hiddentext should be displayed in the span .showtext on top and correspond to the right Race (Rn). For example when R3 is highlighted the content of that .hiddentext "Race 3Oregon 14:30" should be displayed within the span .showtext.
This is the line where I make a mistake:
$('.showtext').text($('.hiddentext').first('td:first').text());
What am I doing wrong here?

Let's start simple:
Your problem:
$('.showtext').text($('.hiddentext').first('td:first').text());
you are saing, that, grab all .hiddentext, choose the first that has a td ... witch is not what you have in code, you have, td that contains hiddentext... so, the other way around.
What you want to do is simply get the current NEXT td and grab the hiddentext, so, just change to:
$('.showtext').text($nextCol.find('.hiddentext').text());
Now, can you see that the <br/> is not correctly rendered? That's because you are setting the text property, and you should set the html property.
the final code should be something like:
$('.showtext').html($nextCol.find('.hiddentext').html());
live example: http://jsfiddle.net/qKj6b/8/
Your code:
every time you need to have placeholders to provide some data to a context, please, DO NOT USE HTML TAGS to hold such values and hide them... make the use of the data- attribute, witch is a HTML5 complience, and works very well in any browser even if it does not have not HTML5 support, like IE6.
your table definition (td) that currently is:
<td class="visible" id="r2">
<span class="hiddentext">Race 2<br />Santa Fe 12:00</span>
<strong>R2</strong>
</td>
should be something like:
<td class="visible" id="r2" data-text="Race 2<br />Santa Fe 12:00">
R2
</td>
witch is way easier to read, and from your javascript code, you can easily get this as:
var hiddenText = $nextCol.data("text");
Your code (part 2):
This one is quite simple to know
Every time you are repeating yourself, you're doing it wrong
You have the methods for Next and Prev almost exactly as each other, so, you are repeating everything, for this, you should refactor your code and just use one simple method, this way, any future change only happens in one place, and one place only.
$(".next").click(function(e){
e.preventDefault();
var $nextCol = $('.highlighted').next('td');
MoveCursor($nextCol, 'next');
});
$(".previous").click(function(e){
e.preventDefault();
var $prevCol = $('.highlighted').prev('td');
MoveCursor($prevCol, 'prev');
});
function MoveCursor(col, side) {
var maxCol = 8;
if((side === 'next' && col.length != 0) ||
(side == 'prev' && col.length != 0 && col.index() >= maxCol)) {
$('.highlighted').removeClass("highlighted");
col.addClass("highlighted");
// show current title
$('.showtext').html(col.data('text'));
if (col.hasClass("invisible")) {
col.removeClass("invisible");
col.addClass("visible");
var $toRem;
if(side == 'prev')
$toRem = col.next('td').next('td').next('td').next('td').next('td').next('td');
else
$toRem = $nextCol.prev('td').prev('td').prev('td').prev('td').prev('td').prev('td');
$toRem.removeClass("visible");
$toRem.addClass("invisible");
}
}
}
Live Example: http://jsfiddle.net/qKj6b/22/

It should be
$('.showtext').html($('.highlighted .hiddentext').html());
Similar for the prev link...
or even better, thanks to #balexandre:
$('.showtext').html($nextCol.find('.hiddentext').html());
$('.showtext').html($prevCol.find('.hiddentext').html());
Fiddle
Update to match #balexandre hint: Fiddle 2

Do the following:
var $currCol = $('.highlighted'); //to get the current column
$('.race strong').text($currCol.closest('.highlighted').first('td:first').text());

.hiddentext class selects all the spans and the first() will always return you the first td.
Just make sure you select .hiddentext from the currently highlighted column and you are good to go.
$('.showtext').text($('.highlighted .hiddentext').first('td:first').text());

Try this (Same for both)
$('.showtext').html($currCol.find('span.hiddentext').html());
Working Example.

Related

I'm trying to set a generic element invisible by attribute and in one line of javascript

I'm limited to one line because of a Chrome Extension and it's the only one that fits my needs.
The <td> needs to be gone through to the attribute "UserName" to determine if a blocked user needs to be invisible.
I cannot figure this out and I'm really a noob when it comes to Javascript (not my language)
I've tried display:none hidden and style.visibility="hidden".
I've tried w3Schools and searched through Javascript and HTML pages for how to this and while I've got code that does work, it's a script that takes about 8 lines which doesn't work. I may have to ditch it but I figured I've give it one last shot.
document.getElementsByTagName("td")[0].getAttribute("theUserName").value("madmax").style.visible = "hidden";
Expected - The <td> should not show up
Results - It shows up
One line to hide the content:
[...document.querySelectorAll("td[theUserName=madmax]")].forEach(e=>e.style.display = 'none');
To remove the <td>:
[...document.querySelectorAll("td[theUserName=madmax]")].forEach(e=>e.remove());
I am assuming that you to iterate through all <td> elements to search for one with theUserName attribute with value madmax, then make that element invisible. That can be achieved with:
for(TdElement of document.getElementsByTagName("td")) {
if (TdElement.getAttribute("theUserName") == "madmax") {
TdElement.style.visiblity = "hidden";
}
}
Condensed to a single line, this is:
for(TdElement of document.getElementsByTagName("td")) if TdElement.getAttribute("theUserName") == "madmax") TdElement.style.visiblity = "hidden"

Format text as user inputs in a contenteditable div

I'm attempting to make a page that allows users to input text and it will automatically format the input -- as in a screenplay format (similar to Amazon's StoryWriter).
So far I can check for text with ":contains('example text')" and add/remove classes to it. The problem is that all of the following p tags inherit that class.
My solution so far is to use .next() to remove the class I added, but that is limited since there might be need for a line break in the script (in dialogue for instance) and that will remove the dialogue class.
$('.content').on('input', function() {
$("p.input:contains('INT.')").addClass("high").next(".input").removeClass("high");
$("p.input:contains('EXT.')").addClass("high").next(".input").removeClass("high");
});
I can't get || to work in the :contains parameter either, but that's the least of my issues.
I have a JS fiddle
I've worked on this for a while now, and if I could change only the node that contains the text (INT. or EXT. in this example) and leaves the rest alone that would work and I could apply it to the rest of the script.
Any help would be appreciated, I'm new to the stackoverflow so thank you.
See the comments in the code below for an explanation of what's going on.
Fiddle Example
JQuery
var main = function(){
var content = $('.content');
content.on('input', function() {
$("p.input").each(function() {
//Get the html content for the current p input.
var text = $(this).html();
//indexOf will return a positive value if "INT." or "EXT." exists in the html
if (text.indexOf('INT.') !== -1 || text.indexOf('EXT.') !== -1) {
$(this).addClass('high');
}
//You could include additional "if else" blocks to check and apply different conditions
else { //The required text does not exist, so remove the class for the current input
$(this).removeClass('high');
}
});
});
};//main close
$(document).ready(main);

Targeting specific row/line of textarea and appending that row

I want to be able to click on a specific element, and have it send a value to a textarea. However, I want it to append to a specific row/line of the textarea.
What I am trying to build is very similar to what happens when you click the notes of the fret board on this site: http://www.guitartabcreator.com/version2/ In fact, i want it almost exactly the same as this.
But right now I am really just trying to see how I can target the specific row, as it seems doable based on this website.
Currently I am using javascript to send a value based on clicking a specific element.
Here is the js:
<script type="text/javascript">
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
}
</script>
This is the HTML that represents the clickable element:
<td> x </td>
This is the textarea:
<textarea rows="6" cols="24" id="tabText" name="text">-
-
-
-
-
-</textarea>
This works fine for sending the value. But it obviously just goes to the next available space. I am a total newb when it comes to javascript, so I am just not sure where to begin with trying to target a specific line.
What I have currently can be viewed here: http://aldentec.com/tab/
Working code:
After some help, here is the final code that made this work:
<script>
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}}
window.onload = function() {
addNote0('', 'tabText');
};
</script>
Tried to solve this only in JS.
What I did here is use an array to model each row of the textfield (note the array length is 6).
Then I used a jQuery selector to trigger any time a <td> element is clicked which calculates the fret and string that was clicked relative to the HTML tree then calls the updateNote function. (If you change the table, the solution will probably break).
In the update note function, I iterate through the tabTextRows array, adding the appropriate note. Finally, I set the value of the <textarea> to the array joined by '\n' (newline char).
Works for me on the site you linked.
This solution is dependant on jQuery however, so make sure that's included.
Also you should consider using a monospaced font so the spacing doesn't get messed up.
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}
I wrote the guitartabcreator website. Jacob Mattison is correct - I am using the text area for display purposes. Managing the data occurs in the backend. After seeing your site, it looks like you've got the basics of my idea down.

Multi-step form

i'm having a problem on how should i implement/build my form. here's the overview.
the first step of the form is to fill up the "Responsibility Center". however, the user can add multiple responsibility center. then the next step would be - each responsibility center added should have one or many "account codes". at the end of the form, before submitting it, all the data should be editable.
the result should be like this:
|**responsibility center**||**account codes**|
| center 1 || account code 1 |
| || account code 2 |
| center 2 || account code 1 |
etc..
i just need some idea on how the form should be built/implemented.
EDIT 1
This is what i've tried
1st step
2nd step
result
EDIT 2
i already know how to add multiple rows (like on the 2nd step) and i can implement that already on the first to the 1st step. so here are my questions:
how can i add account codes per responsibility center?
if what i've tried is not a practical way to implement it, then how should i do it?
Unfortunately, I began writing this answer before you posted the pics of your app. The ideas are still relevant, but I would have tailored my example more to what you are doing. Sorry about that.
I would use jQuery and AJAX to get the job done. jQuery to handle insertion of new elements to the DOM, and for field validation; AJAX to verify that no account codes are duplicated between RCs, or what have you. Personally, I would also use AJAX to handle the form submission instead of using the more traditional <form action= method=> because it gives greater control over the process and doesn't whisk the user off to another page before I am ready. However, it is easiest to describe the <form> example, and you can first build that and then change it over to using AJAX if you want.
The example from here is assuming a blank slate (i.e. I had not seen your sample app before writing this):
First, in your jQuery/javascript, you need a counter to keep track of each RC added. This can be in the <head> tags of your HTML/PHP, or it can be stored in a separate file. If you click on my name and look at other AJAX answers I've given, you'll see many useful examples.
<script type="text/javascript">
$(document).ready(function() {
var ctr = 0;
});
</script>
In your HTML, you need a DIV into which you will append each RC DIV. You also need a link/button/whatever for user to initiate creation of a new RC. This would be a brief form, even just [RC Title] and [Account Code] with a link/button/whatever to create another [Account Code] field and a [Done/Submit] button.
HTML:
<div id="container">
<form action="yourprocessorfile.php" method="POST" id="myform"></form>
</div>
<input type="button" id="mybutt" value="Add New RC" />
JAVASCRIPT/jQuery (again, inside the (document).ready() section above):
$('#mybutt').click(function() {
ctr++;
var str = 'RC TITLE:<br><input id="RC-"'+ctr+' class="RC" type="text"><br>ACCOUNT CODE<br><input id="AC-"'+ctr+' class="AC" type="text"><br>';
$('#myform').append(str);
});
When user presses [Done], use jQuery again to check that each [Account Code] field has been completed.
$('#done').click(function() {
$('.RC').each(function() {
if ($(this).val() == '') {
alert('Please complete all fields');
$(this).focus();
return false;
}
});
$('.AC').each(function() {
if ($(this).val() == '') {
alert('Please complete all fields');
$(this).focus();
return false;
}
});
$('#myform').submit();
});
Edit 2 / Question 1:
You can add new account codes linked to an RC by:
You need to somehow assign a unique data element to the RC, such as an incrementing ID
have a link for adding the new AC
use jQuery to get the ID of the nearest RC element
use .split() to split-off the numerical portion (assign to a var)
use that number when creating your AC
$('.add_AC').click(function() { //Note I used a class, so you can have a link for each RC
var num = $(this).parent().attr('id').split('-')[1];
var str = '';
});
In the above example:
==> Because I used a class, it will fire whenever ANY element with that class is clicked. Of course, when you create the button, you must add that class to the button def, as:
<input type="button" class="add_AC" value="Add Account Code" />
num ==> uses chained jQuery methods to, one-after-another, get the number portion of the RC's id.
$(this) ==> whichever [Add Account Code] button/link/whatever was clicked on.
.parent() ==> This may or may not be correct for your situation. This is the part where we traverse the DOM to find the RC element's ID code, which would look like this: RC-3. You will need to experiment with:
.parent().parent()
.sibling()
.parent().sibling()
.closest()
.prev() or .next()
Play with these selectors, with Dev Tools window opened. It should only take a handful of minutes to find your RC element -- or ask another question and post your HTML.
.attr('id') ==> Obviously, returns the text of the ID, in our case RC-3
.split('-')[1] ==> Creates an array with RC on one side (zero), and 3 on the other (1)
Hopefully this all gives you some idea of where to begin...

Is there a way to place a keyboard shortcut inside an editable div?

For example, i have a div which users can type into it. i would like to place shortcuts so when the user inputs the word pi. The output would be the symbol π. Or if the user inputs sqrt then they would get this symbol inf then the output would be ∞. and even when the tab button is clicked to indent a couple of lines. I have not seen a web app that does this yet so any help would be appreciated.
There's some extensive key tracking + field updating you can do to accomplish this, or you can get a jQuery plugin that already does something similar (if not exactly) and modify it to accomplish the same task.
This might be what you are looking for though:
http://code.google.com/p/js-hotkeys/wiki/about
You could simply use a replace. See JSFiddle demo here
$('.test').keydown(function (event) {
if ($('.test').val().contains("pi")) {
var newVal = $('.test').val().replace("pi", "π");
$('.test').val(newVal);
//Place Cusor at the end of the div if using editable div
}
else if ($('.test').val().contains("inf")) {
var newVal = $('.test').val().replace("inf", "∞");
$('.test').val(newVal);
//Place Cusor at the end of the div if using editable div
}
});
In this sample I am using an input. You can change that to div

Categories

Resources