jQuery on keypress console log input value - javascript

Having a weird minor little issue with submitting an input field on a keypress event - specifically enter.
Following is my js code:
$(document).ready(function() {
$('#findMyCouncillor').on('keypress', function (event) {
var keycode = event.keyCode || event.which;
if(keycode == '13') {
var search = $(this).val();
console.log(search);
}
});
});
And relevant html:
<div class="input-group mb-3">
<input id="findMyCouncillor" type="text" class="form-control" placeholder="Search....">
<div class="input-group-append">
<span class="input-group-text"><i class="fas fa-search"></i></span>
</div>
</div>
The issue is that console.log(search); is working - but search is empty. console.log(typeof search) returns string - but it looks empty? It just console logs a blank line...is this expected?
Perhaps the above code is the wrong way entirely, essentially on enter I want to grab whatever value has been input into the search field...

Related

Need to evaluate content in drop-down in Javascript

As stated in the topic I need to evaluate two fields, one from a drop-down menu item, and one for a text input type field. both in HTML of course. I want to test if the fields are empty, zero, whatever in that context.
I have tried to alter the code, but cannot seem to find the right code.
$(document).ready(function() {
$(function() {
$("#companyDialog").dialog({
autoOpen: false
});
$("#companyButton").on("click", function() {
$("#companyDialog").dialog("open");
});
});
// Validating Form Fields.....
$("#companySubmit").click(function(e) {
var comnpanyname = $("#companyname").val();
var editcompanyscombo = $("#editcompanyscombo").val();
if (companyname === '' || editcompanyscombo === '') {
alert("Please fill all fields marked with an *!");
e.preventDefault();
} else if (editcompanyscombo === '0') {
alert("Select comany to update!");
e.preventDefault();
} else {
alert("Form Submitted Successfully.");
}
});
});
<div class="container">
<div class="main">
<div id="companyDialog" title="Edit company">
<form action="" method="post">
<## CompanyEditCombo ##><br>
<label>New company name:</label>
<input id="companyname" name="companyname" type="text">
<input id="companySubmit" type="submit" value="Submit">
</form>
</div>
<input id="companyButton" type="button" value="Open Company Edit Dialog Form">
</div>
</div>
The fields pop up, but they do not alert if the values are zero or empty.
So far I could see from these snippets, please replace === '' and === '0' by == null
(Double equality comparison operator does not aimed to compare the types. That is why, one should use it because null is type object. s. Developer Mozilla)

Enter key doesn't activate button

