I have a HTML table with text in the cells like so:
<tr><td>HELLO</td></tr>
I then have a text area like so:
<input type="text" id="txt_message" name="txt_message"
I want to make it so that when you click inside the table cell, the data (in this case the word 'HELLO') is inserted into the text area (so the user does not have to type it).
I dont know if this is possible, but I am guessing it is and it is 'probably' something in JavaScript.
If anybody has any advice that would be great, Thank you :)
[Working demo]
var textbox = document.getElementById('textbox');
var table = document.getElementById('table');
// add one event handler to the table
table.onclick = function (e) {
// normalize event
e = e || window.event;
// find out which element was clicked
var el = e.target || e.srcElement;
// check if it's a table cell
if (el.nodeName.toUpperCase() == "TD") {
// append it's content to the textbox
textbox.value += (el.textContent || el.innerText);
}
}
Note: all the conditional assignments with || are for cross-browser compatibility.
Here is Working demo using jquery.
To get the value, use innerhtml and a span, more here: http://www.vbforums.com/showthread.php?t=339864
To update the textarea you should be able to do something like: document.getElementById ("text_message").value = x;
a simple jQuery snippet, assuming you have 1 textarea and multiple td's to click over
(function() {
var ta = $('#txt_message');
$('td').bind('click.addtextarea', function() {
var text = $(this).html();
ta.val([ta.val(), text].join(' ')); /* this add words */
/* ta.val(text); this print one word */
});
})()
Related
My requirement is : Thers's an input field. When user is going to filled it,
on runtime i searched for #tag and make text bold. And wants to separate both groups of #tags
For Example: "I am more #FromSide #FromSide and would like to speak with someone more #ToSide"
Group1: #FromSide #FromSide
Group2: #ToSide
Here's my code:
`$('#custm-field').keyup(function(){`
`let str = $(this).val();`
`let arr = str.split(" ");`
`$(arr).each((i,e)=>{`
`if(e=="#")`
`{ // $(e).css('font-weight','bold');`
`arr[i].replace(e,"<strong>"+e+"</strong>");}
`let newStr = arr.join(" ");`
`$('#custm-field').val(newStr)`
`});`
This can be achieved using RegEx:
$('#custm-field').keyup(function(){
let str = $(this).val();
str = str.replace(/#(.+?)\s/, '<strong>$1</strong>');
$('#custm-field').val(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="custm-field"></input>
However, the bold effect won't be displayed in input fields, you need a contenteditable element for this.
I've constructed a solution for you,
First of all, you can't add HTML tags inside the value of an input tag. So you have to make use of contenteditable HTML attribute, by setting it to true contenteditable="true" on any element you can start to edit the content of it (write inside it).
NOTE: I added a background-color to make it visible when its empty
<div contentEditable="true" id="text" style="background-color: #eee;"></div>
Your JavaScript (JQuery) would look like this:
Note that your code had many errors I had to fix.
$('#text').keyup(function(){
// get the div element
let e = document.querySelector('#text');
// get only the text inside the element (without the HTML tags)
let str = e.innerText;
e.innerHTML = '';
// create a new element to contain our text because you cant add HTML text inside a DOM element directly
let tag = document.createElement('div');
let arr = str.split(" ");
// this string will contain our HTML and text
let newStr = ``;
$(arr).each((i,e)=>{
if(e[0]=="#")
{
newStr += `<strong>${e}</strong>`;
}
else{
newStr += `${e}`
}
newStr += ` `;
})
// add the string to the inner HTML of the element we created
tag.innerHTML = newStr;
// append the newly created element inside the div
e.append(tag);
// based on Vito Gentile answer
// this is to move the cursor to the end of the text we added, other wise the cursor would be at start of the text
cursorManager.setEndOfContenteditable(e);
});
I made use of the code of this answer, this is where this line cursorManager.setEndOfContenteditable(e); came from. Here is their code for convenience.
(function( cursorManager ) {
//From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];
//From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
//Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
function canContainText(node) {
if(node.nodeType == 1) { //is an element node
return !voidNodeTags.contains(node.nodeName);
} else { //is not an element node
return false;
}
};
function getLastChildElement(el){
var lc = el.lastChild;
while(lc && lc.nodeType != 1) {
if(lc.previousSibling)
lc = lc.previousSibling;
else
break;
}
return lc;
}
//Based on Nico Burns's answer
cursorManager.setEndOfContenteditable = function(contentEditableElement)
{
while(getLastChildElement(contentEditableElement) &&
canContainText(getLastChildElement(contentEditableElement))) {
contentEditableElement = getLastChildElement(contentEditableElement);
}
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
}( window.cursorManager = window.cursorManager || {}));
Hopefully this works like what you want.
I have a simple form that has 3 fields. user, id, email.
I have 2 PHP arrays $user & $id
When a user enters there name into the user or id fields I want the respective php arrays checking and if the name or id is in the array then change the background color of the input box they are currently in.
If they update there entry then the checking should continue and if no match is found then revert the background back to it's original white color.
If they empty the input field then the color should change back to white.
The page may be preloaded with values, so I may be changing the background color using php on the initial load..
I've found this, which sort of works for the specified characters in it's array:
$('input').bind("change keyup", function() {
var val = $(this).val();
var regex = /["<>&]/g;
if (val.match(regex)) {
$(this).css("background", "red");
val = val.replace(regex, "");
$(this).val(val);
}
$("p").html(val);
});
I've tried to update it to support a php array, but it doesn't work and I don't know how to make it check either array and revert the color back.
This is what I have so far :
JFIDDLE
Thanks :)
UPDATE
I've got this working using the following :
$(function(){
$('input').bind("change keyup", function() {
var val = $(this).val();
if ($(this).attr('id')=="user") {
var check = <?php echo json_encode($user)?>;
} else {
var check = <?php echo json_encode($id)?>;
}
if ($.inArray(val, check) != -1) {
$(this).css("background-color", "red");
} else {
$(this).css("background-color", "white");
}
});
});
But is there a neater way to write this ?
Thanks :)
if you want to use your php array in javascript, you can do this:
var myArray = <?php echo json_encode($myArray) ?>;
and do the javascript magic
i want to create array of same id or name using getElementById..
i have a "add button", when the user press this button, its generate a dropdown list(dynamic) which the value is get from mysql..
and its looks like this when the user press 3 times..
i want to create an array of this id, and store it to mysql..
this is my JS code :
var menu_paket_array = document.getElementById('menu_paket').value;
alert(menu_paket_array);
the problem is, when i try to create this array(menu_paket_array), the value in this array is just the first id (Test 1) only..
how can i fix this?
thanks...
Using the same id for more than one element is wrong. Id is to uniquely identify certain element. Using it for more elements defeats its -purpose. If you need that for i.e. CSS styling, then use class instead, which is designed just for such scenarios.
An ID must be unique on a page. You can only use it on one element.
Instead, use a CSS class or element type to iterate (here's a fiddle demonstrating this code):
function alertValues() {
var select, selects = document.getElementsByTagName('select');
var out = "";
for (var i = 0; i < selects.length; i++) {
select = selects[i];
if (select.className && select.className.match(/CLASSNAME_TO_INCLUDE/)) {
out += select.options[select.selectedIndex].value;
}
}
alert(out);
}
A better solution, of course, would be to utilize a dom library like jQuery or mootools, with which you could do something like this:
jQuery(function($) {
vals = [];
$('select.CLASSNAME').each(function() { vals.push($(this).val()); });
alert(vals.join(','));
});
document.getElementsByClassName(names);
Where names is the classname u generate for each one.
Instead of assigning each element with id='menu_paket' (for the reasons #WebnetMobile.com explained) assign class='menu_paket'.
Instead of var menu_paket_array=document.getElementById('menu_paket').value;, do
var temp_array = document.getElementsByClassName('menu_paket');
var menu_paket_array = [];
for(i in temp_array){
menu_paket_array[] = temp_array[i].value;
}
I have two text box which is storing in database using AJAX. But I want to return back the new added row in table structure.
I am using this concept in add product to sell . when I want to add an item then it will be display in a tabular grid format.
This is my AJAX code.
var xmlHttp
function newVendorGridInital()
{
//alert("HI");
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{alert ("Browser does not support HTTP Request"); return }
var item= document.getElementById('itemcode').value;
var url="ajax_NewVendorGrid.php"
url=url+"?itm="+item; // For multiple value send.
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=newVendorGrid
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function newVendorGrid()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("GridRuntimeData").innerHTML=xmlHttp.responseText;
> > > I didn't understand how to target the id field > > > GridRuntimeData
}
}
In my html page I have created a table structure i.e. head part.
In my PHP file I am returning the entire inserted row in a html row format using echo statement.
<?php
echo "<tr><td>".$item."</td></tr>";
?>
and my doubt is how to show that row in table. If I write entire table structure in php code then it will be working fine. But i don't want do all the time to return entire row.
Please Help me.
You can dynamically add rows to a table with Javascript like this:
var table = document.getElementById("mytable");
var td = document.createElement('td');
td.innerHTML = 'new row';
var tr = document.createElement('tr');
tr.appendChild(td);
table.appendChild(tr);
jsFiddle demo here
How do I change the area map color for different condition when the area is already highlighted?
This is my code:
if(partyname = "Democrat")
{
var data = $('#MT').data('maphilight') || {fillColor:'ff0000'};
data.alwaysOn = !data.alwaysOn;
$('#MT').data('maphilight', data).trigger('alwaysOn.maphilight');
}
if(partyname = "Republican")
{
var data = $('#MT').data('maphilight') || {fillColor:'000000'};
data.alwaysOn = !data.alwaysOn;
$('#MT').data('maphilight', data).trigger('alwaysOn.maphilight');
}
I am using jquery.maphighlight.min.js jQuery plugin for highlighting the map.
My problem is that the area is highlighted by red color with the first button. If I click the second button, the same area is highlighted but the color cannot be changed (the color should be changed to black).
For starters, try replacing "colorToHightlight" with colorToHighlight so you call the correct variable that you named earlier.
Something like:
Jquery:
var colorToHighlight = "black" //default
$("#color_options a").click(function (e)
{
e.preventDefault(); //stop the anchor tag
colorToHighlight = $(this).attr("id");
}
/*
Do the highlight stuff
*/
HTML:
<div id="color_options">
Green - Red
</div>
We used the alt attribute to hold the colour.
HTML:
<p>Go GREEN</p>
JS/JQuery:
$('.aToggle').click(function (e) {
var data = $('#area1').mouseout().data('maphilight') || {};
data.fillColor = $(this).attr('alt');
$('#area1').data('maphilight', data).trigger('alwaysOn.maphilight');
});
Where "area1" is the map area.