Building real time commenting feature - javascript

I am trying to add real time comment feature to all posts user timeline page.
Here is what i have done:
All Posts contain comment section having following html form:
<form action="#" class='post-comment' data-id='3214'>
<input type="text" name='comment'>
<input type='submit' style='visibility: hidden;'>
</form>
Here is my Javascript code which handles the form submit event:
$(".post-comment").on('submit', function(e){
e.preventDefault(); //STOP default action
var id = $(this).attr("data-id");
console.log('Comment on: '+id);
var dbref = firebase.database().ref('post-user/'+id+'/comments');
var data = $(this).serialize();
var t = Date.now();
dbref.push().set({
postedAt: t,
text:data.comment,
pid:id
});
})
After making some input as comment when user presses the enter key then the web page reloads instead of invoking function in Javascript.
I want to get comment data and corresponding post details(id,authorid) and send comment data to firebase on enter key press.
After doing some searches i came to know about key press events as below:
$("input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("form").submit();
}
});
But in this case i have multiple forms that is every post contains corresponding comment form so i am confused how to implement this here.
Any help will be appreciated.

Give your form an id:
<form id='comment-form' action="#" class='post-comment' data-id='3214'>
Then submit just that form:
$("input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("#comment-form").submit();
}
});

Related

How to trigger an event when use enter key for html