I have a form with one field that the user needs to type into, and a button underneath that when clicked, does some jQuery and hides the login-form. But when I hit enter after typing something in, the page refreshes...
There's part of me that thinks it doesn't need to be an <input> or a <form>
I don't actually need to post anything. I have tried changing the input to a <button> which completely ruins my styling and still doesn't work. What's the best way of getting round this?
<div class="login-page">
<div class="form">
<form class="login-form" method="POST">
<!-- user inputs -->
<p class="phc">PHC:</p><input type="text" id="username" placeholder="Enter Your PHC Here" />
<!-- your submit button -->
<input class="login" type="button" id="submit" value="login">
</div>
True, Adam. If the form does not contain the type submit button, a keypress event has to be added manually. Otherwise Enter will act as the Accept Button on the form.
You need to attach keypress event to the form or at least the field. For convenience, you also need to combine the callback functions into one.
$('#username').on('keypress', function(event){
var code = event.keyCode || event.which;
if(code == 13){
// submit the form.
}
});
$('#username').on('keypress', function(event){
var code = event.keyCode || event.which;
if(code == 13){
console.log('Submitting form');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="login-form" method="POST">
<p class="phc">PHC:</p><input type="text" id="username" placeholder="Enter Your PHC Here" />
<input class="login" type="button" id="submit" value="login">
</form>
If the enter key is pressed when focused to an input field inside a form that has a submit button, the default browser behaviour is to fire a submit event on that form. You can prevent this happening by either:
return false;
or
e.preventDefault();
Full code:
$('.login-form').on('submit', function() {
return false;
});
Fiddle: https://jsfiddle.net/nc1e2gm6/
Bear in mind that if you go down the route of using e.preventDefault(); instead or return false;, you need to pass the e variable from the function call, like:
$('.login-form').on('submit', function(e) { ...
Don't think i explained it very well but i have fixed it, the enter key now activates the submit button rather than refresh the page.
$("form").submit(function() { return false; });
$(document).ready(function(){
$('#username').keypress(function(e){
if(e.keyCode==13)
$('#submit').click();
});
});

Display Search when any key is pressed

I'm currently in the process of implementing a search similar to Designspiration. When you're browsing the website and press any key the search field appears with your key already within it.
I'm already halfway in implementing this, just can't figure out how to do any keystroke. Below is what I've got so far which makes a full screen search appear when a button is clicked.
Jquery
$(function () {
$('a[href="#search"]').on('click', function(event) {
event.preventDefault();
$('#search').addClass('open');
$('#search > .search-container > form > input[type="search"]').focus();
});
$('#search, .search-container, #search button.close').on('click keyup', function(event) {
if (event.target == this || event.target.className == 'close' || event.keyCode == 27) {
$(this).removeClass('open');
}
});
});
HTML
<div id="search">
<button type="button" class="close">×</button>
<div class="search-container">
<span>Type to start Searching</span>
<form class="search" method="get" action="<?php echo home_url(); ?>" role="search">
<input class="search-input" type="search" name="s" placeholder="" autocomplete="off">
</form>
</div>
</div>
How would I go about implementing search, so when a user just starts typing on the website the search box appears and the user starts typing within it?
Any help would be brilliant.
how about this? DEMO
$('#searchPage').fadeOut(0);
var isTypingInput=false,
isSearching=false;
$('input').not('#theSearch').focus(function(){
isTypingInput=true;
});
$('input').not('#theSearch').blur(function(){
isTypingInput=false;
});
$(document).on('keyup',function(e){
if(!isTypingInput && !isSearching){
if(/([a-zA-Z0-9])+/.test(String.fromCharCode(e.which))){
$('#searchPage').fadeIn(200);
$('#theSearch').focus().val(String.fromCharCode(e.keyCode));
isSearching=true;
}
}
});
$('#searchPage').click(function(e){
if($('#theSearch').is(e.target)) return false;
$('#searchPage').fadeOut(200);
isSearching=false;
});
you'll see that if you type inside the input on the page, the search will not appear.
also you can close the search page by clicking somewhere other than the searching input.
http://jsfiddle.net/rblakeley/8utrsfgp/
jQuery
$(function () {
var $field = $('.search-container input'),
character;
$(window).on('keyup', function (event) {
if ($(event.target).is('input, textarea')) return;
character = String.fromCharCode(event.keyCode);
if (!$field.val().length) {
$field.focus().val(character);
}
});
});
This isn't bullet-proof but it's a starting point.

How to remove the focus on a form field when the user presses up or down arrow key?

I have a webpage with autofocus of search form field. I want to remove the focus on the form field when a user presses up or down arrow key so that he can scroll down the page without clicking anywhere on the page. A perfect example of this kind of UX is www.quora.com. How do i do that?
I have tried doing this:
<script type="text/javascript">
$(document).ready(function(){
$("#search").blur();
});
</script>
But, it just removes the focus immediately after the page loads. How do i make it lose focus only when the user presses up or down arrow keys?
My html form field is as follows:
<div class="input-group">
<input class="form-control" id="search" placeholder="" autocomplete="off" type="text" style="border-right:0" autofocus>
<span class="input-group-addon search-addon"><span class="glyphicon glyphicon-search"></span></span>
</div>
try this jQuery :
With autofocus
$(function(){
$('#search').keydown(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code==38 || code==40){
$(this).focusout();
}
});
});
Without autofocus
$(function(){
$(document).keyup(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code!=38 && code!=40){
$('#search').focus();
}
});
});
Arrow Up : 38
Arrow Down: 40
You have to handle keyup event of user.
Form:
<div class="input-group">
<input class="form-control" id="search" placeholder="" autocomplete="off" type="text" style="border-right:0">
<span class="input-group-addon search-addon"><span class="glyphicon glyphicon-search"></span></span>
</div>

Put label next to the input

I have a simple case. I want two things.
Put label next to the input.
Some sort of validation, only digit number for the text box.
The corresponding link is here.
Now the input is below the label.
My code:
<div id="generatePinsDialog" title="Generate New PINs">
<label style="display: inline-block; width: 400px;">
How many?</label>
<input id="newInmateCount" type="text" size="25" value="Enter the number!" />
<br />
<select>
<option value="sameAsID">Same as ID</option>
<option value="appendID">AppendID</option>
</select>
Demo: http://jsfiddle.net/GCtPE/25/
label, input { display: inline-block; }
For verification you will have to use javascript since HTML5 isn't fully supported by all browsers. HTML5 is pretty cool though.
First, remove the "inline-block" from your label and add the for attribute like so:
<label for="newInmateCount" style="width: 400px;">How many?</label>
As for the input, do this for numeric only:
$("#newInmateCount").keydown(function(e) {
if (e.which == 8 || e.which == 46) return true; // for backspace and delete
if (e.which < 48 || (e.which > 57 && e.which < 96) || e.which > 105) return false;
});
See your jsFiddle Updated
Remove the display: inline-block. That is causing the input filed to go to new line.
You this js function to validate just digits, call it onkeypress event of the input field or bind it with onkeydown event
function onlyNumbers(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
jsFiddle demo
to put the label next to the input, change display:inline-block; to display:inline, or decrease the width:400px to a lower value until you acheive the positioning you want. for validation you need to do some reading on regular expressions
jsfiddle here
The input was so far to the right because you set the width of the label to 400px, I just removed that and it looks fine now. Also added some quick validation, you'd obviously have to run the validation when the form is submitted.
<div id="generatePinsDialog" title="Generate New PINs">
<label style="display: inline-block;">
How many?</label>
<input id="newInmateCount" type="text" size="25" value="Enter the number!" />
<br />
<select>
<option value="sameAsID">Same as ID</option>
<option value="appendID">AppendID</option>
</select>
</div>​
And the JS is below:
if($('#newInmateCount').val() != "") {
var value = $('#newInmateCount').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(!intRegex.test(value)) {
errors += "Field must be numeric.<br/>";
success = false;
}
} else {
errors += "Field is blank.</br />";
success = false;
}​
On-submit validation is pretty easy with jQuery. Here's an example. If you want to keep it from ever having something other than numbers in it, you can go with an onchange or onkeyup event and simply strip the numbers from the input.
For the positioning, try inline instead of inline-block.

Categories

Resources