How to switch <td> content with another <td> [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So the thing goes as following: I'm a begginer programmer (so far i know HTML, CSS some JavaScript and some C++) and we have a school project to create a chessboard with figures on them but I want to go a step further and be able to move the figures.
So far I've used the prompt function to get the coordinates and move them around but that feels far too much stone-agish. Now what I wish to accomplish is to be able to click on a , copy its content into a variable and upon clicking on another replace its content with the one stored in the variable. (I'll deal with the rules later..)
Each has its unique id and I have used element.firstChild.nodeValue to acquire the content.. Any suggestions on how to do this in JavaScript without using jQuery (if it can't be done in JavaScript then by all means do it in some other language.. it's about time I start learning them anyway.. :P)

If each <td> has a unique id, what about:
var lastStoredValue = "", lastClicked = ""; // = "" is important in that case
var t1 = document.getElementById("t1"); // td with id="t1"
var t2 = document.getElementById("t2"); // td with id="t2"
t1.onclick = function() {
if (lastClicked !== "t1" && lastStoredValue.trim())
t1.innerHTML = lastStoredValue; // replace its content with the one stored in the variable
if (!lastStoredValue.match(new RegExp(t1.innerHTML)))
lastStoredValue= t1.innerHTML; // copy its content into a variable
lastClicked = "t1";
}
t2.onclick = function() {
if (lastClicked !== "t2" && lastStoredValue.trim())
t2.innerHTML = lastStoredValue; // replace its content with the one stored in the variable
if (!lastStoredValue.match(new RegExp(t2.innerHTML)))
lastStoredValue= t2.innerHTML; // copy its content into a variable
lastClicked = "t2";
}
This gets what is stored into one td and puts it into a variable; then stores what is in the variable into another td when click on that td.

Related

Insert json object in text area [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hi I am developing a small application in JSP.
My idea is to give reference to a JSON element while user is typing in the text area.
for example:
If my JSON contains:
cO2,
H2O,
c9O
and in the text area the user is typing a sentence and as soon as the user types a special character such as # or \ or / if he/she writes "c" character I want a small drop down to appear with the two elements starting with c.
The user can select the element afterwards and then when the form is posted I want to extract those information which was entered from JSON.
This is like when you start typing a name in Facebook I guess.
Any ideas?
Thanks in advance
EDIT: JS Fiddle
<form action="./Protocol" method="POST">
<textarea rows=5 cols=50></textarea>
<input type="submit"/></form>
$('textarea').textcomplete([{
match: /(^|\s)(\w{2,})$/,
search: function (term, callback) {
var words = ['google', 'facebook', 'github', 'microsoft', 'yahoo'];
callback($.map(words, function (word) {
return word.indexOf(term) === 0 ? word : null;
}));
},
replace: function (word) {
return word + ' ';
}}]);
The above JS Fiddle does what I want partly.
One of the two things I want to accomplish here
1. if in the JSON, each word has an ID like {"ID": "1","name": "GOOGLE"} can I get the IDs that are in the textarea to be posted when the form is posted
2. or just the array index numbers, how do I POST the values in the form separately from the textarea.
OK, despite what I said, here's a basic example of how you might achieve this (because I was bored, but not so bored I'm going to do it all for you :)):
HTML
<input id="input"/>
<div id="dropdown"></div>
JS
// grab the DOM elements
var input = document.getElementById('input');
var dropdown = document.getElementById('dropdown');
// assign an function to the onkeyup event for your input box
input.onkeyup = search;
// define your data structure
var arr = ['cO2', 'H2O', 'c9O'];
function search() {
// get the content and length of the content
// `this` in this instance refers to the element to which
// we assigned the function
var val = this.value;
var len = val.length;
// filter out the elements from the array that match
// the content, or nothing if the input is empty
dropdown.textContent = arr.filter(function(el) {
return val !=='' ? el.substring(0, len) === val : '';
});
}
DEMO
Hope that helps you on your way.