I want to send message when I use the enter key but it not working
for my html
<form id="form">
<textarea type="text"></textarea>
<input type="submit" value="Send">
</form>
for my js
const sub = document.getElementById('form');
// send message when hit
sub.addEventListener('submit', send);
// use enter to send message
sub.addEventListener("keypress", (event)=> {
if (event.keyCode === 13) {
send();
}
});
function send(event) {
Also, I keep getting 'keyCode' is deprecated this error message
This is not working, someone help? Thank you in advance!
I have made adjustment to your code and added the event.preventDefault(). The PreventDefault() is used to prevent the default action belonging to that even from happening.
I Have also used the event.which to get the keycode of the enter key
const sub = document.getElementById('form');
// send message when hit
sub.addEventListener('submit', send);
// use enter to send message
sub.addEventListener("keypress", (event)=> {
if (event.which === 13 ) {
//this will prevent the normal behavior of going to a new line when the enter button is pressed
e.preventDefault()
send();
}
});

Form authentication with redirect to another internal url JQuery

I have this code and I need to validate the authentication and submit the form with redirect to another internal URL when I click a button called "go there".
In my code, I need the submit part. Can I find help, please?
jQuery(document).ready(function(e) {
$('#btn-login').click(function(){
var errorCount = 0;
$('#login-wrap input').each(function(){
if($(this).val() === '') {
var errorMsg = 'Please fill '+ $(this).prev('label').text();
$(this).next('.errorMessage').text(errorMsg);
errorCount += 1;
}
});
if (errorCount === 0) {
$('#myModal').modal('show');
}
return false;
});
// Open new tab on click
$('#btn-gothere').click(function(){
$('#myModal').modal('hide');
window.open($(this).data('url'));
});
});
You can set a listener on your <form> to look for submit event.
If it is triggered then prevent it from submitting, validate your input and if they are valid submit this form manually.
Of course you don't have to look form submit event on <form>. You can still use your click event but you will have to provide form for submit method.
// listen on form submit
$('#form').on('submit', event => {
// prevent form from submitting
event.preventDefault();
// save target to variable (target is our form)
const form = event.target;
// check if form is valid
if(isFormValid()) {
// if form is valid then submit it and user will be moved to location provided in "action" parameter with all data from this form
form.submit();
}
});
// yes it is
const isFormValid = () => true;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" action="/some/url" method="POST">
<button type="submit">Submit</button>
</form>

HTML Form: How to remember text values of button click?

If you have a form, type some text into it, and press the Enter key, whenever revisiting that form you can double-click on the input box and see the past text submissions.
I have a site that when you press Enter OR click a button, it should take whatever is in the text box and use it for data processing.
This works totally fine when not surrounded by a form but when surrounded by a form an you press the Enter key, it does not act as an enter button push, I believe it's being overridden by the form.
My goal is to have the user be able to press the Enter key as well as click the button to submit the data, but to also remember the text values that were in the text box regardless of which way you submitted the data.
What I have:
<input type="text" id="username-field" class="form-control" placeholder="username">
<input class="btn btn-default" type="button" id="get-name" value="Get Name">
Javascript
$("#get-name").click(function() {
var name = $("#username-field").val();
// ... call other function with name ...
});
$("#get-name").keydown(function(e) {
if (e.which == 13) {
var name = $("#username-field").val();
// ... call other function with name ...
}
");
What I would like to use:
<form>
<input type="text" id="username-field" class="form-control" placeholder="username">
</form>
I tried doing e.preventDefault() when the Enter key is pressed, but this does not remember the text in the input field.
I also considered doing a small cache type thing but am unsure of how I'd go about this.
Any help would be much appreciated!
Thanks!
Doesn't use form at all. Just, why you added it, if you don't use it as intended?
You either mistyped provided code copy-paste, or have errors in yours script (the $("#get-name").val() mistake).
If you want to prevent form from submission, you should e.preventDefault()-it in submission handler, and return false from it:
$('#form-id').submit(function (e) {
e.preventDefault();
// do smth. else here
...
return false;
})
Saving/retriving data with localStorage for HTML5-supporting browsers:
$(function () {
$('form input[type=text]').doubleclick(function () {
var id = $(this).attr("id");
value = localStorage.getItem("form_xxx_" + id);
// do smth. with cached value, ie:
if (value != "")
$(this).val(value); // put in textfield
});
});
$('form').submit(function (e) {
$('form input[type=text]').each(function () {
var id = $(this).attr("id");
localStorage.setItem("form_xxx_" + id, $(this).val());
});
...
// all other work
});
Note: make sure you don't put some user's personal data in browser's local storage -_-

Pressing 'enter' on a input type="text", how?

I am facing a problem I can not solve JQuery Javascript. Can you help me and help me understand.First here is my code :
(...)
<script type="text/javascript">
// Autocomplete suggestions
$(function () {
$("#autoCompInput").autocomplete({
source: "/Suggestions",
minLength: 3,
select: function (event, ui) {
if (ui.item) {
$("#autoCompInput").val(ui.item.value);
$("form").submit();
}
}
});
});
// Provide search results
$(function () {
$("#autoCompSearch").click(function () {
var searchParameters = $("#autoCompInput").val();
var jsonData = JSON.stringify(searchParameters, null, 2);
window.location = "/Search?criteria=" + searchParameters;
});
});
</script>
(...)
<input class="ui-autocomplete-input" id="autoCompInput" role="textbox" aria-haspopup="true" size="50" autocomplete="off" aria-autocomplete="list" value = "#ViewBag.SearchInfo"/>
<a id= "autoCompSearch" href = "#" ><img src="#Url.Content("~/Content/Menu/Images/magnifier.png")" alt="Search" /></a>
(...)
With this code I can't use the 'Enter' key to execute my search. When the user is in the input autoCompInput I would like to be able to detect if he press 'enter' and launch the submit. I read I must add a onkeyup="onKeyPressed(event)" event but I don't understand how to write the javascipt associated with the command. I tried but without success... Do you have a solution for me?
Thank you,
You should bind the keypress event to your input
$("#autoCompInput").bind("keypress", {}, keypressInBox);
function keypressInBox(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //Enter keycode
e.preventDefault();
$("yourFormId").submit();
}
};
With similar HTML:
<input type="text" id="myTxt" />
<input type="submit" id="mySubmit" />
This script (which uses the latest jQuery 1.7.2) should do it:
$('#mySubmit').click(function() {
alert('Submitted!');
return false;
});
$('#myTxt').on('keyup', function(e) {
if (e.keyCode === 13) {
$('#mySubmit').click();
}
});
Here's a working example.
To assign a keyup event in jquery
$("#autoCompInput").keyup(function(event) {
if (event.keyCode==13) {
alert('enter key');
}
});
I think there is a better and more standard solution to this type of problem.
you can have a GET form around those inputs and whenever you press enter on any input inside that form, it will be submitted to whatever is in the action attribute of the form. This is how it would look like (I took your code but I am removing the bits irrelevant for my answer):
<form id="idForJqueryOnly" action="/Search" method="GET">
<input type="text" name="criteria" value="someuserinput"/>
<button type="submit"><img src="...")" alt="Search" /></button>
</form>
This is standard browser behaviour. So, what the form does? when submitted the browser creates a URL like this:
http://yourserverguesedfromthecurrenturl/Search?criteria=someuserinput
What happened is that the browser took all the inputs with name and value (and not disabled) from the form and serialized them into url form.
Now, the submit event can be triggered by pressing enter on any of the inputs inside, including buttons as long as the buttons don't have the attribute type="button".
If you wanted to do more things with the data with javascript before going to the search page, you can do this with jquery:
$("#idForJqueryOnly").submit(function(){
// here you can do stuff like serialize the form, or sanitize the input of tue user.
var data = $("#idForJqueryOnly").serialize();
$("[name=criteria]").val($("[name=criteria]").val().customSanitizeMethod());
// if you return false, the form will not submit, say, for validation errors:
return customValidator.isFormValid("#idForJqueryOnly");
})

Clear an input field after submission using JavaScript

I am a JavaScript newbie. I have an input text field that I wish to clear after pressing the form submit button. How would I do that?
In your FORM element, you need to override the onsubmit event with a JavaScript function and return true.
<script type="text/javascript">
function onFormSubmit ()
{
document.myform.someInput.value = "";
return true; // allow form submission to continue
}
</script>
<form name="myform" method="post" action="someaction.php" onsubmit="return onFormSubmit()">
<!-- form elements -->
</form>
If a user presses the submitbutton on a form the data will be submitted to the script given in the action attribute of the form. This means that the user navigates away from the site. After a refresh (assuming that the action of the form is the same as the source) the input field will be empty (given that it was empty in the first place).
If you are submitting the data through javascript and are not reloading the page, make sure that you execute Nick's code after you've submitted the data.
Hope this is clear (although I doubt it, my English is quite bad sometimes)..
function testSubmit()
{
var x = document.forms["myForm"]["input1"];
var y = document.forms["myForm"]["input2"];
if (x.value === "")
{
alert('plz fill!!');
return false;
}
if(y.value === "")
{
alert('plz fill the!!');
return false;
}
return true;
}
function submitForm()
{
if (testSubmit())
{
document.forms["myForm"].submit(); //first submit
document.forms["myForm"].reset(); //and then reset the form values
}
}
First Name: <input type="text" name="input1"/>
<br/>
Last Name: <input type="text" name="input2"/>
<br/>
<input type="button" value="Submit" onclick="submitForm()"/>
</form>
After successfully submitting or updating form or password you can put empty value.
CurrentPasswordcontroller.state.confirmPassword = '';

Categories