html text area with jquery - php

noob here
i got this jquery code that i found on stackoverflow
var maxLines = 2,
maxLineWidth = 5;
$('#Users_address').bind('change keyup paste drop', function() {
var value = $(this).val(),
lines = value.split('\n'),
linesLength = lines.length;
if (linesLength > maxLines) {
lines = lines.slice(0, maxLines);
linesLength = maxLines;
}
for (var i = 0; i < linesLength; i++) {
if (lines[i].length > maxLineWidth) {
lines[i] = lines[i].substring(0, maxLineWidth);
}
}
$(this).val(lines.join('\n'));
});
how would i use this with a text area??

Give your textarea an id:
<textarea id="Users_address"></textarea>
And load your script:
$(document).ready(function() {
var maxLines = 2,
maxLineWidth = 5;
$('#Users_address').bind('change keyup paste drop', function() {
var value = $(this).val(),
lines = value.split('\n'),
linesLength = lines.length;
if (linesLength > maxLines) {
lines = lines.slice(0, maxLines);
linesLength = maxLines;
}
for (var i = 0; i < linesLength; i++) {
if (lines[i].length > maxLineWidth) {
lines[i] = lines[i].substring(0, maxLineWidth);
}
}
$(this).val(lines.join('\n'));
});
});

Make your text area id 'Users_address' or change that '#Users_address' to '#{textarea-id}' replacing the stuff in the brackets with your text area id, then it will work with your text area.

Related

How to to output json into a div

Consider the following PHP Block. I want to output "name" to div #1 and "slog" to div #2
<?php
require_once 'db_conx.php';
$Result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated desc limit 1") or die (mysql_error());
while($row = mysql_fetch_array($Result)){
$result = array();
$result['name'] = $row['name'];
$result['slog'] = $row['slog'];
echo json_encode($result);
}
mysql_close($con);
?>
Here's the ajax that just outputs json itself.
var get_fb = (function() {
var counter = 0;
var $buzfeed = $('#BuzFeed');
return function(){
$.ajax({
type: "POST",
url: "../php/TopBusinesses_Algoriththm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>").addClass('flat-menu-button');
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 1000);
})
};
})();
get_fb();
You can update the html/content of a DOM element with the following:
document.getElementById(name).innerHTML = "text";
So in this instance:
document.getElementById('#1').innerHTML = $yourNameContent;
document.getElementById('#2').innerHTML = $yourSlogContent;
First: move var counter = 0; outside from get_fb() function;
Second: Do not call get_fb(); explicitly, because (function(){...})(); already calls method after initialization.
Third: Why use POST method if there is not data to submit!
So, do this and have a try:
var counter = 0;
var $buzfeed = $('#BuzFeed');
var get_fb = (function() {
$.ajax({
type: "GET",
url: "../php/TopBusinesses_Algoriththm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>").addClass('flat-menu-button');
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 1000);
})
})();

Update a span when a select dropdown is made using ajax

I am attempting to code the following script using jquery / ajax / php.
What happens is the php pulls all the records from the database and puts them into a select dropdown. When I select an item from the dropdown ajax pulls the price from the database and adds it into the span called priceeach1 . Well thats what its supposed to do, but my jquery is useless :-S .
The stockID comes from the select box value.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock1').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += data[x]['priceeach'];
}
$('#priceeach1').text( options);
});
});
});
</script>
The HTML :
Price Each : £<span id="priceeach1"></span>
The select2.php :
<?php include 'connectmysqli.php'; ?>
<?php
$id = $_GET['stockID'];
$sql = 'SELECT * FROM stock WHERE stockID = ' . (int)$id;
$result = $db->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = array(
'priceeach' => $row['priceeach'],
);
}
echo json_encode($json);
?>
EDIT >> Ok I have now updated the code with the latest edits, this now WORKS.....apart from an odd problem......If I select the first or last item in the list no price is displayed, anything in between appears just fine..........
Try this,
var options = [];
for (var x = 0; x < data.length; x++) {
options = data[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
It should be like this you have to store price in the array options[] instead of option and then join them by any separator
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options[x] = data[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
});
});
});
</script>
You have to parse your JSON data to actual JSON Object before iterating it.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var jsonParsed = JSON.parse(data);
var options = '';
for (var x = 0; x < jsonParsed.length; x++) {
options[] = jsonParsed[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
});
});
});
</script>
Try to use this snipt:
for (var x = 0; x < data.length; x++) {
options += data[x]['priceeach'];
}
$('#priceeach1').text( options);

