Why javascript press enter button no function? - javascript

I am working on a text field which is pressable with "enter" button but unfortunately it does not work. I am trying following code inside my project.
This is my JavaScript code:
<script>
$(document).ready(function() {
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").live("keyup", function(e) {
var theSearch = $('#search');
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 0));
};
});
});
$("#search").on('keyup',function(e){
var text = document.getElementById("search").value;
if(text !== ""){
if (e.which == 13){
$("#btnSearch").click();
}
}
});
function doSomething(){
var text = document.getElementById("search").value;
window.location.assign("search.php?value = " + text);
}
});
</script>
This is my HTML code:
<input type="text" id="search">
<input type="button" id="btnSearch" onclick="doSomething();" />

use unique selector id
$("#search").on('keyup',function(e){
if (e.which == 13){
alert('abc');
}
});
demo jsfiddle
use input type selector
$('input[type=text]').each(function(i,e) {
$("#"+e.id).on('keyup',function(e){
if (e.which == 13){
alert('abc');
}
});
});
another demo

Place $("input[type=text]").on... inside $(document).ready and make sure you are using JQuery version before 1.7 If you wish to use live

change your html to
<form onsubmit="doSomething();" >
<input type="text" id="search">
<input type="submit" id="btnSearch" />
</form>
while using this you don't have to listen enter key event your doSomething() function will be called automatically on enter press in input field
DEMO

Related

Input values are still accessible after a form reset via ajax call

I am faced with a problem which is a real disaster. After I click the send button to send variables via Ajax to my PHP page, a form reset will get triggered in success response. But the input values are liked to be cached, so when I click the send button while inputs are empty, it resends the previous inserted values.
Moreover, I have disabled the form submission event to prevent submitting the form.
Here is the sample code:
<body>
<form id="myform">
<input class="area" type="text"></input>
<input class="area" type="text"></input>
<input class="area" type="text"></input>
<button id="add">Add</button>
</form>
<div class="response"></div>
</body>
$(document).ready(() => {
$(document)
.off()
.on("click", "#add", function (e) {
e.preventDefault();
var area = $(".area");
area.each(function (i) {
if ($(this).val()) {
var x = $(this).val();
areadim.splice(i, area.length, x);
}
});
$.ajax({
type: "POST",
url: "addsettings.php",
data: {
area: area,
},
beforeSend: function () {
if (areadim.length == 0) {
alert("fill up all inputs");
currentRequest.abort();
} else if (areadim.length <= area.length) {
$.each(area, function () {
if ($(this).val() < 100) {
alert("input is less than 100");
currentRequest.abort();
}
});
}
},
success: function (response) {
$("#myform").trigger("reset");
$(".response").append(response);
$(".area").val("");
},
});
});
});

How to create search button for existing code which execute search on enter press? php/javascript/mysql

