Display a post under the form after submitting it - javascript

I'm trying to build something similar to Facebook's posting system.
Goal: Display a new DIV below an INPUT TEXT field upon the user clicking POST. The DIV should display the contents of the text field.
This is what I have tried:
HTML
<div class="update">
<p>Update </p>
<div class="feed-me" ></div>
<input type="text" name="update status" Id="cmm_box" placeholder ="What's on your mind " />
<input type="button" value="post"/>
</div>
JavaScript/jQuery
<script >
var text front = "" ;
var text end = " #user name " ;
$(document).ready ( function ) {
$('input [ type=button] ' ).click(
function ( ) { update( ); }
);
});
function update( ) {
$( ' div.feed_me ' ) .html ( textfront + $ ( ' cmm_box ' ).val( ) + textend ) ;
$( ' div.feed_me ' ) .html ( textfront + $ ( ' cmm_box ' ).val( ) + textend ) ;
$( ' div.feed_me ' ) .html ( textfront + $ ( ' input [ name=update ] ' ).val( ) + textend ) ;
</script >

Related

How can I auto fit/resize a html5 textarea element to fit the initial content?

Goal:
I'm looking for a way in javaScript/jQuery to size a textarea so that it initially shows all of its text content, hide the vertical scrollbar, and show the resize handle.
The code that is below, first shows the textarea with some content,but not enough that the vertical scrollbar appears. This would be fine, except I want the textarea to look like this no matter how much text it contains, that is showing no vertical scrollbar.
When you click the button, more text is added and the vertical scrollbar shows, which is what I to avoid when I say initially when there is too much content -- the textarea should expand to fit it, which I try to do with the next two button clicks.
Clicking the button again causes the textarea to widen, so that none of the current lines wrap.
Clicking the button again, now causes the textarea to grow taller so the vertical scrollbar no longer shows.
However, the textarea grows too much and a gap shows between the last line of text and the bottom line of the textarea. Not what I want.
If the textarea's scrollHeight represents the whole height of the contents of the textarea, and there are no empty lines at the bottom, why is there a gap?
const text = 'This is a line of text';
var $textarea = $( '#example' );
var i = 0;
$textarea.val( $textarea.val() + text );
for( var l = i + 5 ; i < l; ++i )
$textarea.val( $textarea.val() + "\r\n" + text + '(' + i + ')' );
function doIt( This ) {
if( This.innerText !== 'Click Me Again' ) {
for( var l = i + 5 ; i < l; ++i )
$textarea.val( $textarea.val() + "\r\n" + text + '(' + i + ')' );
if( This.innerText === 'Click Me' ) {
This.innerText = 'Click Me Again';
$( 'p' ).text( 'to make the textarea\s width wider.' );
}
else {
$textarea.css( 'height', 'auto' ); // As per Mr Khan's sugestion.
$textarea.css( 'height', $textarea[ 0 ].scrollHeight + 'px' );
$( 'p' ).html( '<b>Why is there space below the last line of text?</b>' );
}
}
else {
This.innerText = 'Click Me Some More';
$textarea.css( 'width', ( $textarea.width() + 36 ) + 'px' );
$( 'p' ).text( 'to make the textarea\'s height taller and add more text.' );
}
}
#example { width: 185px; height: 100px; overflow: auto; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>jQuery getScrollBarWidth example</title>
</head>
<body>
<h1>Snippet Example</h1>
<button onclick="doIt( this );">Click Me</button><br />
<p>to add more text to the textarea.</p>
<textarea id="example"></textarea>
</body>
</html>
Update
The codePen works for up to 1000 lines when the Rows option is used. After 999 lines then adjusting the textarea's rows attribute no longer works because each row wraps to two lines, so after 999, the rows would probably need to add 2 to the rows attribute (not tested) to prevent the vertical scrollbar from showing, but up to 999 lines is most likely good enough for almost any situation.
Thank you.
Just set the height to auto before setting scrollheight and you are good to go
$textarea.css( 'height', 'auto' );
$textarea.css( 'height', $textarea[ 0 ].scrollHeight + 'px' );
Working Example:
const text = 'This is a line of text';
var $textarea = $( '#example' );
var i = 0;
$textarea.val( $textarea.val() + text );
for( var l = i + 5 ; i < l; ++i )
$textarea.val( $textarea.val() + "\r\n" + text + '(' + i + ')' );
$textarea.css( 'height', 'auto' ); //==========> Add this here
$textarea.css( 'height', $textarea[ 0 ].scrollHeight + 'px' ); //==========> Add this here
function doIt( This ) {
if( This.innerText !== 'Click Me Again' ) {
for( var l = i + 5 ; i < l; ++i )
$textarea.val( $textarea.val() + "\r\n" + text + '(' + i + ')' );
if( This.innerText === 'Click Me' ) {
This.innerText = 'Click Me Again';
$( 'p' ).text( 'to make the textarea\s width wider.' );
}
else {
$textarea.css( 'height', 'auto' ); // As per Mr Khan's sugestion.
$textarea.css( 'height', $textarea[ 0 ].scrollHeight + 'px' );
$( 'p' ).html( '<b>Why is there space below the last line of text?</b>' );
}
}
else {
This.innerText = 'Click Me Some More';
$textarea.css( 'width', ( $textarea.width() + 36 ) + 'px' );
$( 'p' ).text( 'to make the textarea\'s height taller and add more text.' );
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="doIt( this );">Click Me</button><br />
<p>to add more text to the textarea.</p>
<textarea id="example"></textarea>

How to retrieve old text and subtract from total - JS

This is a follow up question on an existing question. I am able to get total sub-price tof products that i selected and add up to get the grand total. Now, when an item is deselected, i want to subtract the price of the item being deselected from the existing grand total?
How do i get that done please?
When i try to get the oldtext, it is always 0 .. why is this happening?
HTML
<div class="panel" id="panel">
<div>
<div >
<p> class="mygoods" >Total: <span ></span></p>
</div>
JS
<script type="text/javascript">
function order(food)
{
var ad = JSON.parse(food.dataset.food);
if(food.checked == true) {
$('.panel').append(
'<div class="container" style=" font-size:14px; "> '+
'<p class="total" ><span class="sub-total" name="total" id="total"></span></p>'+
'<input size="50" type="text" class="form-control quantity" id="qty" placeholder=" qty " name="quantity[]" required/>'+
'</div>'
)
}
else{
var total = $(".panel .container [data-id=" + ad.id + "]").parent().find(".total").text();
$(".panel .container [data-id=" + ad.id + "]").parent().remove();
if (total) {
$('.mygoods span').text(function(oldtext) {
console.log('this is my old text '+oldtext)
return oldtext ? oldtext - total : oldtext;
});
}
}
}
$('.panel').on('keyup','.quantity',function()
{
var sum;
container = $(this).closest('div');
quantity = Number($(this).val());
price = Number($(this).closest('div').find('.price').data('price'));
container.find(".total span").text(quantity * price);
sum = 0;
$(".sub-total").each(function(){
sum = sum + Number($(this).text());
})
$('.mygoods span').text(sum);
});
</script>
$( '.mygoods span' ).text( function( oldtext ) {
console.log( 'this is my old text ' + oldtext )
return oldtext ? oldtext - total : oldtext;
} );
the .text method returns the parameters index and text - you only are retrieving one. Therefore the index is being stored in the oldtext variable, not the text.
Type: Function( Integer index, String text ) => String A function
returning the text content to set. Receives the index position of the
element in the set and the old text value as arguments.
http://api.jquery.com/text/
You can fix this by simply adding another parameter.
$( '.mygoods span' ).text( function(index, oldtext ) {
console.log( 'this is my old text ' + oldtext )
return oldtext ? oldtext - total : oldtext;
} );
I tried copying a snippet over to show you, but the code you provided is not enough to build anything. The attempted build is below.
function order( food ) {
var ad = JSON.parse( food.dataset.food );
if ( food.checked == true ) {
$( '.panel' ).append( '<div class="container" style=" font-size:14px; "> ' +
'<p class="total" ><span class="sub-total" name="total" id="total"></span></p>' +
'<input size="50" type="text" class="form-control quantity" id="qty" placeholder=" qty " name="quantity[]" required/>' +
'</div>' )
} else {
var total = $( ".panel .container [data-id=" + ad.id + "]" ).parent().find(
".total" ).text();
$( ".panel .container [data-id=" + ad.id + "]" ).parent().remove();
if ( total ) {
$( '.mygoods span' ).text( function( index, oldtext ) {
console.log( 'this is my old text ' + oldtext )
return oldtext ? oldtext - total : oldtext;
} );
}
}
}
$( '.panel' ).on( 'keyup', '.quantity', function() {
var sum;
container = $( this ).closest( 'div' );
quantity = Number( $( this ).val() );
price = Number( $( this ).closest( 'div' ).find( '.price' ).data( 'price' ) );
container.find( ".total span" ).text( quantity * price );
sum = 0;
$( ".sub-total" ).each( function() {
sum = sum + Number( $( this ).text() );
} )
$( '.mygoods span' ).text( sum );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel" id="panel">
<div>
<div>
<p class="mygoods"> Total: <span></span></p>
</div>
</div>
</div>

How to search and retrieve data from json file in Jquery?

I have a json file with below data.
{"student1":[{"id":1,"name":"Test Data1","email":"test1#g.com"}]}
{"student2":[{"id":2,"name":"Test Data2","email":"test2#g.com"}]}
{"student3":[{"id":3,"name":"Test Data3","email":"test3#g.com"}]}
{"student4":[{"id":4,"name":"Test Data4","email":"test4#g.com"}]}
And I use $.getJSON method to retrieve but data won't output. And I want to search data with Key like student3, then the data of student3 will have to output.
Here is my JQuery code.
$.getJSON( "test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Here is my Full Source Code.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Test Json</title>
</head>
<body>
<input type="text" name="name" id="name">
<input type="text" name="email" id="email">
<input type="button" name="submit" id="submit" value="Submit" onclick="submitForm()">
<input type="button" name="edit" id="edit" value="Edit" onclick="Edit()">
<br><br>
<div></div>
</body>
<script type="text/javascript">
function submitForm(){
var name = $("#name").val();
var email = $("#email").val();
var obj = {
table: []
};
obj.table.push({id: 1, name:name, email:email});
var json = JSON.stringify(obj);
$.ajax
({
type: "GET",
dataType : 'json',
url: 'save_json.php',
data: { data: json },
success: function () {alert("Thanks!"); },
failure: function() {alert("Error!");}
});
$("#name").val('');
$("#email").val('');
}
function Edit(){
$.getJSON( "general.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
}
</script>
</html>
You can try this code/syntax may not be correct....
searchParam would be 'Student3'..
$.getJSON( "test.json", function( data , searchParam ) {
var items = [];
var filterObj =data[searchParam];
if(filterObj != undefined)
{
var parsedData = Json.Parse(filterObj);
$.each( parsedData , function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
}
Please add below mentioned code.
$(document).ready(function(){
$.getJSON( "test.json", function(data) {
var items = [];
$.each( data, function( key, val ) {
$.each( val, function( key2, val2 ) {
items.push( "<li id='" + key2 + "'>" +val2[0].name + "</li>" );
});
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
});
also remove student1,student2 and use only student and find value
using key.
Your json data will be something like below.
[{"student":[{"id":1,"name":"Shyam","email":"test#g.com"}]},
{"student":[{"id":1,"name":"Niraj","email":"test#g.com"}]},
{"student":[{"id":1,"name":"Mehul","email":"test#g.com"}]},
{"student":[{"id":1,"name":"Ritesh","email":"test#g.com"}]}]
Let me know if it not works.

replace sub string in javascript string

I have a string in Javascript,
'WorkExperience_0_companydetails_0_name'
I want to get the following string
'WorkExperience_1_companydetails_1_name'
How could I achieve this in jQuery?
Try,
"WorkExperience_0_companydetails_0_name".split("0").join('1');
Or
"WorkExperience_0_companydetails_0_name".replace("0","1");
DEMO
as you want to update its value by 1
var str="WorkExperience_0_companydetails_0_name";
var ar = str.split("_");
var n=parseInt(ar[1],10)+1;
var newStr = str.replace(ar[1],n);
<ul>
<div class="test"></div>
<li id="foo1">foo</li>
<li id="bar1" class="test">bar</li>
<li id="baz1">baz</li>
<div class="test"></div>
</ul>
<div id="last"></div>
var foo = $( "li" );
// This implicitly calls .first()
console.log( "Index: " + foo.index( "li" ) ); // 0
console.log( "Index: " + foo.first().index( "li" ) ); // 0
var baz = $( "#baz1" );
console.log( "Index: " + baz.index( "li" )); // 2
var listItem = $( "#bar1" );
console.log( "Index: " + listItem.index( ".test" ) ); // 1
var div = $( "#last" );
console.log( "Index: " + div.index( "div" ) ); // 2`enter code here`

Jquery trying to remove dynamically made elements

I am using Jquery to dynamically add elements to my form and then remove them if necessary, I can do this when there is only one form being added, however my next form allows the user to add an ingredient and it adds a quantity element with it, I cant work out how to remove both the elements with a button. I have created a JSfiddle would be great if something could help.
http://jsfiddle.net/w5PKZ/
$(document).ready(function() {
var addDiv2 = $('#addIngredient');
var i = $('#addIngredient p').size() + 1;
$('#addNewIngredient').on('click', function () {
$('<p> <input id="step_' + i + '" size="40" name="ingredient[]' + '" type=text" value="" placeholder="Ingredient" /> </p>').appendTo(addDiv2);
$('<p> <input id="step_' + i + '" size="40" name="quantity[]' + '" type=text" value="" placeholder="Quantity" />Remove </p>').appendTo(addDiv2);
i++;
return false;
});
$(document).on('click','.remNew2', function () {
if (i > 3) {
$(this).parents('p').remove();
i - 2;
}
return false;
});
});
JSFIDDLE DEMO
Add the dynamic elements in a single paragraph <p> instead of 3 different paragraphs. This way you can keep your event handler AS IT IS.
$('#addNewIngredient').on('click', function () {
$('<p> <input id="step_' + i + '" size="40" name="ingredient[]' + '" type=text" value="" placeholder="Ingredient" /><input id="step_' + i + '" size="40" name="quantity[]' + '" type=text" value="" placeholder="Quantity" /> Remove </p> ').appendTo(addDiv2);
i++;
return false;
});
Try this
$(this).parent().prevAll(':lt(2)').remove().end().remove();
Your selection gets only the element "remove", you must also select the newly added using .prevAll()
Note: id's must be unique
DEMO
fiddle Demo
$(document).on('click', '.remNew2', function () {
if (i > 1) {
$(this).parents('p').prev().remove();
$(this).parents('p').prev().remove();
$(this).parents('p').remove();
i--;
}
return false;
});
try this
$('#addNewIngredient').on('click', function () {
console.log('clicked');
var newDiv = $("<div></div>");
$('<p> <input id="step_' + i + '" size="40" name="ingredient[]' + '" type=text" value="" placeholder="Ingredient" /> </p>').appendTo(newDiv);
$('<p> <input id="step_' + i + '" size="40" name="quantity[]' + '" type=text" value="" placeholder="Quantity" />').appendTo(newDiv);
$('<p> Remove </p>').appendTo(newDiv).click(function(){
newDiv.remove();
});
addDiv2.append(newDiv);
i++;
return false;
});
Updated fiddle http://jsfiddle.net/w5PKZ/10/
It is more efficient to build a basic tag and then individually add the arguments rather than passing in a long html string.
You can add the remove event handler directly to the individual anchors and pass in references to the elements you want removing if you do it all in the same scope as you create the elements:
JSFIDDLE
$(document).ready(function() {
var addDiv2 = $('#addIngredient');
var i = $('#addIngredient p').size() + 1;
$('#addNewIngredient').on('click', function () {
var p1 = $( '<p />' )
.appendTo(addDiv2),
p2 = $( '<p />' )
.appendTo(addDiv2),
p3 = $( '<p />' )
.appendTo(addDiv2),
ingredient = $( '<input />' )
.attr( 'id', 'ingredient_' + i )
.attr( 'size', '40' )
.attr( 'name', 'ingredient[]' )
.attr( 'type', 'text' )
.attr( 'placeholder', 'Ingredient' )
.val( $( '#ingredient_1' ).val() )
.appendTo( p1 ),
quantity = $( '<input />' )
.attr( 'id', 'quantity_' + i )
.attr( 'size', '40' )
.attr( 'name', 'quantity[]' )
.attr( 'type', 'text' )
.attr( 'placeholder', 'Quantity' )
.val( $( '#quantity_1' ).val() )
.appendTo( p2 ),
a = $( '<a />' )
.attr( 'href', '#' )
.text( 'Remove' )
.appendTo( p3 )
.on( 'click', function(e) {
p1.remove();
p2.remove();
p3.remove();
e.preventDefault();
// DO NOT DECREMENT i - you may get duplicate IDs
} );
i++;
return false;
});
});
You could also just add all the elements to p1 rather than creating multiple paragraphs (and it would be better semantically if you used div elements rather than p elements).

Categories

Resources