Adding tags to selection - php

I am using this Javascript to effect the following changes in my selected text:
function formatText(el,tag){
var selectedText = document.selection?document.selection.createRange().text:el.value.substring(el.selectionStart,el.selectionEnd);// IE:Moz
if (selectedText == "")
{return false}
var newText='"#28'+tag+'"'+selectedText+'"#28'+tag+'"';
if(document.selection){ //IE
document.selection.createRange().text=newText;
}
else{ //Moz
el.value=el.value.substring(0,el.selectionStart)+newText+el.value.substring(el.selectionEnd,el.value.length);
}
}
However, i want the new tags to only be visible in another textarea not the one where I actually do the selecting. In this case I have 2 Text areas, one is called "message_text" the other is called "message" ... I iwll input and select text in "message_text" but any changes made to the selection must only reflect in the "message" text area.
At present I have tried this:
<button type="button" value="D" onclick="formatText(message,'D')" class="blue">D</button>
But this only works if I have selected anytnin in the "message" text area.
Thanks

You have to extend the javascript code:
function formatText(el_from, el_to, tag) {
var selectedText = document.selection ? document.selection.createRange().text : el_from.value.substring(el_from.selectionStart, el_from.selectionEnd);// IE:Moz
if (selectedText == "") {
return false;
}
var start_index = el_to.value.indexOf(selectedText);
var sel_t_len = selectedText.length;
var copy_selText = el_to.substring(start_index, sel_t_len);
var newText='"#28'+tag+'"'+copy_selText+'"#28'+tag+'"';
el_to.value = el_to.value.substring(0, start_index) + newText + el_to.value.substring(sel_t_len, el_to.value.length);
}
Then You can call it like this:
<button type="button" value="D" onclick="formatText(document.getElementById('message_text'), document.getElementById('message'),'D')" class="blue">D</button>
PS: I'm not sure about document.getElementById - haven't used it for years since using jQuery... You should convert to jQuery, too... You would not noeed to solve JS for IE or FF or Chrome, etc - jQuery handles this by itself...
EDIT : OK, I did a little customization and it should fit to Your needs...

Related

Jquery Change Input background color if entry matches PHP Array?

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

Attaching textbox value to a link in the form of a variable without using submit button

I was wondering how it would be possible to attach an HTML form's text box value to a link. For instance, I have 3 links and each link goes to a different PHP file, however, I need to pass a variable. Because of the design of my page, I cannot use buttons. So, I created a form with a text field. How do I send that Text Fields value with the links?
EG:
<form>
<input type="text" name="test1" id="test1"></input></form>
Link 1
Link 2
Link 3
I hope this makes sense as to what I am trying to do.
EDIT:
I tried to do this dynamically, but:
OK, I made a function like this:
<script>
function awardcode()
{ var awamount = document.getElementById("awardamount");
document.write('<?php $awardvar = ' + awamount.value + '; ?>');
};
</script>
Then, I made the link via PHP that looks like this:
echo '<a id=awlink3 name=awlink3 href="index.php?siteid=gmaward&type=xp&post=' . $posts_row['posts_id'] . '&handle=' . $posts_row['handle'] . '&varamount=' . $awardvar . '">Award XP</a>';
However, that didn't work. This is my input box code:
<form><input type=text name='awardamount' id='awardamount' onchange='awardcode()' style:'width:10px;'></form>
When I put the number and then tab, it loads an empty page.
How can I adjust that?
You'll need to dynamically change the link using JavaScript. Here's one approach:
$('a').on('click',function(e) {
e.preventDefault();
var url = $(this).attr('href').split('$')[0];
window.location = url + $('#test1').val();
});
But it might be better to add an onchange event to the textbox itself, so that the HREF changes instantly and the user can see the intended destination on mouseover:
$('#test1').on('change', function () {
var val = $(this).val();
$('a[href*=\\?id\\=]').each(function (i, el) {
$(el).attr('href', function (j, str) {
return str.split('?')[0] + "?id=" + val;
});
});
});

change input button style using javascript on click