can not parse getElementById [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this function which produces the correct value when run, but I am having a hell of a time displaying the results.
Here is the JS which is calculated onChange in a form I am trying to display the resulting value elsewhere on the form. The alert displays the correct value but my id remains blank.
Thanks in advance for taking a look
function calculate_mtow1() {
togw_n = 0;
togw = $('#togw').val();
if (togw != '' && togw != 0 && togw != 'Nan') {
var togw = togw.replace(",", "");
togw_n = togw;
}
burn_n = 0;
burn = $('#burn').val();
if (burn != '' && burn !=0 && burn != 'Nan') {
var burn = burn.replace(",", "");
burn_n = burn;
}
var mtow1 = parseInt(togw_n) + parseInt(burn_n);
$('#mtow1').val(mtow1);
document.getElementById('mtow1');
alert(mtow1);
}
<td>TOW + Fuel Burn =<span id="mtow1"></span></td>
Your code is getting the element with getElementById but then not doing anything with it. You need to assign the result of getElementById to something, or call methods on it on the same line. If your goal is to put the value of mtow1 into your <span>, try doing this:
// Solution 1
var spanElement = document.getElementById("mtow1");
spanElement.innerHtml = mtow1;
Alternatively, perhaps you were trying to display the value of mtow1 by using this jQuery:
$('#mtow1').val(mtow1);
That doesn't do what you think it does. It changes the "value" attribute of the span to the value of mtow1, but that change isn't visible to the user. It's the same as writing this as your HTML:
<td>TOW + Fuel Burn =<span id="mtow1" value="valueofmtow1"></span></td>
If you want to use jQuery instead of the getElementById method I posted above, you could do this:
// Solution 2
$('#mtow1').html(mtow1);
You don't need to do both. Either solution will work on its own.

Facing error while getting value of dynamically created textbox [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have created a dynamic textbox but unable to fetch its value on runtime. it shows something else.
code
var UL = document.createElement('ul');
var Li = document.createElement('li');
var A4 = document.createElement('input');
A4.type = 'text';
A4.setAttribute('id', 'current_page');
A4.value = list.length;
A4.setAttribute('style', 'width:30px;height:26px;text-align:center;position:relative;left:35px');
Li.appendChild(A4);
UL.appendChild(Li);
script
var va = $('#current_page').val;
alert(va);
Seeing as you're using JavaScript for everything else, save the jQuery for another day:
var va = document.getElementById('current_page').value;
In jQuery you need to use .val(); instead of .val;
var va = $('#current_page').val();
alert(va);
It doesn't look like you're ever appending anything to the document.
You need to use $('#current_page').val(); to get the value
For future reference can check if your selectors are finding anything using:
console.log($('#current_page'));
Use .val() in jQuery and it is a function
var val = $('#current_page').val();
alert(val);
Using Native JavaScript, You can use document.getElementById
alert(document.getElementById('current_page').value)

Can this big block of code be avoided in javascript? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Haven't worked much on front-end and was wondering if what I did is correct.
I have created an html table that displays data.
I have added button and check-boxes to modify structurally the table i.e. add a row.
The code to do that is a big block of code that does something like:
var table = document.getElementById('table');
table.insertRow(1);
var id_td = document.createElement('td');
//create options element
id_td.appendChild(options);
var name_td = document.createElement('td');
//create input textbox
name_td.appendChild(txt_box);
etc etc
So I don't like the fact that it is a really big-block of essentially repeating code that creates the elements.
I wanted to know, am I on the right track? Is this the only way unless we use some library like JQuery?
The VanillaJS approach
You can use something like
var table = document.getElementById('table');
table.innerHTML = "<tr><td id="+id+"></td><td class="name"></tr>";
To add your markup as a string, which might end up being more clear. Tough to tell exactly without seeing exactly how you're repeating yourself, but you might be able to abstract this out into a function
Libraries
There are plenty of libraries though that abstract away this ugliness though. jQuery is one, but something like knockoutjs might be a better fit for you.
It allows you to define a data model and bind html templates to that data model with automatic updating. So you could then just define your data as a JSON object and have it reflected in the DOM, with future updates just touching the view-model object and not having to deal with the DOM functions at all.
I don't like the fact that it is a really big-block of essentially repeating code that creates the elements
Why not make aliases for the long-winded function names?
var gid = function (id) {return document.getElementById(id);}, // so short!
ce = function (e) {return document.createElement(e)}, // ce(tag) is easy!
td = function () {return ce('td');}, // td() now makes a new `<td>`
ap = function (p, c) {return p.appendChild(c), p;}; // return more useful
now that "big-block" is
var table = gid('table'),
row = table.insertRow(1);
var id_td = td(), options = ce('select');
ap(id_td, options);
var name_td = td(), txt_box = ce('textarea');
ap(name_td, txt_box);
// etc etc

Using Javascript how to exchange the id of textbox [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How can I exchange ids of two textboxes?
I have two textboxes,
<input type="text" id="name1" name="fname"/>
and
<input type="text" id="name2" name="lname"/>
programatically through Javascript, I want to exchange the ids name1 and name2 of both the textboxes. Please suggest the right way to achieve this.
function swapId( elem1, elem2 ) {
var temp = elem1.id;
elem1.id = elem2.id;
elem2.id = temp;
}
swapId( document.getElementById('name1'), document.getElementById('name2') );
Which is a very simplified example. There should be more checking if passed in values really are references to actual DOM nodes etc. But this will work just fine.
Exchanging the IDs is as simple as getting a reference to the two text boxes, then assigning the IDs you want them to have. While it is invalid to temporarily have two elements with the same ID, no browser will prevent you from doing so.
var fname = document.getElementById('name1');
var lname = document.getElementById('name2');
fname.setAttribute('id', 'name2');
lname.setAttribute('id', 'name1');
Try this code...
var id1 = document.getElementById('name1');
var id2 = document.getElementById('name2');
id1.setAttribute("id", "name2");
id2.setAttribute("id", "name1");

Categories