keydown event delete my div content - javascript

In my JavaScript file I created 2 events;
Key-down and click;
When you click on the button or press Enter, the text written in input field is show up in a div text area; This code works for the button click event but doesn't work correctly in key-down event.
HTML code:
<div id="chatarea">
<div id="jqarea">
<div class="chatboxcontent"></div>
</div>
</div>
<div class="chatbox">
<input type="hidden" name="cfrom" id="cfrom" value="<?php echo $cuser; ?>" ></input>
<p><input type="text" name="digit" id="digit" size="50"/></p>
<p><button class="btn" title="send" type="button">
<span>Send</span>
</button>
</p>
</div>
Javascript code
$("#digit").keydown(function(event){
if (event.which == 13) {
filltxtarea($("#digit").val());
}
});
$(".btn").click(function(){
filltxtarea($("#digit").val());
});
function filltxtarea(desctext) {
var uchat = $("#cfrom").val();
//$(".chatboxcontent").append('<div class=chatboxmessage><span class="chatboxmessagefrom">' + uchat + ': </span><span class="chatboxmessagecontent">' + desctext + '</span></div>');
$('#digit').val('');
$('#digit').focus();
$.post('chat.php','action=newrow&message='+desctext,function(data){
if (data==='failed'){alert("error in mysqli")};
});
}
});
function chatHeartbeat(){
$.ajax({
url: 'chat.php?action=chatheartbeat',
dataType: 'json',
cache: false,
success: function(data) {
alert("0");
$.each(data.items, function(i,item){
if(item){
alert("1");
$(".chatboxcontent").append('<div class=chatboxmessage><span class="chatboxmessagefrom">'+item.f+': </span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
}
});
}
});
setTimeout('chatHeartbeat();',1000);
}
When I use click anything work and I can see alert(1) and alert(2) but with key-down it create a new row in the db but I have only alert(0).... How can this be possible??? Any idea????

Did you try prevent default, sometimes with enter key you can have unwanted behavior:
$("#digit").keydown(function(event) {
if (event.which == 13) {
event.preventDefault();
filltxtarea($("#digit").val());
}
});

Related

Handle the enter key press? [duplicate]

This question already has answers here:
Detect the Enter key in a text input field
(12 answers)
Closed 5 months ago.
Im modifying someones code so a little bit lost!
I have a html page with a textbox and button (which performs a search)
Is it possible to perform the search when Enter is pressed on the keyboard?
thanks
P
<div class="col-md-12">
<div id='FAQHome'><h3><a href='newFAQ.aspx'>FAQ HOME</a></h3></div><br><br>
<input id="searchBox" class="searchBox" />
<input id="searchButton" class="searchButton" type="button" value="SEARCH" />
<div id="financialServices" class="mainText"></div>
</div>
<script>
window.document.onkeydown = CheckEnter;
function CheckEnter(){
console.log('CheckEnter' + event.keyCode);
}
$(function(){
$('#searchButton').click(function() {
$('#financialServices').empty();
//do the ajax call ...
$.ajax ({
url: _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getbytitle('FAQs')/items?$top=100&$orderby=Category,Title asc",
dataType: 'json',
async: false,
headers: { "Accept": "application/json;odata=verbose" },
success: function(data) {
var htmlMain = '';
var tabContent = '';
var theCount=0;
//search
console.log('get search results');
for(var result in data.d.results) {
etc ...
You can use Keypress Event in jQuery and JQuery keyCode.
jQuery keypress Event reference : https://api.jquery.com/keypress/
jQuery key code reference : https://www.educba.com/jquery-keycode/
Use Like:
$( "#searchBox" ).keypress(function( event ) {
if ( event.which == 13 ) {
get_Search();
}
});
});
Full code :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="col-md-12">
<div id='FAQHome'><h3><a href='newFAQ.aspx'>FAQ HOME</a></h3></div><br><br>
<input id="searchBox" class="searchBox" />
<input id="searchButton" class="searchButton" type="button" value="SEARCH" onclick="get_Search()" />
<div id="financialServices" class="mainText"></div>
</div>
<script>
$(document).ready(function(){
//use key press event
$( "#searchBox" ).keypress(function( event ) {
if ( event.which == 13 ) {
get_Search();
}
});
});
function get_Search() {
$('#financialServices').empty();
//do the ajax call ...
$.ajax ({
url: _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getbytitle('FAQs')/items?$top=100&$orderby=Category,Title asc",
dataType: 'json',
async: false,
headers: { "Accept": "application/json;odata=verbose" },
success: function(data) {
var htmlMain = '';
var tabContent = '';
var theCount=0;
//search
console.log('get search results');
}
});
}
</script>
I would suggest that you wrap your input fields in a form element.
<form>
<div class="col-md-12">
<div id='FAQHome'><h3><a href='newFAQ.aspx'>FAQ HOME</a></h3></div>
<br><br>
<input id="searchBox" class="searchBox" />
<input id="searchButton" class="searchButton" type="submit" value="SEARCH" />
<div id="financialServices" class="mainText"></div>
</div>
</form>
...

How to get the button to work on keyboard Enter?

I'm trying to get the button to work without clicking on it.
I tried but with using 'Submit' and 'button', neither works unless user clicks the button.
<input id="txtDusNumber" class="form-control form-control-sm" type="text" />
<input type="submit" name="submit" class="btn " value="Search" id="enter-btn" onclick="ShowCard()" />
<input type="button" class="btn " value="Search" onclick="ShowCard()" />
<script>
function ShowCard() {
var dusNumberVal = $('#txtDusNumber').val();
if (dusNumberVal) {
$.ajax({
url: "#Url.Action("display","Card")",
data: { number: dusNumberVal },
type: 'GET',
success: function (result) {
$('#results').html(result);
},
error: function () {
alert("error...");
}
});
} else {
alert('Please enter Number.');
}
}
</script>
Try this:
$(document).keypress(function(e) {
if(e.which == 13) {
ShowCard();
}
});
function ShowCard(){
...
}
What it does is when the page is loaded, once you press enter, the ShowCard function gets executed.
Wrap <button type="submit"> in <form> tag

search form doesn't submits

I have this search form:
JSFIDDLE
and it doesn't submits. When I click to enter or search icon. why?
<form action="/search.php" method="get">
<fieldset>
<ul class="toolbar clearfix">
<li><button type="submit" id="btn-search"><span class="fa fa-search" style="color:gray;"></span></button></li>
<li><input type="search" id="search" placeholder="" name="s"></li>
</ul>
</fieldset>
</form>
$(document).ready(function() {
$('#btn-search').on('click', function(e) {
e.preventDefault();
$('#search').fadeIn().focus();
});
});
Because you are preventing form submit with e.preventDefault()
and not submitting form with any other methods.
You can submit your form using ajax like this:
$('#btn-search').on('click', function(e) {
e.preventDefault();
if( $('#search').val() ){
$.ajax({
url : 'submit.php',
data : { 'input': $('#search').val() },
success : function( response ) {
alert( response );
}
});
}
$('#search').animate({
width: 'toggle',
}).focus();
});
and write submit functions in submit.php
Inside submit.php you can write what you need to do with user input. Something like this:
<?php
echo "You have entered: " . $_GET['input'];
?>
Hope this helps..

Submit form via Enter key and Submit button both

Hi I have form and following things are bothering me:
1. Form does not submit on pressing enter.
2. When i press enter in input field then Search Now button needs to be pressed
twice to search places.
Form is displayed as below:
<form method="POST" id="mylocform" action="">
<h3 class="animated slideInLeft delay-2">
<input type="text" placeholder="Start Typing Your Location" id="geocomplete"
style="color:black;width:100%;padding:5px;height:45px;border-radius:5px"
autocomplete="off" class="chkmeloc" onblur="checkmylocform()"/></h3>
<input type="submit" class="btn btn-default btn-lg animated fadeInUpBig delay-3"
style="color: black;background-color: #FFF;border-color: #FFF;"
value="Search Now!"/>
</form>
Validation goes like below:
$(document).ready(function(){
$("form#mylocform").submit(function(event) {
event.preventDefault();
validate();
});
});
function checkmylocform(){
var checkOdlen = $(".chkmeloc").val().length;
if(checkOdlen==0){
$(".chkmeloc").css("border-color","#F05F68");
$(".chkmeloc").focus();
$(".chkmelocmess").html('<button type="submit" class="btn btn-default
btn-lg" style="background: #FFF;color:red">
<i class="fa fa-warning text-red"></i>
Select Your Location</button>');
return false;
}
else{
$(".chkmeloc").css("border-color","#0C9");
$(".chkmelocmess").html('<input type="submit" class="btn btn-default
btn-lg" style="color: black;background-color: #FFF;border-color: #FFF;"
value="Search Now!"/>');
return true;
}
}
function validate(){
$.each($('form :input'),function(){
$(this).blur().change();
});
if(!checkmylocform()){
return false;
}
else{
submitform();
}
}
Submit Form has code to submit form via ajax as below. Please help me to get out of this situation.
$("Your selector").keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
$(input[type = submit]).click();
return false;
}
});
look at this site:
http://tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/
the site says that enter key is automaticly a submit in al browser
Try This
File index.html :
<form class="form-inline" action="" method="POST">
<input type="password" name="token" placeholder="Enter Facebook access token..." class="subscribe-email">
<button type="submit" class="btn">Start!</button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
File script.js :
$('.get_token form').submit(function(e) {
e.preventDefault();
var postdata = $('.get_token form').serialize();
$.ajax({
type: 'POST',
url: 'assets/submit_token.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 0) {
$('.success-message').hide();
$('.error-message').hide();
$('.error-message').html(json.message);
$('.error-message').fadeIn();
}
else {
$('.error-message').hide();
$('.success-message').hide();
$('.get_token form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
}
});
});

How to prevent repeat sending ajax jQuery?

I have a button
<span class="btn btn-primary" id="open-label"><i class="icon-plus icon-white"></i> Add label</span>
which open modal window (http://twitter.github.com/bootstrap/javascript.html#modals)
<div id="ajax-labels"></div>
<div id="labels-modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="header">Add label</h3>
</div>
<div class="modal-body">
<div class="control-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<input type="text" id="name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="color">Color</label>
<div class="controls">
<input type="text" id="color" name="color" value="#a5f3d4" size="6" class="iColorPicker" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="submit-label"><i class="icon-ok icon-white"></i> Add label</button>
</div>
</div>
<script>
function append_labels() {
$("#ajax-labels").empty();
$.ajax({
url: "/ajax",
type: "POST",
cache: false,
data: {
type: "get_labels"
},
success: function (html) {
labels = $.parseJSON(html);
$.each(labels, function () {
$("#ajax-labels").append('<span class="label" id="' + this.id + '" style="background-color: ' + this.color + '">' + this.name + '<i id="edit-label" class="icon-pencil icon-white"></i></span> ');
});
}
});
}
$('span#open-label').click(function () {
$('#labels-modal').modal('show');
$('#labels-modal #submit-label').click(function () {
$('#labels-modal #submit-label').prop('disabled', true);
var name = $('#labels-modal #name').val().trim();
var color = $('#labels-modal #color').val().trim();
if (name != '' || color != '') {
$.ajax({
url: "/ajax",
type: "POST",
cache: false,
data: {
type: "add_label",
name: name,
color: color
},
success: function () {
$('#labels-modal').modal('hide');
append_labels();
}
});
} else {
return false;
}
});
});
</script>
After filling labels, user click on "Add label" and jquery send request, after sending, script close modal and refresh (on ajax) labels list. Question - if user quick clicks on "Add label", script send form repeatedly and i responce doubles in database. How I Can prevent this?
Try using one
$('span#open-label').one('click', function () { //...
This will guarantee your modal/ajax function will execute only once.
Disable the form and button on the first click so that the UI does not allow additional clicks. You can do this manually, or use the jQuery Block UI plugin.
Here is another post on how to do this: jquery disable submit button on form submission
Edit:
You are defining a event handler inside of a click handler. So what jQuery is doing is assigning that event handler each time the containing click is fired. So depending on how many times the top level click was executed, will be how many times your AJAX call will fire. Even though it is only 1 click of your button, the previous clicks are the culprit. Extract that click handler definition to outside of the other and you should be good to go.
$('span#open-label').click(function () {
$('#labels-modal').modal('show');
});
$('#labels-modal #submit-label').click(function () {
$('#labels-modal #submit-label').prop('disabled', true);
var name = $('#labels-modal #name').val().trim();
var color = $('#labels-modal #color').val().trim();
if (name != '' || color != '') {
$.ajax({
url: "/ajax",
type: "POST",
cache: false,
data: {
type: "add_label",
name: name,
color: color
},
success: function () {
$('#labels-modal').modal('hide');
append_labels();
}
});
} else {
return false;
}
});
Add this to the click handler
$('span#open-label').click(function () {
if( ($(this).attr('clicked') == '1') ) {
/* do something else then */
return;
}
$(this).attr('clicked', '1');
$('#labels-modal').modal('show');
This way, the next time you click you could show an alert.
If you want to "re-activate" the "open-label", you just do this :
$('span#open-label').attr('clicked', '0');

Categories

Resources