I wanted to change the style of the button I'm using every time I clicked that button and together change it's text. Problem is I wanted to do it using and external javascript which I'm not that familiar with it's syntax. To elaborate what I wanted to do is to have a button having a text displaying like: Very Good, Good, Moderate, Failed. Each of the text has it's own assigned gradient color using CSS let's say a gradient of Green for Very Good, Yellow for Good, Orange for Moderate and Red for failed. Tried searching for it but I only landed on an irrelevant posts. What I think is that I need to make a button with on click and everytime I click the javascript will add int values from 0 and reset back to 0 after it reaches 3. then I think I can use case for the css class assigning like this.style="failed" Well I don't know if this is possible.
UPDATE:
After doing some research I've managed to do something about the changing texts (using javascript alone) but not yet the class part since I think the class is a keyword in javascript. here's my script so far:
function buttonChange(){
var button = document.getElementById("stats");
switch (button.value)
{
case "Very Good":
button.value="Good";
break;
case "Good":
button.value="Moderate";
break;
case "Moderate":
button.value="Failed";
break;
default:
button.value="Very Good";
}
}
now the problem is the style. :)
Using jQuery your code could look something like this:
var values = new Array('Very Good', 'Good', 'Moderate', 'Failed');
var colors = new Array('lime', 'yellow', 'orange', 'red');
$('#rate').click(function() {
// current index is stored in data attribute
var idx = $(this).data('value') + 1;
// last value was selected -> go back to first one
if (idx >= values.length) {
idx = 0;
}
// update data attribute with current index
$(this).data('value', idx);
// update button text
$(this).val(values[idx]);
// update button background color
$(this).css('background-color', colors[idx]);
});​
See this FIDDLE.
have a look at this:
Change an element's class with JavaScript
I think that your CSS should have all the styles for gradients and stuff like this:
.VeryGood {//gradient for very good
}
.Good {//gradient for good
}
.Moderate {//gradient for moderate
}
.Failed { //gradient for failed
}
and then, use this javascript and html :
<script type="text/javascript">
var i = 1; //change to 0 if element dosen't need to have any class by default
var classArray = new Array();
classArray[0] = 'VeryGood';
classArray[1] = 'Good';
classArray[2] = 'Moderate';
classArray[3] = 'Failed';
function changeClass()
{
document.getElementById("MyElement").className = classArray[i];
i++;
if(i>=3){
i=0;
}
}
</script>
...
<button onclick="changeClass()">My Button</button>
now, the array key i increases every time the button is clicked, so by default, you can have your element's class as VeryGood, and every time the button is clicked, it advances to next class, so after VeryGood comes Good then Moderate then Failed, ithe it resets itself to VeryGood. hope this is what you are looking for :)
Here is a jQuery solution to cycle through the button text and the background colour for the four states:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var states = ['Very Good', 'Good', 'Moderate', 'Failed'];
var colors = ['green', 'Yellow', 'orange', 'red'];
var index = 0;
$('body').on('click', '#button', function(){
index = ++index%4;
$("#button").html(states[index]);
$("#button").css('background-color',colors[index]);
});
});
</script>
</head>
<body>
<button id="button" style="background-color:green"; type="button">Very Good</button>
</body>
</html>
Note the modulus (%) operator which simplifies the circular increment of 'index' from 0 to 3.

How to dynamically add an HTML array element[]

I have a form where I need to dynamically add as many text fields as the user wants to. I want the text fields to be an array, for example:
<input type="text" name="room_text[]">
I've already built something I thought would work. It successfully adds more text boxes. I added two more text boxes with javascript dynamically, making the form look like this:
<input type="text" name="room_text[]">
<input type="text" name="room_text[]">
<input type="text" name="room_text[]">
BUT, when I posted it to the PHP file, it only gets the first value. The reason why I know this is a javascript problem is becuase it works fine if you have more than one text box on page load. Its just when you add more text boxes with javascript.
If this helps, this is the jquery function I use to add the boxes:
$('.add').live("click", function() {
var mu = $(this).parent('td').parent('tr');
var clone = $(this).parent('td').parent('tr').clone();
$(clone).children('td').children('.add').remove();
$(clone).children('td').children('.redtext').remove();
$(clone).children('td').children('.remove').css("display", "inline");
$(clone).css("display", "none");
$(mu).after(clone);
$(clone).show("fast");
});
I believe the problem resides in the .clone() function. Can you try a different method, say ...
$('.add').live("click", function() {
var mu = $(this).parent('td').parent('tr');
var clone = '<tr>' + $(this).parent('td').parent('tr').html() + '</tr>';
$(clone).children('td').children('.add').remove();
$(clone).children('td').children('.redtext').remove();
$(clone).children('td').children('.remove').css("display", "inline");
$(clone).css("display", "none");
$(mu).after(clone);
$(clone).show("fast");
});
UPDATED - Oops. In that version "clone" is a string, not an element, so the .children() functions aren't working ... here's a corrected version:
$('.add').live("click", function() {
var mu = $(this).parent('td').parent('tr');
var clone = $('<tr>' + $(mu).html() + '</tr>');
$(clone).children('td').children('.add').remove();
$(clone).children('td').children('.redtext').remove();
$(clone).children('td').children('.remove').css("display", "inline");
$(clone).hide();
$(mu).after(clone);
$(clone).show("fast");
});​

Click HTML table data and insert into text area

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 */
});
})()

Categories