append new text on textarea

I am writing a tag system based on http://jsfiddle.net/joevallender/QyqYW/1/ but when i try to add new tag by typing in textarea, it works fine but when i click on any tag, previous new text will be removed.
HTML
<textarea id="tags"></textarea>
<div id="tagButtons"></div>
Javascript
var tags = [
'JavaScript',
'jQuery',
'HTML5',
'CSS3'
];
var selectedTags = [];
for(var i = 0; i < tags.length; i++) {
var el = $('<span>').text(tags[i]);
$('#tagButtons').append(el);
}
$('#tagButtons span').click(function(){
var val = $(this).text();
var index = selectedTags.indexOf(val);
if(index > -1) {
var removed = selectedTags.splice(index,1);
$(this).removeClass('selected');
} else {
selectedTags.push(val);
$(this).addClass('selected');
}
$('#tags').val(selectedTags.join(', '));
});
​
Your problem is in this line
$('#tags').val(selectedTags.join(', '));
It's overwriting what was in the textarea before.
EDIT:
Try it :
http://jsfiddle.net/QyqYW/92/
var tags = [
'JavaScript',
'jQuery',
'HTML5',
'CSS3',
'PHP'
],
keys = "";
var selectedTags = [];
for(var i = 0; i < tags.length; i++) {
var el = $('<span>').text(tags[i]);
$('#tagButtons').append(el);
}
//changed click event to "on" event..
//it seems that click doesn't bind to dynamically added elements
$('#tagButtons').on("click" , "span" , function(){
//Checks if you've forgot to type "," and then adds your tag
if(keys != ""){
selectedTags.push(keys);
$('#debug').prepend($('<div>').html('Added: ' + keys));
var newEl = $('<span class="selected">').text(keys);
$('#tagButtons').append(newEl);
$('#tags').focus().val(selectedTags.join(', ') + ", ");
keys = "";
}
var val = $(this).text();
var index = selectedTags.indexOf(val);
if(index > -1) {
var removed = selectedTags.splice(index,1);
$(this).removeClass('selected');
$('#debug').prepend($('<div>').html('Removed: ' + removed));
$('#tags').focus().val(selectedTags.join(', ') + ", ");
} else {
selectedTags.push(val);
$(this).addClass('selected');
$('#debug').prepend($('<div>').html('Added: ' + val));
$('#tags').focus().val(selectedTags.join(', ') + ", ");
}
});
//adds tag after you type ","..
//if you forgot to, look above the first line in the on event
$("#tags").keydown(function(evt){
if(evt.which == 188){
selectedTags.push(keys);
$('#debug').prepend($('<div>').html('Added: ' + keys));
var newEl = $('<span class="selected">').text(keys);
$('#tagButtons').append(newEl);
$('#tags').val(selectedTags.join(', '));
keys = "";
} else if(evt.which ==8){
//for after adding tag you can't use Backspace to delete it.
//remove tag from butotns
if(keys == ""){
evt.preventDefault();
} else {
keys += String.fromCharCode(evt.which).toLowerCase();
}
});
I continued working on the jsfiddle on your original question
add and remove multiple tag by onclick to textarea
see http://jsfiddle.net/joevallender/QyqYW/14/
To be honest I think you should just put the tags into a seperate div or input. They should be stored seperately in a db anyway.
$(this).text();
Abowe, will only return value which was rendered oryginaly into DOM from html. Whatever you type into textarea is not there yet, you have to hook on ('#tags').on('keyup' function () {});
and store what was typed in order to include it to textarea later.

Implement a dynamic selectbox in html

I am trying to develop a select box so that I can change the selected option dynamically
e.g.
selectbox option display message
---------------------------------------------
field 1 text
field 2 integer
field 3 bool
There are three select boxes. The first select box provide three options.
when select box 1 is selected, the other select boxes will have only 2 options (excluding the selected one)
When select box 2 is selected, the other select boxes will have only 1 option (excluding the selected two)
When a select box's value changes, the appropriate message is displayed.
All of the text that will be displayed is read in from a database as an array in the following format:
name text
id integer
address text
Then I create a select box with the three option
When I set select box 1's value as name, the text message is displayed, and so on.
How should I implement this? (I hope you get my idea) Thank you again for your help.
Thank you
I'd suggest something akin to the following:
var sel1 = document.getElementById('one'),
sel2 = document.getElementById('two'),
sel3 = document.getElementById('three'),
sels = document.getElementsByTagName('select'),
reset = document.getElementById('reset');
function disableOpts(elem) {
for (var i = 0, len = sels.length; i < len; i++) {
if (sels[i] != elem) {
var opts = sels[i].getElementsByTagName('option');
for (var c = 0, leng = opts.length; c < leng; c++) {
if (c == elem.selectedIndex) {
opts[c].disabled = true;
}
}
}
}
};
sel1.onchange = function() {
disableOpts(this);
};
sel2.onchange = function() {
disableOpts(this);
};
sel3.onchange = function() {
disableOpts(this);
};​
JS Fiddle demo.
Edited to add the messages, as requested in comments (which I overlooked in the actual question...):
var sel1 = document.getElementById('one'),
sel2 = document.getElementById('two'),
sel3 = document.getElementById('three'),
sels = document.getElementsByTagName('select'),
reset = document.getElementById('reset'),
msgs = ['text','integer','boolean'];
function disableOpts(elem) {
for (var i = 0, len = sels.length; i < len; i++) {
if (sels[i] != elem) {
var opts = sels[i].getElementsByTagName('option');
for (var c = 0, leng = opts.length; c < leng; c++) {
if (c == elem.selectedIndex) {
opts[c].disabled = true;
}
}
}
}
hideMessage(elem);
};
function displayMessage(elem){
for (var i=0,len=sels.length;i<len;i++){
if (sels[i] == elem){
var span = elem.parentNode.getElementsByTagName('span')[0];
span.innerHTML = msgs[i];
span.style.display = 'block';
}
}
};
function hideMessage(elem){
for (var i=0,len=sels.length;i<len;i++){
if (sels[i] == elem){
var span = elem.parentNode.getElementsByTagName('span')[0];
span.innerHTML = '';
span.style.display = 'none';
}
}
};
sel1.onchange = function() {
disableOpts(this);
};
sel2.onchange = function() {
disableOpts(this);
};
sel3.onchange = function() {
disableOpts(this);
};
sel1.onfocus = function() {
displayMessage(this);
};
sel2.onfocus = function() {
displayMessage(this);
};
sel3.onfocus = function() {
displayMessage(this);
};
sel1.onblur = function() {
hideMessage(this);
sel2.onblur = function() {
hideMessage(this);
};};
sel3.onblur = function() {
hideMessage(this);
};​​
JS Fiddle demo.
Take a look at this plugin, maybe it can help you.
For the data than you can put a php foreach for the <option> element on the select.

undefined value single checkbox javascript to another page

i have two page, the first page is index.php i also using facebox framework in it. the second page is addevent.php i've tried in many ways to catch the value of single checkbox in addevent.php and passing it to index.php. but it didn't show the value. so is there someting wrong with my code ? what i'm miss ? any help would be appreciate..
index.php
echo ">".$check=$_REQUEST['check'];
echo "check[0]: ".$check[0];
&lthead&gt
&ltscript src="inc/jquery-1.4.4.min.js" type="text/javascript"&gt&lt/script&gt
&ltscript src="inc/facebox.js" type="text/javascript"&gt&lt/script&gt
&ltbody>
&lta href="addevent.php" rel="facebox" &gtlink&lt/a&gt
&lt/body>
addevent.php
&lthead&gt
&ltscript src="inc/jquery-1.4.4.min.js" type="text/javascript"&gt&lt/script&gt
&ltscript src="inc/facebox.js" type="text/javascript"&gt&lt/script&gt
&ltscript language="javascript" type="text/javascript"&gt
function AddEventAgenda(){
//--- i've tried this method & firebug said:document.eventAgendaForm.checkName[0] is undefined----
var elemLength = document.eventAgendaForm.checkName.length;
if (elemLength==undefined) {
elemLength=1;
if (document.eventAgendaForm.checkName.checked) {
// we know the one and only is checked
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
} else {
for (var i = 0; i&ltelemLength; i++) {
if (eventAgendaForm.checkName[i].checked) {
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//--- also this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var len = document.eventAgendaForm.checkName.length;
if(len == undefined) len = 1;
for (i = 0; i &lt len; i++){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var formNodes = document.eventAgendaForm.getElementsByTagName('input');
for (var i=0;i&ltformNodes.length;i++) {
/* do something with the name/value/id or checked-state of formNodes[i] */
if(document.eventAgendaForm.checkName[i].checked){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
if (typeof document.eventAgendaForm.checkName.length === 'undefined') {
/*then there is just one checkbox with the name 'user' no array*/
if (document.eventAgendaForm.checkName.checked == true )
{
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
}else{
/*then there is several checkboxs with the name 'user' making an array*/
for(var i = 0, max = document.eventAgendaForm.checkName.length; i &lt max; i++){
if (document.eventAgendaForm.checkName[i].checked == true )
{
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//-----------------------------------------------
window.location="index.php?tes=1" + check; // display the result
$(document).trigger('close.facebox');
}
&lt/script&gt
&ltscript type="text/javascript"&gt
// i don't know if these code have connection with checkbox or not?
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function () {
oldonload();
func();
}
}
}
addLoadEvent(function () {
initChecklist();
});
function initChecklist() {
if (document.all && document.getElementById) {
// Get all unordered lists
var lists = document.getElementsByTagName("ul");
for (i = 0; i &lt lists.length; i++) {
var theList = lists[i];
// Only work with those having the class "checklist"
if (theList.className.indexOf("checklist") &gt -1) {
var labels = theList.getElementsByTagName("label");
// Assign event handlers to labels within
for (var j = 0; j &lt labels.length; j++) {
var theLabel = labels[j];
theLabel.onmouseover = function() { this.className += " hover"; };
theLabel.onmouseout = function() { this.className = this.className.replace(" hover", ""); };
}
}
}
}
}
&lt/script&gt
&lt/head&gt
&ltform name="eventAgendaForm" id="eventAgendaForm" &gt
&ltul class="checklist cl3"&gt
&ltli &gt&ltlabel for="c1"&gt
&ltinput id="checkId" name="checkName" value="1" type="checkbox" &gt
&lt/label&gt&lt/li&gt&lt/ul&gt
&ltinput class="tombol" type="button" name="Add" value="Add" onclick="AddEventAgenda()" /&gt
&lt/form&gt
why not use jQuery if you are including jQuery library?
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").val();//gets you the value regardless if checked or not
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").attr("checked"); //returns checked status
or
var global_variable=""; //should be initialized outside any function
jQuery("#FORM_ID_HERE").children(":input[type='checkbox']").each(function(){
if (jQuery(this).attr("checked"))global_variable+="&"+jQuery(this).attr("name")+"="+jQuery(this).val();
});
this is just a suggestion to start from, not ideal. the ideal part is to use [] in your form.

Categories