I have a website which someone else have been coding for me and i'm trying to understand how to change a simple thing.
I am not webdeveloper but on the last days I got familiar a bit with php, mysql and javascript (i'm familiar with java).
****The Question:****
On my website I have search form which works without search button (search function works on enter press or when choosing from autocomplete). How do i change it to work only with search button ?
The web developed with framework called CodeIgniter.
This is how controller looks like:
public function searchGym()
{
if($_POST)
{
$gym_name=$_POST['gym_name'];
$gym_name=trim($gym_name," ");
$data['details']=$this->user_model->getGymByName($gym_name);
$data['gym_name']=$gym_name;
$this->load->view('he/searched_gym',$data);
}
}
This is how model look like:
public function getGymByName($query_string)
{
$query_string=mysql_real_escape_string($query_string);
$query=$this->db->query("select * from gym_members_table where member_title like '%$query_string%'");
return $query->result_array();
}
</code>
And this is the index.php search form :
<div class="search-home">
<input type="text" onkeypress="gymhandle(event);" class="form-control gym_search" id="gym" name="gym" placeholder="
Search by Name
" >
<div class="autosuggest1"></div>
<div class="autosuggest"></div>
</div>
<script>
function settextbox(rval){
$('.autosuggest').hide();
$('#gym').val(rval);
$('#gym_search2').val(rval);
searchGymByName(rval);
}
$(document).ready(function(){
$('.autosuggest').hide();
$('#gym').keyup(function(e)
{
var code = (e.keyCode || e.which);
// do nothing if it's an arrow key
if(code == 37 || code == 38 || code == 39 || code == 40 || code==13) {
return;
}
var search_term = $(this).val();
var getdata = { 'search_term': search_term};
if(search_term!=''){
$.ajax({
url: "<?php echo site_url('hebrew/searchGymAuto');?>",
data: getdata,
type: 'POST',
success: function(data){
$('.autosuggest').show();
$('.autosuggest').html(data);
}
});
}
else
{
$('.autosuggest').hide();
}
});
});
$('.autosuggest').hide();
function searchGymByName(rval)
{
$('.autosuggest').hide();
var gym_name=rval;
$.ajax({
url:"<?php echo site_url();?>hebrew/searchGym",
type: "POST",
data:{gym_name: gym_name},
success:function(res){
$('html, body').animate({ scrollTop: 0 }, 0);
$("#ajax-map").hide();
$("#city").val('');
$("#city1").val('');
$("#ajax-page-hide").show();
$("#ajax-page-hide").html(res);
}
});
}
Thanks!!
You can cancel the enter keypress on those fields like this:
$('.gym_search').keypress(function(e){
if ( e.which == 13 ) return false;
//or...
if ( e.which == 13 ) e.preventDefault();
});
Remove the id attribute from the search input field, and place id="gym" on the search button. And then in $('#gym').click(function(e) [note: 'click' instead of 'keyup'], change the search_term to
var search_term = $("gym_search").val();
Remove onkeypress event from text box. Add ajax call for search in java script function and call that function on button click event

prevent form submission from enter button

i have a live chat messaging system whenever user press enter button it refreshes the page i have tried using prevent default code also but did not worked for me.... here is the code and if there is any problem in the below code please let me know as i'm totally new to website programming
jQuery(document).ready(function() {
jQuery('.btn-success').click(function() {
var form_name = jQuery(this).attr('title');
var obj = jQuery(this);
jQuery(".ajax_indi").show();
switch (form_name) {
case "npost":
var message = jQuery("#message").val();
break;
default:
alert("something went wrong!");
}
if((jQuery(message) == ''))
{
alert("Message Cannot be Empty");
jQuery(".ajax_indi").hide();
return false;
} else {
jQuery(this).attr("disabled", "disabled");
jQuery(this).prop('value', 'Loading...');
jQuery(this).css('cursor', 'default');
}
var str = jQuery("#"+form_name).serialize();
jQuery.ajax({
type: "POST",
url: "chat.php",
data: str,
cache: false,
success: function(html){
jQuery('#chat1').append(html);
obj.attr("disabled", false);
obj.prop('value', 'Post');
obj.css('cursor', 'pointer');
jQuery(".ajax_indi").hide();
document.getElementById(form_name).reset();
}
});
});
});
Edited part
<form id="npost" name="npost">
<input class="form-control" placeholder="Type your message here..."
type="text" name="message">
<input type="hidden" name="id" value="1">
<span class="input-group-btn">
<button type="button" class="btn btn-success" title="npost" >Send</button>
if you want to prevent from submitting the form you can use return false if you want to stop executing the function and stop submitting it
You need to use preventDefault in order to stop form submission on clicking enter because by default form gets submitted when anyone presses enter. So use preventDefault like this:
<script type="text/javascript" >
jQuery(document).ready(function(){
jQuery('.btn-success').click(function(e){ // added e
e.preventDefault(); // added this line
var form_name = jQuery(this).attr('title');
var obj = jQuery(this);
jQuery(".ajax_indi").show();
var message = '';
switch (form_name)
{
case "npost":
var message = jQuery("#message").val();
break;
default:
alert("something went wrong!");
}
if((jQuery(message) == ''))
{
alert("Message Cannot be Empty");
jQuery(".ajax_indi").hide();
return false;
} else {
jQuery(this).attr("disabled", "disabled");
jQuery(this).prop('value', 'Loading...');
jQuery(this).css('cursor', 'default');
}
var str = jQuery("#"+form_name).serialize();
jQuery.ajax({
type: "POST",
url: "chat.php",
data: str,
cache: false,
success: function(html){
jQuery('#chat1').append(html);
obj.attr("disabled", false);
obj.prop('value', 'Post');
obj.css('cursor', 'pointer');
jQuery(".ajax_indi").hide();
document.getElementById(form_name).reset();
}
});
});
});
</script>
Here You should not stop form default action you to prevent enter key default answer here is the code to prevent.
$('#npost').on('keyup keypress', function(e) {
if (e.which== 13) {
e.preventDefault();
return false;
}
});

How to press "Enter" to redirect to other page?

I am working on search function which I did it well to get what result I want. I have a search text field which can allow user to key in the value and JavaScript will help me get the relevant data for the text field value. Now I want my text field can be function when I press on it using button "Enter". Once I press on "Enter" button, it will redirect me to a new page which shows all the relevant data of the keyword I key in in the text field.
This is my JavaScript and HTML code inside HTML page:
<script>
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 0));
};
});
});
</script>
SEARCH<input type="text" id="search" autocomplete="off">
<ul id="results" style="display:none"></ul>
After keyin value inside the text, JavaScript will call search.php to get all the relevant data. But I can't click on text field to show all value. Hope you guy can give me a solution to work on it. Thanks in advanced.
Try this and use jQuery 1.8 or minimum.
$("input#search").live("keyup", function(e)
if(e.which == 13) {
//perform your operations
}
});
You could make it a form so that it would submit when the user hits enter.
<form method="get" action="search page.php" onsubmit="return validate();">
SEARCH<input type="text" id="search" autocomplete="off">
<ul id="results" style="display:none"></ul>
</form>
<script type="text/JavaScript">
function validate() {
//If the form value is "" (nothing)
if (document.getElementById("search").value == "") {
return false; //Stop the form from submitting
}
return true;
}
</script>

Enter key to submit Ajax form

I have a very simple AJAX form that asks for an email address and sends it to me after submitting.
How can I can I get the form to submit when hitting the enter key?
This runs when user clicks submit button:
<script type="text/javascript">
$(document).ready(function () {
$("#submit_btn").click(function () {
// Get input field values:
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
// Everything looks good! Proceed...
if (proceed) {
/* Submit form via AJAX using jQuery. */
}
});
// Reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function () {
$("#contact_form input, #contact_form textarea").css('border-color', '');
$("#result").slideUp();
});
});
</script>
I know this question has been asked before -- I'm having trouble getting the keypress function to work.
I tried this to no avail:
$("#contact_form").keypress(function (e) {
if ((e.keyCode == 13) && (e.target.type != "textarea")) {
e.preventDefault();
// Get input field values
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
// Everything looks good! Proceed...
if (proceed) {
/* Submit form via AJAX using jQuery. */
}
}
});
The form is #contact_form.
Any help would be would appreciated…
Just bind the submit event to your form, and then the enter key will also work:
$("#contact_form").submit(function (e) {
e.preventDefault();
// Get input field values
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
if (proceed) {
// Insert the AJAX here.
}
});
And the code is here: http://jsfiddle.net/6TSWk/6/
add new class in every fieldbox or checkbox => class keypressbutton
then replace your code on keypress with this, below :
$(document).on("keypress",".keypressbutton",function(event) {
var keyCode = event.which || event.keyCode;
if (keyCode == 13) {
$("#submit_btn").click();
return false;
}
});
$("#myform").keypress(function(event){
if(event.keycode===13){ // enter key has code 13
//some ajax code code here
//alert("Enter key pressed");
}
});
You have two opening brackets in your if statement and miss a closing bracket. Also, I would change e.target.type. Try this:
$("#contact_form").keypress(function (e) {
if ((e.keyCode == 13) && ($('input[name="email"]').is(':focus'))) {
e.preventDefault();
//get input field values
var user_email = $('input[name=email]').val();
//simple validation at client's end
//we simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
}
});
Instead of using button on click function you can use submit button.
Load the validate.js file
function validateEmail(email)
{
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(email))
{
return true; }
else{
return false;
}
}
$("#test-form").validate({
submitHandler: function(form) {
//form.submit();
var email=$("#email").val();
if(email=='' )
{
// Here you can type your own error message
$('#valid').css("display","none");
$('#empty').css("display","block");
return false;
}
if (!(validateEmail(email))) {
$('#empty').css("display","none");
$('#valid').css("display","block");
return false;
}
else {
$.ajax({
url: "signup.php",
type: form.method,
data: $(form).serialize(),
success: function(response) {
}
});
}
}
});
});
Simple way is this:
In HTML codes:
<form action="POST" onsubmit="ajax_submit();return false;">
<b>First Name:</b> <input type="text" name="firstname" id="firstname">
<br>
<b>Last Name:</b> <input type="text" name="lastname" id="lastname">
<br>
<input type="submit" name="send" onclick="ajax_submit();">
</form>
In Js codes:
function ajax_submit()
{
$.ajax({
url: "submit.php",
type: "POST",
data: {
firstname: $("#firstname").val(),
lastname: $("#lastname").val()
},
dataType: "JSON",
success: function (jsonStr) {
// another codes when result is success
}
});
}

Categories